diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index aebc72fc..420ebca7 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -52,11 +52,6 @@ "source": "./plugins/aem/project-management", "description": "Project lifecycle management for AEM Edge Delivery Services" }, - { - "name": "aem-forms", - "source": "./skills/aem/forms", - "description": "Skills for building AEM Adaptive Forms through AI conversation" - }, { "name": "app-builder", "source": "./plugins/app-builder", diff --git a/.gitignore b/.gitignore index 4baea143..a500705a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,46 +1,15 @@ -# ── Dependencies ───────────────────────────────────────── +# Dependencies node_modules/ -# ── Python ─────────────────────────────────────────────── -__pycache__/ -*.pyc -*.pyo -*.egg-info/ -.venv/ -venv/ -*.egg -pip-wheel-metadata/ - -# ── Build / Distribution ──────────────────────────────── -dist/ -build/ -!skills/**/build/ -*.whl - -# ── Test / Coverage ────────────────────────────────────── -.pytest_cache/ -.coverage -htmlcov/ -*.cover - -# ── Credentials & Environment ──────────────────────────── -.env -.env.* -!.env.example - -# ── OS Files ───────────────────────────────────────────── +# OS files .DS_Store -Thumbs.db -# ── Editor / IDE ───────────────────────────────────────── +# Editor files *.swp *.swo *~ -.idea/ -.vscode/ -*.code-workspace -# ── Temporary Files ────────────────────────────────────── +# Temporary files drafts/tmp/ # Release artifacts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1a630f3a..af6f3a59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,17 +31,6 @@ For other contributors, a maintainer of the project has to approve the pull requ To contribute a new skill, follow the format described in the [Agent Skills specification](https://agentskills.io). When your skill is ready, open a pull request and ping [#agentskills](https://adobe.enterprise.slack.com/archives/C0APTKDNPEY) on Slack to get a review. -### Skill Architecture - -For skill trees with 5+ skills — especially those with routing, orchestration, or phased workflows — follow the architectural patterns in the [Skill Architecture Guide](docs/skill-architecture/README.md). It provides templates for: - -- **[Skill Router](docs/skill-architecture/skill-router-template.md)** — SKILL.md files that dispatch to sub-skills -- **[Directory Structure](docs/skill-architecture/directory-structure.md)** — standard layout for flat, grouped, and deep skill trees -- **[Routing Table](docs/skill-architecture/routing-table-template.md)** — offloaded routing logic for complex routers -- **[Guidelines](docs/skill-architecture/guidelines-template.md)** — cross-cutting constraints shared across multiple skills - -These patterns extend the agentskills.io spec with conventions for keeping routers lean (< 100 lines), offloading heavy content to `assets/`, and organizing skills into registries and domains. - ## Quality Checks PRs go through three tiers of quality checks: diff --git a/README.md b/README.md index bbf5713c..7c7dc12a 100644 --- a/README.md +++ b/README.md @@ -93,31 +93,6 @@ Handover documentation and PDF guides generation for AEM Edge Delivery Services | `whitepaper` | Create professional PDF whitepapers from Markdown | | `auth` | Authenticate with AEM Config Service API | -### AEM Forms - -Turn natural language into production AEM Adaptive Forms. A plan-driven skill gateway with 16 skills across 6 domains. - -**Quick Start:** -```bash -# Say: "Set up a new AEM Forms workspace for my project." -# Then: "Here's the requirements doc for my form. Build it." -``` - -The **forms-orchestrator** routes intents through a 6-step algorithm — it generates plans from requirements via a Planner, resolves skills via a Domain Registry, and executes them. For single tasks it routes directly to the matching domain. - -#### Domains - -| Domain | Skills | -|--------|--------| -| `analysis` | `analyze-requirements`, `analyze-v1-form`, `create-screen-doc`, `review-screen-doc` | -| `build` | `scaffold-form`, `create-form`, `create-component` | -| `logic` | `add-rules`, `create-function`, `optimize-rules` | -| `integration` | `manage-apis` | -| `infra` | `setup-workspace`, `sync-forms`, `sync-eds-code`, `git-sandbox` | -| `context` | `manage-context` | - -**Requirements:** Node.js 18+, Python 3.10+, `git` on PATH. The plugin manages its own Python virtual environment — dependencies are installed automatically on first use. - ### AEM as a Cloud Service — Create Component The `create-component` skill creates complete AEM components following Adobe best practices for AEM Cloud Service and AEM 6.5. It covers: @@ -268,23 +243,74 @@ plugins/ │ │ │ └── plugin.json │ │ └── skills/ │ │ ├── best-practices/ +│ │ │ ├── README.md +│ │ │ ├── SKILL.md +│ │ │ └── references/ │ │ ├── migration/ +│ │ │ ├── README.md +│ │ │ ├── SKILL.md +│ │ │ ├── references/ +│ │ │ └── scripts/ │ │ ├── ensure-agents-md/ +│ │ │ ├── SKILL.md +│ │ │ └── references/ +│ │ │ ├── AGENTS.md.template +│ │ │ └── module-catalog.md │ │ ├── create-component/ +│ │ │ ├── SKILL.md +│ │ │ ├── assets/ +│ │ │ └── references/ │ │ ├── aem-workflow/ +│ │ │ ├── SKILL.md +│ │ │ ├── workflow-model-design/ +│ │ │ ├── workflow-development/ +│ │ │ ├── workflow-triggering/ +│ │ │ ├── workflow-launchers/ +│ │ │ ├── workflow-debugging/ +│ │ │ ├── workflow-triaging/ +│ │ │ └── workflow-orchestrator/ │ │ └── dispatcher/ +│ │ ├── SKILL.md +│ │ ├── config-authoring/ +│ │ ├── technical-advisory/ +│ │ ├── incident-response/ +│ │ ├── performance-tuning/ +│ │ ├── security-hardening/ +│ │ └── workflow-orchestrator/ │ └── 6.5-lts/ │ ├── .claude-plugin/ │ │ └── plugin.json │ └── skills/ │ ├── aem-workflow/ +│ │ ├── SKILL.md +│ │ ├── workflow-model-design/ +│ │ ├── workflow-development/ +│ │ ├── workflow-triggering/ +│ │ ├── workflow-launchers/ +│ │ ├── workflow-debugging/ +│ │ ├── workflow-triaging/ +│ │ └── workflow-orchestrator/ │ ├── aem-replication/ +│ │ ├── README.md +│ │ ├── SKILL.md +│ │ ├── configure-replication-agent/ +│ │ ├── replicate-content/ +│ │ ├── replication-api/ +│ │ └── troubleshoot-replication/ │ ├── ensure-agents-md/ │ └── dispatcher/ +│ ├── SKILL.md +│ ├── config-authoring/ +│ ├── technical-advisory/ +│ ├── incident-response/ +│ ├── performance-tuning/ +│ ├── security-hardening/ +│ └── workflow-orchestrator/ ├── app-builder/ │ ├── .claude-plugin/ │ │ └── plugin.json │ └── skills/ +│ ├── _shared/ │ ├── appbuilder-project-init/ │ ├── appbuilder-action-scaffolder/ │ ├── appbuilder-ui-scaffolder/ @@ -293,21 +319,6 @@ plugins/ │ └── appbuilder-cicd-pipeline/ └── creative-cloud/ └── adobe-for-creativity/ -skills/ -└── aem/ - └── forms/ - ├── .claude-plugin/ - │ └── plugin.json - ├── pyproject.toml - ├── setup.sh - ├── forms-orchestrator/ - │ ├── SKILL.md - │ ├── assets/ - │ ├── scripts/ - │ └── references/ - │ ├── planner/ - │ └── domain-registry/ - └── tests/ ├── .claude-plugin/ │ └── plugin.json ├── skills/ diff --git a/docs/skill-architecture/README.md b/docs/skill-architecture/README.md deleted file mode 100644 index 8b4fe140..00000000 --- a/docs/skill-architecture/README.md +++ /dev/null @@ -1,357 +0,0 @@ ---- -name: skill-architecture -description: > - Architectural patterns and templates for building multi-skill systems. - Extends the agentskills.io specification with patterns for skill routers, - routing tables, guidelines, and directory structure conventions. ---- - -# Skill Architecture Guide - -This guide defines **architectural patterns** for organizing complex multi-skill systems. It extends the [agentskills.io specification](https://agentskills.io) — which defines the per-skill format (`SKILL.md`, `scripts/`, `references/`, `assets/`) — with patterns for composing skills into larger systems. - -> **When do you need this?** If your skill tree has 5+ skills and any form of routing, orchestration, or phased execution, these patterns will help you keep it consistent, lean, and maintainable. - ---- - -## Skill Types - -Every SKILL.md and asset file declares a `type` in its frontmatter. The type is the single most important field — it tells contributors and agents what role this file plays without reading the body. - -### SKILL.md Types - -These types apply to SKILL.md files — the nodes in a skill tree. - -| Type | Role | Routes? | Implements? | Template | -|------|------|---------|-------------|----------| -| `router` | Top-level gateway that dispatches to sub-skills, registries, or other routers | Yes | No | [skill-router-template.md](skill-router-template.md) | -| `domain` | Groups related skills under a named domain, routes intents to leaf skills | Yes | No | Specialization — e.g., domain-template.md | -| `skill` | Leaf node that does actual implementation work | No | Yes | *(none — leaf skills are freeform per agentskills.io)* | - -**Key rules:** -- Every SKILL.md **must** have exactly one `type` -- `router` and `domain` types never implement — they dispatch only -- Only `type: skill` files do real work (create files, run scripts, modify code) -- The `type` field goes right after `description` in the frontmatter - -> **Planner pattern:** A planner is a `type: skill` that generates plan files from user requirements. It's not a separate type — it's a specialization of `skill`. See [Plan-Driven Workflows](#plan-driven-workflows). - -### Asset File Types - -These types apply to asset files (`.md` files in `assets/`) — supporting documents offloaded from routers. - -| Type | Role | Lives In | Template | -|------|------|----------|----------| -| `routing-table` | Routing algorithm offloaded from a router SKILL.md | `assets/routing-table.md` | [routing-table-template.md](routing-table-template.md) | -| `guidelines` | Cross-cutting constraints shared across multiple skills | `assets/guidelines.md` | [guidelines-template.md](guidelines-template.md) | -| `plan-template` | Schema and template for plan files generated by a planner | `assets/plan-template.md` | planner-template.md | -| `plan-type` | Reference for a specific plan type (structure, workflow, logic, etc.) | `references/-plan.md` | *(freeform)* | -| `strategy` | Plan generation strategy — defines how to decompose requirements into plans | `references/default-strategy.md` | *(freeform)* | - -> Paths in the "Lives In" column are relative to the skill that owns the asset. - -Asset files are loaded on demand — they don't consume tokens until explicitly referenced. - -### Frontmatter Examples - -A leaf skill: -``` ---- -name: add-rules -description: > - Add business rules to AEM Adaptive Forms. -type: skill -license: Apache-2.0 ---- -``` - -A router: -``` ---- -name: forms-orchestrator -description: > - Skill Gateway for AEM Forms. Routes to domains. -type: router -license: Apache-2.0 ---- -``` - -A domain: -``` ---- -name: analysis -description: > - Domain router for analysis & documentation skills. -type: domain -license: Apache-2.0 ---- -``` - -A planner: -``` ---- -name: planner -description: > - Plan generator. Decomposes user requirements into ordered, executable plans. -type: skill -license: Apache-2.0 ---- -``` - ---- - -## Architectural Layers - -A complex skill system stacks types in layers, from top to bottom: - -``` -┌─────────────────────────────────────┐ -│ type: router │ ← entry point, pure dispatcher -│ (orchestrator / gateway) │ -└──────────────────┬──────────────────┘ - │ - ┌──────────┴──────────┐ - ▼ ▼ -┌──────────────┐ ┌──────────────┐ -│ type: skill │ │ type: router │ ← planner (generates plans) -│ (planner) │ │ (domain │ OR domain registry -│ │ │ registry) │ -└──────┬───────┘ └──────┬───────┘ - │ │ - ▼ ▼ - Plan files ┌──────────────┐ - plans// │ type: domain │ ← domain routers - NN-.md └──────┬───────┘ - │ - ▼ - ┌──────────────┐ - │ type: skill │ ← leaf nodes — do the actual work - └──────────────┘ - -Supporting files (loaded on demand): - type: routing-table → assets/routing-table.md - type: guidelines → assets/guidelines.md - type: plan-template → assets/plan-template.md - type: plan-type → references/<type>-plan.md - type: strategy → references/default-strategy.md -``` - -Not every skill tree needs all layers. Use what fits: - -| Complexity | Recommended Types | -|------------|-------------------| -| 1–4 skills | `skill` only — flat, no routing needed | -| 5–10 skills | One `router` at the top + `skill` leaves | -| 10–20 skills | `router` → `domain` → `skill` (group skills into domains) | -| 20+ skills or phased workflows | `router` → `skill` (planner) + `router` (domain registry) → `domain` → `skill` | - ---- - -## Templates - -Each type has a corresponding template that defines the required sections and structure. - -| Template | Produces Type | Purpose | -|----------|--------------|---------| -| [**Skill Router Template**](skill-router-template.md) | `router` | SKILL.md for any generic dispatcher (orchestrator, registry) | -| [**Routing Table Template**](routing-table-template.md) | `routing-table` | Asset file for routing logic offloaded from a router | -| [**Guidelines Template**](guidelines-template.md) | `guidelines` | Asset file for cross-cutting constraints | -| [**Directory Structure**](directory-structure.md) | *(layout guide)* | Standard directory layout for all types | - -Skill trees may also define **specialized templates** that extend the generic router template for specific types: - -| Specialization | Produces Type | Defined By | Location | -|---------------|--------------|-----------|----------| -| Domain Router Template | `domain` | `aem/forms` | `domains/assets/templates/domain-template.md` | -| Planner Template | `skill` (planner) | `aem/forms` | `planner/SKILL.md` | -| Plan Template | `plan-template` | `aem/forms` | `planner/assets/plan-template.md` | -| Plan Type Reference | `plan-type` | `aem/forms` | `planner/references/<type>-plan.md` | -| Strategy | `strategy` | `aem/forms` | `planner/references/default-strategy.md` | - -> **Leaf skills** (`type: skill`) don't need a template — they follow the freeform [agentskills.io](https://agentskills.io) format. Keep them under 500 lines / 5,000 tokens. - ---- - -## Key Principles - -### 1. Routers are lean - -Router SKILL.md files (`type: router`, `type: domain`) should be **under 100 lines**. They contain: -- YAML frontmatter (with `type`) -- A routing diagram or table (the core dispatch logic) -- Links to `assets/` files for everything else - -Heavy content goes into typed asset files: -- Routing algorithms → `assets/routing-table.md` (`type: routing-table`) -- Constraints & conventions → `assets/guidelines.md` (`type: guidelines`) -- Contribution guides → `assets/contribution-guide.md` -- Templates → `assets/templates/` - -### 2. Progressive disclosure - -Following the agentskills.io principle, skills load in layers: - -| Layer | Loaded | Token budget | -|-------|--------|-------------| -| `name` + `description` + `type` (frontmatter) | At startup, for all skills | ~100 tokens | -| SKILL.md body (instructions) | When skill is activated | < 5,000 tokens | -| `references/`, `assets/`, `scripts/` | On demand during execution | As needed | - -This is why routers stay lean — they're loaded on every routing decision. Asset files (`type: routing-table`, `type: guidelines`) are loaded only when their content is needed. - -### 3. Consistent directory conventions - -| Directory | Purpose | Contains Types | -|-----------|---------|---------------| -| `references/` | Sub-skills or reference documentation | `router`, `domain`, `skill` | -| `assets/` | Static resources offloaded from SKILL.md | `routing-table`, `guidelines`, templates, catalogs | -| `scripts/` | Executable code (bash, python, JS) | N/A | - -### 4. Naming - -- Directory names = `name` field in frontmatter (per agentskills.io spec) -- Lowercase, hyphens only: `analyze-requirements`, `build-journey` -- Router SKILL.md headings include their role: `# <Name> — Domain Router`, `# <Name> — Domain Registry` - ---- - -## Type Relationships - -How the types interact in a running system: - -``` -User Intent - │ - ▼ -[type: router] ←── reads [type: routing-table] to decide - │ - ├──→ has requirements, no plans? ──→ [type: skill / planner] generates plans - │ │ │ - │ │ plan files at - │ │ plans/<journey>/NN-<title>.md - │ │ │ - │ ▼ ▼ - ├──→ plan exists? ──→ read plan step → resolve skill via domain registry - │ │ - │ ▼ - ├──→ [type: router] ←── registry resolves domain/skill - │ │ - │ ▼ - └──→ [type: domain] ←── reads [type: guidelines] for constraints - │ - ▼ - [type: skill] ←── does the actual work -``` - -| From | To | Relationship | -|------|----|-------------| -| `router` | `router` | Dispatches to sub-routers (registries) | -| `router` | `domain` | Routes intents directly to a domain | -| `router` | `skill` (planner) | Routes to planner when requirements exist but no plans | -| `skill` (planner) | plan files | Generates ordered plan files from requirements | -| `router` | plan files | Reads and executes plan steps sequentially | -| plan step | `domain` | Each plan step declares a domain + skill to invoke | -| `domain` | `skill` | Routes to the leaf skill that implements | -| `router` / `domain` | `routing-table` | Reads routing logic (asset, loaded on demand) | -| `router` / `domain` | `guidelines` | Reads constraints (asset, loaded on demand) | - ---- - -## Plan-Driven Workflows - -For multi-phase or complex workflows, a **planner** dynamically generates plans from user requirements at runtime. Rather than relying on a fixed phase graph, the planner analyzes the specific requirements and produces a tailored sequence of plans — each scoped to a feature slice and executable via the domain registry. - -### Characteristics - -| Aspect | Description | -|--------|-------------| -| Workflow definition | Dynamic — generated from requirements at runtime | -| Adaptability | Planner adapts plan count and scope to the specific requirements | -| Plan count | Variable (1–15 plans per journey) | -| Ordering | Sequential with explicit dependencies between plans | -| Scope per plan | Feature-scoped — each plan is a vertical slice (build + logic + integration) | -| Best for | Complex, variable-scope work (e.g., building forms from diverse requirements) | - -### Plan Architecture - -``` -Requirements (journey docs, Screen.md, screenshots) - │ - ▼ -┌────────────────────────────────┐ -│ Planner (type: skill) │ -│ Resolves strategy │ -│ Analyzes requirements │ -│ Decomposes into ordered plans │ -└─────────────┬──────────────────┘ - │ - ▼ -┌────────────────────────────────┐ -│ Plan Files │ -│ plans/<journey>/ │ -│ ├── 01-form-structure.md │ -│ ├── 02-workflow-branch-a.md │ -│ ├── 03-api-integration.md │ -│ └── 04-error-handling.md │ -└─────────────┬──────────────────┘ - │ - ▼ -┌────────────────────────────────┐ -│ Orchestrator executes plans │ -│ sequentially, resolving each │ -│ step via Domain Registry │ -└────────────────────────────────┘ -``` - -### Plan Types - -Plans are not typed explicitly — their type emerges from which specification sections and skills they use. Common plan types: - -| Type | Purpose | Primary Skills | -|------|---------|----------------| -| Structure | Form skeleton — panels, fields, basic validations | `create-form`, `scaffold-form` | -| Workflow | Specific user flow or conditional branch | `create-form`, `add-rules`, `create-function` | -| Logic | Cross-cutting validations and business rules | `add-rules`, `create-function` | -| Integration | API wiring — data loading, save/submit, external services | `manage-apis`, `create-function`, `add-rules` | -| Infrastructure | Error handling, session mgmt, toasts, sanitization | `create-function`, `add-rules` | - -### Plan Conventions - -| Property | Convention | -|----------|-----------| -| File path | `plans/<journey>/NN-<short-title>.md` | -| Numbering | Zero-padded two digits: `01`, `02`, ..., `10`, `11` | -| Max per journey | 15 — if more are needed, the journey is too complex; split it | -| Execution | Sequential — each plan declares dependencies explicitly | -| Scope | Feature-scoped — a single plan can invoke multiple skills across domains | - -### Strategy - -The planner uses a configurable strategy to decide how to decompose requirements: - -| Priority | Location | Description | -|----------|----------|-------------| -| 1 (highest) | `plans/custom-strategy.md` | User-provided override | -| 2 (default) | `references/default-strategy.md` | Default workflow-focused decomposition | - -### Key Files in a Plan-Driven System - -| What | Where | -|------|-------| -| Planner | `references/planner/SKILL.md` | -| Plan template | `references/planner/assets/plan-template.md` | -| Default strategy | `references/planner/references/default-strategy.md` | -| Plan type references | `references/planner/references/<type>-plan.md` | -| Generated plan files | `plans/<journey>/NN-<title>.md` | -| User strategy override | `plans/custom-strategy.md` | - ---- - -## Getting Started - -1. **New skill tree?** Start with [Directory Structure](directory-structure.md) to set up the layout. -2. **Need a dispatcher?** Use the [Skill Router Template](skill-router-template.md) — produces `type: router`. -3. **Router getting long?** Offload routing logic to a [Routing Table](routing-table-template.md) (`type: routing-table`) and constraints to a [Guidelines](guidelines-template.md) file (`type: guidelines`). -4. **Need to group skills?** Create domain routers (`type: domain`) — use a domain template if your skill tree has one, or adapt the generic router template. -5. **Need multi-phase workflows?** Use a plan-driven approach — create a planner (`type: skill`) that generates plans from requirements. See [Plan-Driven Workflows](#plan-driven-workflows). -6. **Building a leaf skill?** Just follow [agentskills.io](https://agentskills.io) — set `type: skill` and keep it under 500 lines. \ No newline at end of file diff --git a/docs/skill-architecture/directory-structure.md b/docs/skill-architecture/directory-structure.md deleted file mode 100644 index 9aa40e77..00000000 --- a/docs/skill-architecture/directory-structure.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -name: directory-structure -description: > - Standard directory layout conventions for multi-skill systems. - Covers flat, grouped, and deep skill trees with type annotations. -type: guidelines ---- - -# Skill Directory Structure - -How to organize a skill tree's files and folders. Follows the [agentskills.io specification](https://agentskills.io) for per-skill layout, with conventions for multi-skill composition. - -Every SKILL.md and asset file declares a `type` — see the [Skill Architecture Guide](README.md) for the full type reference. - ---- - -## Per-Skill Layout (agentskills.io standard) - -Every skill is a directory with at minimum a `SKILL.md`: - -``` -<skill-name>/ -├── SKILL.md # type: skill | router | domain -├── references/ # Sub-skills or reference docs -│ ├── <sub-skill>/ -│ │ └── SKILL.md # type: skill | router | domain -│ └── <reference>.md -├── assets/ # Static resources, offloaded content -│ ├── guidelines.md # type: guidelines -│ ├── routing-table.md # type: routing-table -│ └── templates/ -│ └── <template>.md -├── scripts/ # Executable code -│ └── <script>.sh -├── eval/ # Test fixtures and evaluation plans -│ ├── eval-plan.md -│ └── fixtures/ -└── plans/ # Generated plan files (plan-driven workflows) - └── <journey>/ - ├── 01-<title>.md - └── 02-<title>.md -``` - -**Rules:** -- `name` in SKILL.md frontmatter **must match** the directory name -- `type` in SKILL.md frontmatter **must match** the skill's role (see below) -- SKILL.md body should be **under 500 lines / 5,000 tokens** (routers: under 100 lines) -- Use relative paths for all file references - ---- - -## Type by Layer - -In a multi-layer skill tree, each layer uses specific types: - -``` -Level 0 (entry point) → type: router (orchestrator / gateway) -Level 1 (registries) → type: router (domain registry) - → type: skill (planner — generates plans dynamically) -Level 2 (grouping) → type: domain (domain routers) -Level 3 (implementation) → type: skill (leaf skills — do the work) - -Supporting files at any level: - assets/routing-table.md → type: routing-table - assets/guidelines.md → type: guidelines - assets/plan-template.md → type: plan-template (plan-driven only) - references/*-plan.md → type: plan-type (plan-driven only) - references/*-strategy.md → type: strategy (plan-driven only) -``` - -| Level | Type | Routing? | Implementation? | Max Lines | -|-------|------|----------|-----------------|-----------| -| 0 | `router` | Yes | No | 100 | -| 1 | `router` | Yes | No | 100 | -| 2 | `domain` | Yes | No | 100 | -| 1 | `skill` (planner) | No | Yes (generates plans) | 500 | -| 3 | `skill` | No | Yes | 500 | -| Any | `routing-table` | N/A | N/A | No limit | -| Any | `guidelines` | N/A | N/A | No limit | -| Any | `plan-template` | N/A | N/A | No limit | -| Any | `plan-type` | N/A | N/A | No limit | -| Any | `strategy` | N/A | N/A | No limit | - ---- - -## Flat Layout (1–4 skills) - -All skills are `type: skill`. No router needed: - -``` -my-skill-tree/ -├── .claude-plugin/ -│ └── plugin.json -└── skills/ - ├── skill-a/ - │ └── SKILL.md # type: skill - ├── skill-b/ - │ └── SKILL.md # type: skill - └── skill-c/ - └── SKILL.md # type: skill -``` - -Each skill is standalone and triggered independently by its `description` field. - ---- - -## Grouped Layout (5–10 skills) - -Add a `type: router` at the top that dispatches to `type: skill` leaves: - -``` -my-skill-tree/ -├── .claude-plugin/ -│ └── plugin.json -└── skills/ - └── <orchestrator>/ - ├── SKILL.md # type: router — dispatches to sub-skills - ├── assets/ - │ ├── routing-table.md # type: routing-table (if routing is complex) - │ └── guidelines.md # type: guidelines (if cross-cutting rules exist) - └── references/ - ├── skill-a/ - │ └── SKILL.md # type: skill - ├── skill-b/ - │ └── SKILL.md # type: skill - └── skill-c/ - └── SKILL.md # type: skill -``` - -The `type: router` SKILL.md is lean (< 100 lines) and links to `assets/` for details. - ---- - -## Deep Layout (10+ skills, multi-phase workflows) - -The full type stack: `router` → `router` (registries) + `skill` (planner) → `domain` → `skill`: - -``` -my-skill-tree/ -├── .claude-plugin/ -│ └── plugin.json -└── skills/ - └── <orchestrator>/ - ├── SKILL.md # type: router (gateway) - ├── assets/ - │ ├── routing-table.md # type: routing-table - │ └── guidelines.md # type: guidelines - │ - ├── references/ - │ ├── <planner>/ - │ │ ├── SKILL.md # type: skill (plan generator) - │ │ ├── assets/ - │ │ │ └── plan-template.md # type: plan-template - │ │ └── references/ - │ │ ├── default-strategy.md # type: strategy - │ │ ├── structure-plan.md # type: plan-type - │ │ ├── workflow-plan.md # type: plan-type - │ │ ├── logic-plan.md # type: plan-type - │ │ ├── integration-plan.md # type: plan-type - │ │ └── infrastructure-plan.md # type: plan-type - │ │ - │ └── <domain-registry>/ - │ ├── SKILL.md # type: router (registry) - │ ├── assets/ - │ │ ├── skills-catalog.md - │ │ ├── skill-resolution.md - │ │ └── contribution-guide.md - │ └── references/ - │ ├── <domain-a>/ - │ │ ├── SKILL.md # type: domain - │ │ └── references/ - │ │ └── <skill-1>/ - │ │ └── SKILL.md # type: skill (leaf) - │ └── <domain-b>/ - │ ├── SKILL.md # type: domain - │ └── references/ - │ └── ... # type: skill (leaves) - │ - └── plans/ # Generated plan files (at runtime) - └── <journey>/ - ├── 01-form-structure.md - ├── 02-workflow-branch-a.md - ├── 03-api-integration.md - └── 04-error-handling.md -``` - -Key characteristics of the plan-driven deep layout: -- **The planner is a single `type: skill`** that generates plans dynamically at runtime -- **`plans/` directory starts empty** and is populated by the planner based on requirements -- **Plan type references** live under the planner as structured specs for each category of work -- **Strategy files** control decomposition — user can override with `plans/custom-strategy.md` - ---- - -## Convention Summary - -| Convention | Rule | -|------------|------| -| **`type` field** | Every SKILL.md and typed asset file must declare `type` in frontmatter. | -| **`type: router`** | < 100 lines. Route only, never implement. | -| **`type: domain`** | < 100 lines. Route only, never implement. Groups related skills. | -| **`type: skill`** | < 500 lines / 5,000 tokens. Does the actual work. | -| **`type: routing-table`** | Asset file. Routing algorithm offloaded from a router. | -| **`type: guidelines`** | Asset file. Cross-cutting constraints for multiple skills. | -| **`references/`** | Sub-skills (folders with SKILL.md) or reference docs. | -| **`assets/`** | Offloaded content: `routing-table`, `guidelines`, templates, catalogs. | -| **`assets/templates/`** | Templates for creating new items. Each template prescribes a fixed `type`. | -| **`scripts/`** | Executable code. Self-contained, with error handling. | -| **`eval/`** | Test plans and fixtures for evaluating skill quality. | -| **`type: plan-template`** | Asset file. Schema/template for plan files generated by a planner. | -| **`type: plan-type`** | Reference file. Defines spec patterns for a category of plans (structure, workflow, etc.). | -| **`type: strategy`** | Reference file. Plan decomposition strategy (default or custom). | -| **`plans/`** | Generated plan files. Created by the planner at runtime, executed by the orchestrator. | -| **Directory name = `name` field** | Always. No exceptions. | - ---- - -## Anti-Patterns - -| Anti-Pattern | Why It's Bad | Fix | -|-------------|-------------|-----| -| Missing `type` in frontmatter | Contributors can't tell what the file does without reading it | Add `type` — it's required | -| `type: router` with > 100 lines | Loaded on every routing decision, wastes tokens | Offload to `type: routing-table` and `type: guidelines` assets | -| `type: skill` that also routes to sub-skills | Violates single-responsibility, bloats the file | Split into `type: router` + `type: skill` | -| `type: domain` that implements logic | Domains are routers — they dispatch, not implement | Move implementation to a `type: skill` leaf | -| Deeply nested references (3+ levels) | Hard to discover, slow to navigate | Flatten or use registries (`type: router`) | -| Guidelines duplicated across skills | Drift, contradictions | Consolidate in `type: guidelines` asset at parent level | -| `resources/` instead of `references/` + `assets/` | Non-standard naming, confuses the discovery model | Rename to standard directories | -| Template without a fixed `type` | Users don't know what type the output file should be | Every template must prescribe a fixed `type` | -| Plans with more than 10 steps | Too much scope in a single plan | Split into two plans along a natural boundary | -| More than 15 plans per journey | Journey is too complex | Decompose the journey into sub-journeys | -| Plan scope defined by skill domain instead of feature | Produces fragmented, hard-to-test increments | Scope plans by feature — each plan can invoke multiple skill domains | \ No newline at end of file diff --git a/docs/skill-architecture/guidelines-template.md b/docs/skill-architecture/guidelines-template.md deleted file mode 100644 index 74f63310..00000000 --- a/docs/skill-architecture/guidelines-template.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -name: guidelines-template -description: > - Template for guidelines and constraints asset files. Use when cross-cutting - rules apply across multiple skills in a router's tree. -type: guidelines ---- - -# Guidelines Template - -Use this template when you have constraints, conventions, or rules that apply across multiple skills managed by a single router. Instead of duplicating them in each leaf skill, consolidate them in one asset file. - -> **Produces type:** `guidelines` — Asset files created from this template must have `type: guidelines` in their frontmatter. This type signals that the file contains cross-cutting constraints read by `type: router` or `type: domain` SKILL.md files. - -> **Where this file lives:** `<skill>/assets/guidelines.md` -> **Referenced from:** The router's SKILL.md via a markdown link - ---- - -## Template - -Copy and adapt the sections below. - -### Guidelines File - -``` ---- -name: guidelines -description: > - Constraints and conventions for all skills under <router-name>. -type: guidelines ---- - -# <Router Name> — Guidelines - -Cross-cutting rules that apply to all skills in this tree. - ---- - -## Constraints - -Hard rules that must never be violated. - -> **<constraint-id>:** <What is forbidden and why. Be specific.> - -> **<constraint-id>:** <Another constraint.> - -> **<constraint-id>:** <Another constraint.> - ---- - -## Conventions - -Soft rules — preferred patterns that should be followed unless there's a documented reason not to. - -| Convention | Rule | Applies To | -|-----------|------|-----------| -| <convention-name> | <What to do> | <Which skills this applies to> | -| <convention-name> | <What to do> | All skills | - ---- - -## File Locations - -Canonical paths for assets managed by skills in this tree. - -| Asset | Path | Managed By | -|-------|------|-----------| -| <asset-type> | `<canonical/path/pattern>` | `<skill-id>` | -| <asset-type> | `<canonical/path/pattern>` | `<skill-id>` | - ---- - -## Error Handling - -How skills should handle common error conditions. - -| Condition | Action | -|-----------|--------| -| <error condition> | <what to do — halt, prompt user, retry, skip> | -| <error condition> | <what to do> | -``` - ---- - -## When to Use This Template - -| Scenario | Use This? | -|----------|-----------| -| A single skill with its own rules | No — keep rules in the skill's SKILL.md | -| 2–3 skills share a constraint | Maybe — consider a brief note in the parent router | -| 5+ skills share constraints, file conventions, or error handling | **Yes** | -| Rules are getting duplicated across multiple SKILL.md files | **Yes** | -| You need a single source of truth for file paths and conventions | **Yes** | \ No newline at end of file diff --git a/docs/skill-architecture/routing-table-template.md b/docs/skill-architecture/routing-table-template.md deleted file mode 100644 index 361e6e1c..00000000 --- a/docs/skill-architecture/routing-table-template.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -name: routing-table-template -description: > - Template for routing table asset files. Use when a router SKILL.md's - routing logic is too complex to keep inline. -type: routing-table ---- - -# Routing Table Template - -Use this template when your router SKILL.md's routing logic exceeds a simple table — e.g., it has multi-step algorithms, decision trees, precedence rules, or resolution logic. - -> **Produces type:** `routing-table` — Asset files created from this template must have `type: routing-table` in their frontmatter. This type signals that the file contains routing logic offloaded from a `type: router` or `type: domain` SKILL.md. - -> **Where this file lives:** `<skill>/assets/routing-table.md` -> **Referenced from:** The router's SKILL.md via a markdown link - ---- - -## Template - -Copy and adapt the sections below. - -### Routing Algorithm - -``` ---- -name: routing-table -description: > - Routing algorithm for <router-name>. Defines the step-by-step logic - for matching user intents to sub-skills. -type: routing-table ---- - -# Routing Algorithm - -Step-by-step routing logic for `<router-name>`. - ---- - -## Decision Flow - -Describe the routing algorithm as a numbered sequence. Each step is a decision point. - -1. **<Gate / Precondition>** — <condition to check> - - If true → <action: route to skill, halt, prompt user> - - If false → continue to step 2 - -2. **<Check active state>** — <is there an active task/plan/session?> - - If yes → <resume it> - - If no → continue to step 3 - -3. **<Primary match>** — <match intent against primary dispatch table> - - If matched → <route to matched target> - - If no match → continue to step 4 - -4. **<Fallback match>** — <match intent against fallback dispatch table> - - If matched → <route to matched target> - - If no match → continue to step 5 - -5. **<No match>** — Ask user to clarify - ---- - -## Dispatch Tables - -### Primary Dispatch - -| Priority | Intent Pattern | Target | Confidence | -|----------|---------------|--------|------------| -| 1 | <pattern> | `<skill-id>` | High | -| 2 | <pattern> | `<skill-id>` | High | -| 3 | <pattern> | `<skill-id>` | Medium — confirm with user | - -### Fallback Dispatch - -| Intent Pattern | Target | -|---------------|--------| -| <broad pattern> | `<skill-id>` | - ---- - -## Precedence Rules - -Define what happens when multiple matches occur. - -| Condition | Resolution | -|-----------|-----------| -| Multiple targets match with equal confidence | Present options to user, let them choose | -| Active state exists + new intent conflicts | Active state takes precedence unless user explicitly overrides | -| Explicit request by name/ID | Always wins, regardless of other rules | - ---- - -## Resolution Logic - -If this router resolves references (e.g., pipeline phases → domain skills), document the resolution algorithm here. - -1. Look up `<key>` in `<table>` → get `<result>` -2. Validate `<result>` exists → if not, halt and report error -3. Route to `<result>` -``` - ---- - -## When to Use This Template - -| Scenario | Use This? | -|----------|-----------| -| Router has a simple intent → skill table (< 10 rows, no precedence) | No — keep inline in SKILL.md | -| Router has multi-step decision logic | **Yes** | -| Router has precedence rules or conflict resolution | **Yes** | -| Router resolves references across registries | **Yes** | -| Multiple dispatch tables (primary + fallback) | **Yes** | -```` diff --git a/docs/skill-architecture/skill-router-template.md b/docs/skill-architecture/skill-router-template.md deleted file mode 100644 index 006ebb91..00000000 --- a/docs/skill-architecture/skill-router-template.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -name: skill-router-template -description: > - Generalized template for SKILL.md files that route user intents - to sub-skills. Routers dispatch — they do not implement. -type: router ---- - -# Skill Router Template - -Use this template for any SKILL.md that dispatches to sub-skills rather than implementing logic itself. This covers orchestrators, domain routers, pipeline registries, and any other routing layer. - -> **Core rule:** A router SKILL.md should be **under 100 lines**. If it's growing beyond that, offload content to `assets/` (see [Routing Table Template](routing-table-template.md) and [Guidelines Template](guidelines-template.md)). - ---- - -## Template - -Copy and fill in the sections below. - -### Frontmatter - -The `type` field in frontmatter declares the skill's architectural role. Always include it. - -| `type` | Use When | -|--------|----------| -| `router` | Any SKILL.md that dispatches to sub-skills (orchestrators, registries, generic routers) | -| `domain` | Domain router — groups related skills under a domain (use domain-template.md instead) | -| `skill` | Leaf skill that does actual work (not a router — don't use this template). Also used for **planners** that dynamically generate plans from requirements — see [Plan-Driven Workflows](README.md#plan-driven-workflows) | - -``` ---- -name: <router-id> -description: > - <One-line purpose. What does this router dispatch? What triggers it?> -type: router -license: Apache-2.0 -metadata: - author: <Author or Organization> - version: "<semver>" ---- -``` - -> **Note:** Generic routers use `type: router`. For domain-specific routers, use the domain template (`type: domain`). For plan-driven workflows, pair this router with a planner (`type: skill`) — see [Plan-Driven Workflows](README.md#plan-driven-workflows). Leaf skills use `type: skill`. - -### Body - -``` -# <Router Name> - -<1–2 sentence description. What this router does and what it does NOT do.> - -> This router **selects** and **routes**. It does not implement. - ---- - -## Routing Table - -First match wins. - -| Intent | Skill | Description | -|--------|-------|-------------| -| <Intent pattern 1> | `<skill-id-1>` | <What this skill does> | -| <Intent pattern 2> | `<skill-id-2>` | <What this skill does> | -| <Intent pattern 3> | `<skill-id-3>` | <What this skill does> | - -> If the intent is ambiguous, present the top matches to the user and let them choose. - ---- - -## Sub-Skills - -| Skill | Path | Purpose | -|-------|------|---------| -| `<skill-id-1>` | [`references/<skill-id-1>/SKILL.md`](references/<skill-id-1>/SKILL.md) | <One-line purpose> | -| `<skill-id-2>` | [`references/<skill-id-2>/SKILL.md`](references/<skill-id-2>/SKILL.md) | <One-line purpose> | - ---- - -## Assets - -Link to offloaded content. Remove rows that don't apply. - -| What | Where | -|------|-------| -| Routing algorithm (detailed) | [`assets/routing-table.md`](assets/routing-table.md) | -| Constraints & conventions | [`assets/guidelines.md`](assets/guidelines.md) | -| Contribution guide | [`assets/contribution-guide.md`](assets/contribution-guide.md) | -| Templates | `assets/templates/` | -``` - ---- - -## Section Reference - -| Section | Required | Purpose | -|---------|----------|---------| -| **Frontmatter** | Yes | Identity, triggers, metadata | -| **Title + Description** | Yes | What this router does (1–2 sentences) | -| **Routing Table** | Yes | The core dispatch logic — intent → skill | -| **Sub-Skills** | Yes | Registry of all sub-skills with paths | -| **Assets** | If offloading | Links to offloaded routing logic, guidelines, templates | - ---- - -## When to Offload to Assets - -| Symptom | Action | -|---------|--------| -| SKILL.md exceeds ~100 lines | Offload the largest section to `assets/` | -| Routing algorithm has multi-step logic, decision trees, or precedence rules | Move to `assets/routing-table.md` | -| Constraints apply across multiple sub-skills | Move to `assets/guidelines.md` | -| Contribution instructions (how to add skills, extend the router) | Move to `assets/contribution-guide.md` | -| Templates for creating new sub-skills | Move to `assets/templates/` | - ---- - -## Examples in This Repo - -| Router | Type | Pattern | Location | -|--------|------|---------|----------| -| Forms Orchestrator | `router` | Top-level gateway → planner + domain registry | `skills/aem/forms/forms-orchestrator/SKILL.md` | -| Domain Registry | `router` | Catalogs domains, resolves plan steps to skills | `skills/aem/forms/forms-orchestrator/references/domain-registry/SKILL.md` | -| Analysis Domain | `domain` | Routes analysis intents to analysis skills | `skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/SKILL.md` | \ No newline at end of file diff --git a/forms-skills-issues.md b/forms-skills-issues.md deleted file mode 100644 index 558b5f36..00000000 --- a/forms-skills-issues.md +++ /dev/null @@ -1,154 +0,0 @@ -Issue 1: ------------------------------------------------------------ -While using forms-sync tool we encounter the following error: - -``` -Error: Missing environment variables: AEM_HOST, AEM_TOKEN -``` - -RCA: The PWD is correct but it's still not finding the .env. Let me check how the tool loads configuration. - ------------------------------------------------------------ -Issue 2: ------------------------------------------------------------ -While using the form transformation tool, we encounter the following error: - -``` -Error: Bash(/Users/anirudhaggar/.claude/plugins/cache/adobe-skills/aem-forms/0.1.0/bin/rule-transform - /Users/anirudhaggar/Documents/aem/codes/adobe-aem-forms/forms-skills-t…) - ⎿  Error: Exit code 1 - Traceback (most recent call last): - File "/Users/anirudhaggar/.claude/plugins/cache/adobe-skills/aem-forms/0.1.0/scripts/rule_coder/bridge/cli/jcr-to-crispr.py", line 17, in <module> - from formsgenailib.core.form import ( - ...<2 lines>... - ) - ModuleNotFoundError: No module named 'formsgenailib' - {"success":false,"error":"Transform error: JCR to CRISPR conversion failed: spawnSync /bin/sh EPIPE","stack":"Error: JCR to CRISPR conversion failed: spawnSync - /bin/sh EPIPE\n at convertJcrToCrispr - (/Users/anirudhaggar/.claude/plugins/cache/adobe-skills/aem-forms/0.1.0/scripts/rule_coder/bridge/cli/transform-form.js:119:15)\n at transformFormJson - (/Users/anirudhaggar/.claude/plugins/cache/adobe-skills/aem-forms/0.1.0/scripts/rule_coder/bridge/cli/transform-form.js:141:21)\n at main - (/Users/anirudhaggar/.claude/plugins/cache/adobe-skills/aem-forms/0.1.0/scripts/rule_coder/bridge/cli/transform-form.js:209:41)\n at Object.<anonymous> - (/Users/anirudhaggar/.claude/plugins/cache/adobe-skills/aem-forms/0.1.0/scripts/rule_coder/bridge/cli/transform-form.js:226:1)\n at Module._compile - (node:internal/modules/cjs/loader:1469:14)\n at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)\n at Module.load - (node:internal/modules/cjs/loader:1288:32)\n at Module._load (node:internal/modules/cjs/loader:1104:12)\n at Function.executeUserEntryPoint [as runMain] - (node:internal/modules/run_main:174:12)\n at node:internal/main/run_main_module:28:49"} -``` -RCA: The error indicates that the Python module `formsgenailib` is missing. This module is likely a dependency for the form transformation tool. I will need to check the installation instructions for the tool and ensure that all required dependencies are installed, possibly via pip or another package manager. - -The issue is that rule-transform can't build the context needed for FUNCTION_CALL rules because the formsgenailib module is missing. Let me fix that dependency. - ------------------------------------------------------------ -Issue 3: ------------------------------------------------------------ -Error: The api-manager looks for specs in a specific directory. Let me create the OpenAPI YAML specs directly and then build the clients. I'll create all 5 API specs. - ------------------------------------------------------------ -Issue 4: ------------------------------------------------------------ -form-sync tool is not used to push the form. The form is not pushed after every plan. We should ask the user if they want to push the form after the plan is generated. If yes, we can run the push command. This will ensure that the form is always in sync with the latest changes and avoid any discrepancies between local and AEM versions. - - ------------------------------------------------------------ -Issue 5: ------------------------------------------------------------ -Build stage was failing in the eds-code PR pipeline due to `package-lock.json` drift. - -What happened: -- `eds-code-sync push` clones the repo, then runs `npm install` to install dependencies (needed so `npm run lint` and `npm run build:json` can execute). -- `npm install` modifies `package-lock.json` — the local Node.js (v24) resolved `picomatch@4.0.4` as a new transitive dependency, which wasn't in the original lock file (generated with a different Node version). -- The push tool commits ALL changes in the cloned repo — including the modified `package-lock.json`. -- CI runs `npm ci` (not `npm install`) — `npm ci` is strict and requires `package.json` and `package-lock.json` to be in exact sync. Since the lock file was modified by a different Node version, it fails with `Missing: picomatch@4.0.4`. - -RCA: The `push` and `validate` commands used `npm install` which can modify `package-lock.json` when the local Node.js version differs from CI. The modified lock file was then committed, causing `npm ci` in CI to fail. - -Resolution: Replaced `npm install` with `npm ci` in both `push.py` and `validate.py`. `npm ci` installs exactly what is recorded in `package-lock.json` without modifying it. Also updated docstrings in `cli.py`, and updated `SKILL.md` (sync-eds-code) — rewrote Lock-file Handling section, Critical Rules, Workflow, and Troubleshooting table. - -Files changed: -- `sync-eds-code/scripts/eds_code_sync/push.py` -- `sync-eds-code/scripts/eds_code_sync/validate.py` -- `sync-eds-code/scripts/eds_code_sync/git_ops.py` (removed unused `restore_file` method) -- `sync-eds-code/scripts/eds_code_sync/cli.py` -- `sync-eds-code/SKILL.md` - ------------------------------------------------------------ -Issue 6: ------------------------------------------------------------ -`aem-psi-check` was failing in the eds-code PR because the PR description was missing a preview URL. - -What happened: -- AEM EDS repos have an `aem-psi-check` CI gate that validates PR descriptions. -- It requires a preview URL in the PR body matching this pattern: - ``` - URL for testing: - - - https://<branch>--<repo>--<owner>.aem.page/ - ``` -- The `eds-code-sync push --pr` command created a PR with a generic body that didn't include the test URL, so it always failed this check. - -RCA: The auto-generated PR body only contained file count, branch name, and base branch — no AEM preview URL. The `aem-psi-check` CI gate rejected it every time. - -Resolution: Updated `push.py` to auto-generate the preview URL from the branch name, repo, and owner (extracted from `config.github_repo`) and include it in the PR body under a `URL for testing:` section. Added documentation in `SKILL.md` (sync-eds-code) with a new "AEM PSI Check & PR Body" section and a troubleshooting row. - -Files changed: -- `sync-eds-code/scripts/eds_code_sync/push.py` -- `sync-eds-code/SKILL.md` - ------------------------------------------------------------ -Issue 7: ------------------------------------------------------------ -Script path resolution was broken — `CLAUDE_PLUGIN_ROOT` path was missing `forms-orchestrator/` segment. - -What happened: -- SKILL.md files referenced scripts as `${CLAUDE_PLUGIN_ROOT}/scripts/eds-code-sync`. -- `CLAUDE_PLUGIN_ROOT` resolves to the plugin root (`forms/`, where `.claude-plugin/` lives). -- But the scripts actually live under `forms/forms-orchestrator/scripts/`, not `forms/scripts/`. -- This caused `no such file or directory` errors when the agent tried to run any CLI tool. - -RCA: All SKILL.md files used `${CLAUDE_PLUGIN_ROOT}/scripts/...` but the scripts directory is nested one level deeper under `forms-orchestrator/`. The path was missing the `forms-orchestrator/` segment. - -Resolution: Updated all `${CLAUDE_PLUGIN_ROOT}/scripts/...` references to `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/...` across all affected SKILL.md files. - -Files changed: -- `sync-eds-code/SKILL.md` — 3 paths fixed (validate, push, sync) -- `setup-workspace/SKILL.md` — 2 paths fixed (test, sync) -- `add-rules/SKILL.md` — 7 paths fixed (rule-transform, parse-functions, api-manager ×2, rule-validate, rule-save ×2, rule-grammar) - ------------------------------------------------------------ -Issue 8: ------------------------------------------------------------ -`setup-workspace/SKILL.md` contained hardcoded example paths with `/Users/alice/projects`. - -What happened: -- Step 2 of the setup flow included an example with a hardcoded absolute path: - `FORMS_WORKSPACE=/Users/alice/projects/loan-app` -- While "alice" is a fictional user, hardcoded absolute paths in skill documentation can mislead the agent into using literal paths instead of dynamically resolved ones. - -RCA: The SKILL.md used a concrete example path instead of the generic `<cwd>/<name>` placeholder that was already defined earlier in the same step. - -Resolution: Removed the hardcoded `/Users/alice/projects/loan-app` example block and replaced the confirmation message with the generic `<cwd>/<name>` placeholder, which is already explained in the `.env` template block above it. - -Files changed: -- `setup-workspace/SKILL.md` - ------------------------------------------------------------ -Issue 9: ------------------------------------------------------------ -No guideline existed for how SKILL.md files should reference CLI scripts, leading to broken path resolution. - -What happened: -- Claude Code injects a `Base directory for this skill:` header into each skill at runtime, pointing to the skill's own directory on disk. -- The agent was resolving script paths relative to this base directory (e.g., navigating up 7 levels with `../../../../../../..`), producing absolute paths tied to the developer's source repo. -- These paths don't exist on other users' machines where the plugin is installed from the cache. -- There was no documented guideline telling skill authors (or the agent) to use `${CLAUDE_PLUGIN_ROOT}` instead of the skill base directory for script paths. - -RCA: Missing contribution guideline. Skill authors and the agent had no documented rule for how to reference scripts. The skill base directory (injected by Claude Code) is meant for resolving skill-local assets (`assets/`, `references/`), not for locating scripts that live at `forms-orchestrator/scripts/`. - -Resolution: Added a "Script & Path Resolution" section to `guidelines.md` (agent-facing) and a "Script References in SKILL.md" section to `contribution-guide.md` (developer-facing). Both enforce these rules: -1. Always use `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/<tool>` for script paths. -2. Never construct script paths from the skill's base directory. -3. Never hardcode absolute paths — no `/Users/...` in any SKILL.md. -4. Use relative paths only for skill-local assets within the skill's own directory tree. - -Files changed: -- `forms-orchestrator/assets/guidelines.md` -- `domain-registry/assets/contribution-guide.md` diff --git a/skills/aem/forms/.claude-plugin/plugin.json b/skills/aem/forms/.claude-plugin/plugin.json deleted file mode 100644 index 96542346..00000000 --- a/skills/aem/forms/.claude-plugin/plugin.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "aem-forms", - "version": "0.1.0", - "description": "Skills for building AEM Adaptive Forms through AI conversation — create, validate, and deploy forms via natural language", - "author": { - "name": "Adobe" - }, - "repository": "https://github.com/adobe/skills", - "license": "Apache-2.0", - "skills": [ - "./forms-orchestrator", - "./forms-orchestrator/references/planner", - "./forms-orchestrator/references/domain-registry", - "./forms-orchestrator/references/domain-registry/references/infra", - "./forms-orchestrator/references/domain-registry/references/infra/references/setup-workspace", - "./forms-orchestrator/references/domain-registry/references/infra/references/sync-forms", - "./forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code", - "./forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox", - "./forms-orchestrator/references/domain-registry/references/analysis", - "./forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements", - "./forms-orchestrator/references/domain-registry/references/analysis/references/analyze-v1-form", - "./forms-orchestrator/references/domain-registry/references/analysis/references/create-screen-doc", - "./forms-orchestrator/references/domain-registry/references/analysis/references/review-screen-doc", - "./forms-orchestrator/references/domain-registry/references/build", - "./forms-orchestrator/references/domain-registry/references/build/references/scaffold-form", - "./forms-orchestrator/references/domain-registry/references/build/references/create-form", - "./forms-orchestrator/references/domain-registry/references/build/references/create-component", - "./forms-orchestrator/references/domain-registry/references/logic", - "./forms-orchestrator/references/domain-registry/references/logic/references/add-rules", - "./forms-orchestrator/references/domain-registry/references/logic/references/create-function", - "./forms-orchestrator/references/domain-registry/references/logic/references/optimize-rules", - "./forms-orchestrator/references/domain-registry/references/integration", - "./forms-orchestrator/references/domain-registry/references/integration/references/manage-apis", - "./forms-orchestrator/references/domain-registry/references/context", - "./forms-orchestrator/references/domain-registry/references/context/references/manage-context" - ], - "keywords": [ - "adobe", - "aem", - "forms", - "adaptive-forms", - "edge-delivery-services" - ] -} diff --git a/skills/aem/forms/README.md b/skills/aem/forms/README.md deleted file mode 100644 index 21f0c5ec..00000000 --- a/skills/aem/forms/README.md +++ /dev/null @@ -1,314 +0,0 @@ -# AEM Forms Skills for AI Coding Agents - -> Turn natural language into production AEM Adaptive Forms. - -Skills plugin that gives AI coding agents (Claude Code, etc.) the knowledge and tools to create, validate, and deploy AEM Adaptive Forms through conversation. - ---- - -## Table of Contents - -- [How It Works](#how-it-works) -- [User Guide](#user-guide) _(install, set up workspace, start building)_ -- [Developer Guide](#developer-guide) _(work on the plugin itself)_ - ---- - -# How It Works - -The plugin is organized as a **Plan-Driven Skill Gateway** — a layered routing architecture with two registries that maps user intents to the right skill automatically. - -``` -User Intent → forms-orchestrator → Planner / Domain Registry → Domain Router → Skill → Tools -``` - -The entry point is the **forms-orchestrator** (`forms-orchestrator/SKILL.md`). It uses a **Planner** to generate multi-step plans from requirements, and a **Domain Registry** to catalog all available domains and skills. Domain routers dispatch to leaf skills, and each skill owns its tools and references. - -### Architecture - -``` -User Intent - │ - ▼ -┌────────────────────────────────────────┐ -│ forms-orchestrator │ ← type: router (entry point) -│ forms-orchestrator/SKILL.md │ -└──────────────────┬─────────────────────┘ - │ - ┌─────────┴─────────┐ - ▼ ▼ -┌──────────────┐ ┌──────────────┐ -│ Planner │ │ Domain │ -│ (generates │ │ Registry │ -│ plans) │ │ (catalogs │ -│ │ │ domains & │ -│ │ │ skills) │ -└──────┬───────┘ └──────┬───────┘ - │ │ - ▼ ▼ - Plan files Domain Routers - plans/<journey>/ ┌──────────────┐ - NN-<title>.md │ type: domain │ - └──────┬───────┘ - │ - ▼ - ┌──────────────┐ - │ type: skill │ ← leaf nodes do the work - └──────────────┘ -``` - -### 6-Step Routing Algorithm - -Routing follows a strict 6-step algorithm defined in `forms-orchestrator/assets/routing-table.md`: - -| Step | Name | Condition | Action | -|------|------|-----------|--------| -| 1 | **Workspace gate** | No workspace detected? | → `infra` › `setup-workspace` (hard block) | -| 2 | **Active plan** | Active plan in `.agent/handover.md`? | → Resume it | -| 3 | **Plans exist** | Pending plans in `plans/<journey>/`? | → Activate next → execute | -| 4 | **Generate plans** | User has requirements but no plans? | → Planner generates them | -| 5 | **Domain fallback** | Intent is a single task? | → Route to domain directly | -| 6 | **No match** | None of the above? | → Ask user to clarify | - -You don't need to memorize this — just start talking to the agent. The orchestrator handles routing. - -> **Full details:** See `forms-orchestrator/SKILL.md` for the complete routing table and orchestrator constraints, and `forms-orchestrator/assets/routing-table.md` for the algorithm definition. - -### Domains - -| Domain | Purpose | Skills | -|--------|---------|--------| -| `analysis` | Requirements & documentation | `analyze-requirements`, `analyze-v1-form`, `create-screen-doc`, `review-screen-doc` | -| `build` | Form structure & components | `scaffold-form`, `create-form`, `create-component` | -| `logic` | Business rules & functions | `add-rules`, `create-function`, `optimize-rules` | -| `integration` | APIs & data | `manage-apis` | -| `infra` | Setup, sync, deploy | `setup-workspace`, `sync-forms`, `sync-eds-code`, `git-sandbox` | -| `context` | Agent memory & session continuity | `manage-context` | - -### Plan Types - -Instead of fixed phases, the **Planner** dynamically generates plans from user requirements. Each plan is one of five types: - -| Plan Type | Purpose | -|-----------|---------| -| Structure | Building the form skeleton — panels, fields, basic validations | -| Workflow | Implementing a specific user flow or conditional branch | -| Logic | Adding cross-cutting validations and business rules | -| Integration | Wiring APIs — data loading, save/submit, external services | -| Infrastructure | Cross-cutting concerns — error handling, session management | - -Plans are generated as Markdown files in `plans/<journey>/NN-<title>.md` and executed sequentially by the orchestrator. - ---- - -# User Guide - -Everything you need to install the plugin, set up a workspace, and start building forms. - -## 1. System Requirements - -| Requirement | Why | -|-------------|-----| -| Node.js 18+ | Runs the form validator, rule transformer, and rule save tools | -| Python 3.10+ | Runs form sync, API manager, and rule validation (deps managed by the plugin) | -| `git` on PATH | Used by `eds-code-sync` and `git-sandbox` for repo operations | - -The plugin bundles its own Python virtual environment — you don't install any Python packages yourself. - -## 2. Install the Plugin - -### Claude Code - -``` -/plugin install aem-forms@adobe-skills -``` - -### Vercel Skills (npx) - -``` -# Install all skills -npx skills add adobe/skills --path skills/aem/forms --all - -# Or install a single skill -npx skills add adobe/skills --path skills/aem/forms --skill create-form - -# List what's available -npx skills add adobe/skills --path skills/aem/forms --list -``` - -Python dependencies are installed automatically on first use. - -## 3. Get Started - -After installation, tell your agent: - -> _"Set up a new AEM Forms workspace for my project."_ - -The `setup-workspace` skill handles everything — directory structure, `.env` credentials, system checks, and first sync. See [`forms-orchestrator/references/domain-registry/references/infra/references/setup-workspace/SKILL.md`](forms-orchestrator/references/domain-registry/references/infra/references/setup-workspace/SKILL.md) for the full workspace layout, credential reference, and configuration guide. - -Once your workspace is ready, just start talking: - -> _"Here's the requirements doc for a personal loan application. Build the form."_ - -The **forms-orchestrator** (`forms-orchestrator/SKILL.md`) receives your intent and runs through the 6-step routing algorithm. For complex requirements it invokes the **Planner** to generate a sequence of plans, then executes each plan by routing to the appropriate domain and skill. For simple single-task requests it routes directly to the matching domain. See the orchestrator for the complete routing table and available skills across all six domains: `analysis`, `build`, `logic`, `integration`, `infra`, and `context`. - ---- - -# Developer Guide - -Everything you need to work on the plugin code — add skills, modify scripts, and run tests. - -## Prerequisites - -- Python 3.10+ (3.13 recommended) -- Node.js 18+ -- `git` and `npm` on PATH -- [`uv`](https://docs.astral.sh/uv/) (recommended) or `python3 -m venv` - -## 1. Clone and Set Up - -``` -git clone <repo-url> -cd skills/aem/forms - -# Run the setup script — creates .venv at project root, installs everything -./forms-orchestrator/scripts/setup.sh -``` - -The script will: -1. Create a `.venv` virtual environment at the project root (uses `uv` if available, falls back to `python3 -m venv`). -2. Install the project in editable mode (`pip install -e ".[dev]"`). -3. Install the Node.js bridge dependencies (`npm install` in `forms-orchestrator/scripts/rule_coder/bridge/`). - -After setup, activate the venv in any new shell: - -``` -source .venv/bin/activate -# (The root ./setup.sh wrapper also works — it forwards to forms-orchestrator/scripts/setup.sh) -``` - -| Flag | What it does | -|------|-------------| -| `--force` | Delete existing `.venv/` and recreate from scratch | -| `--skip-deps` | Create/activate venv but skip package installation | - -## 2. Run Tests - -``` -source .venv/bin/activate - -# Validate plugin structure (14 skill entries, all SKILL.md files, script directories, Python packages) -bash tests/test_plugin_structure.sh -``` - -There's also a manual end-to-end test plan in `tests/e2e-test-plan.md` (30–45 min, covers analyze → create → rules → functions → validate) and an error-handling guide in `tests/error-handling-guide.md` for CLI tool error patterns and recovery. - -Individual skills may also have `eval/` directories for skill-level testing. - -## Repository Structure - -``` -forms/ -├── pyproject.toml # Python packaging — deps, entry points -├── setup.sh # Wrapper → forms-orchestrator/scripts/setup.sh -├── README.md # This file -├── .claude-plugin/ -│ └── plugin.json # Plugin metadata and skill registry -├── forms-orchestrator/ -│ ├── SKILL.md # forms-orchestrator — entry point (type: router) -│ ├── assets/ -│ │ ├── guidelines.md # Orchestrator constraints & conventions -│ │ └── routing-table.md # 6-step routing algorithm -│ ├── scripts/ # Shared CLI wrappers + tool backends -│ │ ├── setup.sh # Environment setup (creates .venv at project root) -│ │ ├── _resolve-workspace # Workspace resolution helper (sourced by all tools) -│ │ ├── api-manager # CLI wrapper -│ │ ├── eds-code-sync # CLI wrapper -│ │ ├── form-sync # CLI wrapper -│ │ ├── git-sandbox # CLI wrapper -│ │ ├── parse-functions # CLI wrapper -│ │ ├── python3 # Python venv wrapper -│ │ ├── rule-grammar # CLI wrapper -│ │ ├── rule-save # CLI wrapper -│ │ ├── rule-transform # CLI wrapper -│ │ ├── rule-validate # CLI wrapper -│ │ ├── api_manager/ # Python backend for api-manager -│ │ └── rule_coder/ # Node.js backend for rule-* tools -│ └── references/ -│ ├── planner/ # Plan generator (type: skill) -│ │ ├── SKILL.md -│ │ ├── assets/ -│ │ │ └── plan-template.md -│ │ └── references/ -│ │ ├── default-strategy.md -│ │ ├── structure-plan.md -│ │ ├── workflow-plan.md -│ │ ├── logic-plan.md -│ │ ├── integration-plan.md -│ │ └── infrastructure-plan.md -│ └── domain-registry/ # Domain & skill catalog (type: router) -│ ├── SKILL.md -│ ├── assets/ -│ │ ├── skills-catalog.md -│ │ ├── skill-resolution.md -│ │ ├── contribution-guide.md -│ │ └── templates/ -│ │ └── domain-template.md -│ └── references/ -│ ├── analysis/ # SKILL.md + references/{analyze-requirements, analyze-v1-form, create-screen-doc, review-screen-doc} -│ ├── build/ # SKILL.md + references/{scaffold-form, create-form, create-component} -│ ├── logic/ # SKILL.md + references/{add-rules, create-function, optimize-rules} -│ ├── integration/ # SKILL.md + references/{manage-apis} -│ ├── infra/ # SKILL.md + references/{setup-workspace, sync-forms, sync-eds-code, git-sandbox} -│ └── context/ # SKILL.md + references/{manage-context} -└── tests/ - ├── README.md - ├── test_plugin_structure.sh - ├── e2e-test-plan.md - └── error-handling-guide.md -``` - -Every level follows the [agentskills.io specification](https://agentskills.io/specification): `SKILL.md` (required) + `scripts/` + `references/` + `assets/` (optional). - -## Shared CLI Tools (`forms-orchestrator/scripts/`) - -| Tool | Backend | Description | -|------|---------|-------------| -| `api-manager` | `forms-orchestrator/scripts/api_manager/cli.py` | Manage OpenAPI specs and JS clients | -| `rule-transform` | `forms-orchestrator/scripts/rule_coder/bridge/cli/transform-form.js` | Transform form JSON for rule editing | -| `rule-validate` | `forms-orchestrator/scripts/rule_coder/validator/` | Validate rule JSON against grammar | -| `rule-save` | `forms-orchestrator/scripts/rule_coder/bridge/cli/save-rule.js` | Save compiled rules back to form | -| `rule-grammar` | `forms-orchestrator/scripts/rule_coder/grammar/` | Print the rule grammar reference | -| `parse-functions` | `forms-orchestrator/scripts/rule_coder/bridge/cli/parse-functions.js` | Parse custom function JSDoc annotations | - -## Skill-Embedded CLI Tools - -These tools live inside individual skill directories at `forms-orchestrator/references/domain-registry/references/<domain>/references/<skill>/scripts/`. - -| Tool | Domain / Skill | Language | -|------|----------------|----------| -| `form-sync` | `infra/sync-forms` | Python | -| `eds-code-sync` | `infra/sync-eds-code` | Python | -| `git-sandbox` | `infra/git-sandbox` | Python | -| `form-validate` | `build/create-form` | Node.js | -| `scaffold-form` | `build/scaffold-form` | Python | -| `cct-create` | `build/create-component` | Python | -| `api-skill` | `integration/manage-apis` | Python | - -## Adding a New Skill - -1. Decide which domain it belongs to (`analysis`, `build`, `logic`, `integration`, `infra`, or `context`). -2. Create a directory under `forms-orchestrator/references/domain-registry/references/<domain>/references/<skill-name>/`. -3. Add a `SKILL.md` file with frontmatter (`name`, `description`) and instructions. -4. If the skill needs a CLI tool, add a `scripts/` directory inside the skill. -5. If the skill has a **Python** package, add its `scripts/` path to the `PYTHONPATH` block in `forms-orchestrator/scripts/python3` (the central Python wrapper manages all package paths — no individual script should set `PYTHONPATH`). -6. If the skill has a **Python** package, add its `scripts/` path to `pyproject.toml` under `[tool.setuptools.packages.find]` `where`. -7. Register it in `forms-orchestrator/references/domain-registry/assets/skills-catalog.md`. -8. Register it in `.claude-plugin/plugin.json` under the `skills` array. -9. Run `bash tests/test_plugin_structure.sh` to verify. - ---- - -## License - -Apache 2.0 — see [LICENSE](../../../LICENSE) for details. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/SKILL.md b/skills/aem/forms/forms-orchestrator/SKILL.md deleted file mode 100644 index b4be01e2..00000000 --- a/skills/aem/forms/forms-orchestrator/SKILL.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -name: forms-orchestrator -description: > - Skill Gateway for AEM Forms. Pure router with two registries — Planner - (references/planner/SKILL.md) and Domain Registry (references/domain-registry/SKILL.md). - Routes user intents to plans (sequences of skill invocations), resolves each - plan step to a domain/skill, and executes accordingly. When no plans exist, - generates them from user requirements. Routing algorithm and constraints are - in assets/. Triggers: plan, workflow, how to build, end to end, orchestrate, - what skill, which skill, next step, getting started, build a form, route. -type: router -license: Apache-2.0 -metadata: - author: Adobe - version: "1.0" ---- - -# Forms Orchestrator — Skill Gateway - -Pure router. Two registries. No implementation logic. - -``` -User Intent - │ - ▼ -┌────────────────────────────────────────┐ -│ Plans │ -│ plans/<journey>/NN-<title>.md │──→ ordered steps, each declaring skill(s) -└──────────────────┬─────────────────────┘ - │ - ▼ -┌────────────────────────────────────────┐ -│ Domain Registry │ -│ references/domain-registry/SKILL.md │──→ resolves domain/skill to implementation -└──────────────────┬─────────────────────┘ - │ - ▼ - Skill executes -``` - -> This gateway **selects** and **routes**. It does not implement. -> Plans define the step sequence. Domains own the skills. The orchestrator connects them. - ---- - -## Routing - -When a user prompt arrives, follow the routing algorithm in [`assets/routing-table.md`](assets/routing-table.md): - -1. **Workspace gate** — no workspace? → `infra` › `setup-workspace` (hard block) -2. **Active plan** — 🔵 Active plan in `.agent/handover.md`? → resume it -3. **Plans exist** — plans in `plans/<journey>/`? → pick next pending → execute -4. **Generate plans** — user has requirements but no plans? → Planner generates them → execute -5. **Domain fallback** — intent is a single task? → route to domain directly -6. **No match** — ask user to clarify - -Full step-by-step logic, decision tables, and precedence rules: **[`assets/routing-table.md`](assets/routing-table.md)** - ---- - -## Registries - -| Registry | File | What It Does | -|----------|------|-------------| -| **Planner** | [`references/planner/SKILL.md`](references/planner/SKILL.md) | Generates plans from user requirements (journey docs, screenshots, Screen.md, etc.) using a default or custom strategy | -| **Domain Registry** | [`references/domain-registry/SKILL.md`](references/domain-registry/SKILL.md) | Catalogs domains and skills, matches intents to domains, resolves plan step targets to executable skills | - -Plan files live in `plans/<journey>/`. Domain skill trees live in `references/domain-registry/references/`. - ---- - -## Guidelines & Constraints - -All orchestrator constraints, conventions, file locations, workspace resolution, plan conventions, and general routing rules: **[`assets/guidelines.md`](assets/guidelines.md)** - ---- - -## Quick Reference - -| What | Where | -|------|-------| -| Routing algorithm | `assets/routing-table.md` | -| Constraints & conventions | `assets/guidelines.md` | -| Plan template | `references/planner/assets/plan-template.md` | -| Planner | `references/planner/SKILL.md` | -| Plan files | `plans/<journey>/NN-<title>.md` | -| Domain registry | `references/domain-registry/SKILL.md` | -| Domain routers | `references/domain-registry/references/<domain>/SKILL.md` | -| Domain template | `references/domain-registry/assets/templates/domain-template.md` | -| Skills catalog & intent routing | `references/domain-registry/assets/skills-catalog.md` | -| Domain contribution guide | `references/domain-registry/assets/contribution-guide.md` | diff --git a/skills/aem/forms/forms-orchestrator/assets/guidelines.md b/skills/aem/forms/forms-orchestrator/assets/guidelines.md deleted file mode 100644 index 0a9848ae..00000000 --- a/skills/aem/forms/forms-orchestrator/assets/guidelines.md +++ /dev/null @@ -1,149 +0,0 @@ -# Orchestrator Guidelines - -Constraints, conventions, and reference tables for the Forms Orchestrator. - ---- - -## Script & Path Resolution - -All CLI tools live under `forms-orchestrator/scripts/` — **not** at the plugin root. When referencing any script from a SKILL.md, always use `${CLAUDE_PLUGIN_ROOT}` as the base and include the `forms-orchestrator/` segment: - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/<tool-name>" <args> -``` - -### Rules - -| # | Rule | -|---|------| -| 1 | **Always use `${CLAUDE_PLUGIN_ROOT}`** — never construct paths from the skill's own base directory. The base directory injected by Claude Code (e.g., `Base directory for this skill: /path/to/...`) is for resolving skill-local assets (`assets/`, `references/`), **not** for locating scripts. | -| 2 | **Always include `forms-orchestrator/`** — the plugin root (`${CLAUDE_PLUGIN_ROOT}`) is the directory containing `.claude-plugin/`. Scripts are one level deeper at `forms-orchestrator/scripts/`. | -| 3 | **Never hardcode absolute paths** — no `/Users/...` paths in SKILL.md files. Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths and `<cwd>/<name>` style placeholders for documentation examples. | -| 4 | **Skill-local assets use relative paths** — files within a skill's own directory tree (e.g., `assets/plan-template.md`, `references/grammar-reference.md`) should be referenced with relative paths from the SKILL.md, not with `${CLAUDE_PLUGIN_ROOT}`. | - -### Available Scripts - -| Script | Full Path | -|--------|-----------| -| `eds-code-sync` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync` | -| `form-sync` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/form-sync` | -| `rule-transform` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-transform` | -| `rule-validate` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-validate` | -| `rule-save` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-save` | -| `rule-grammar` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-grammar` | -| `parse-functions` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/parse-functions` | -| `api-manager` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/api-manager` | -| `git-sandbox` | `${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/git-sandbox` | - ---- - -## Workspace Gate - -Before any routing occurs, verify the workspace exists. - -**Check:** `FORMS_WORKSPACE` environment variable is set, or `.env` file exists in cwd. - -| Condition | Action | -|-----------|--------| -| Workspace exists | Proceed to routing | -| Workspace missing | Route to Domain Registry → `infra` › `setup-workspace` immediately. **Block all other routing until complete.** | - -> No domain, no skill, no plan may execute without a resolved workspace — except `setup-workspace` itself. - ---- - -## Workspace Resolution - -All CLI tools auto-resolve the workspace directory before running. Every tool sources `scripts/_resolve-workspace` which ensures `.env`, `metadata.json`, `sandbox.json`, and all workspace directories are found correctly. - -**Resolution order (first match wins):** - -1. **`FORMS_WORKSPACE` already in environment** — e.g. exported by the caller -2. **`FORMS_WORKSPACE` read from `.env` in cwd** — written by `setup-workspace` during initial setup -3. **Fall back to cwd** — backwards-compatible default - ---- - -## Plan Conventions - -Plans are sequentially ordered execution units within a journey. Each plan contains ordered steps, and each step invokes one or more skills via the Domain Registry. - -| Rule | Description | -|------|-------------| -| **File path** | `plans/<journey>/NN-<short-title>.md` | -| **Numbering** | Zero-padded two digits: `01`, `02`, ..., `10`, `11` | -| **Execution order** | Sequential — each plan declares its dependencies explicitly | -| **Max per journey** | 15 — if more are needed, the journey is likely too complex (check complexity thresholds) | -| **Template** | See `references/planner/assets/plan-template.md` | -| **Generation** | Plans are generated by the Planner (`references/planner/SKILL.md`) using a default or user-customized strategy | -| **Decomposition guidelines** | See Domain Registry → `analysis` › `analyze-requirements` skill (§ Plan Generation) | - -### Plan Status Tracking - -Plan status is tracked in `.agent/handover.md` via the Plan Execution Status dashboard, managed by Domain Registry → `context` › `manage-context`. - -**Statuses:** ✅ Done — 🔵 Active — ⬚ Pending — ⏸️ Blocked — ❌ Failed - -### Journey Completion - -When all plans for a journey show ✅ Done: -- `manage-context` archives the journey to `.agent/history.md` -- The journey row in `.agent/handover.md` moves to ✅ Done -- The next queued journey (if any) is promoted to active - ---- - -## General Routing Rules - -1. **The orchestrator does not implement** — it only selects and routes. All logic lives in plans, domains, and skills. -2. **Plans first, domain fallback** — always try to find or generate plans before falling through to direct domain routing. -3. **Active plan takes priority** — if `.agent/handover.md` shows a 🔵 Active plan, resume it before considering new intents. -4. **One active plan at a time** — do not start a new plan while one is in progress. Complete or pause the current plan first. -5. **Plans own checkpoints** — each plan defines its own completion criteria and post-completion checkpoint behavior. -6. **Domains own skills** — the orchestrator never invokes a skill directly. It routes to a domain router, which handles skill-level dispatch. -7. **Ambiguity requires user input** — if multiple plans or domains match, present options. Never guess. -8. **No silent side effects** — never update `.agent/` files, deploy, or modify code without user confirmation. - ---- - -## Config Files - -| File | Managed By | Purpose | -|------|------------|---------| -| `.env` | `setup-workspace` | `FORMS_WORKSPACE` path + AEM/GitHub credentials — never commit | -| `metadata.json` | `sync-forms` | Tracks synced form/fragment paths (AEM ↔ local) | -| `sandbox.json` | `git-sandbox` | Restricts allowed commit paths and push branch names | - ---- - -## File Locations - -### Orchestrator Structure - -| What | Where | -|------|-------| -| Orchestrator | `SKILL.md` | -| Routing table | `assets/routing-table.md` | -| Guidelines (this file) | `assets/guidelines.md` | -| Plan template | `references/planner/assets/plan-template.md` | -| Planner | `references/planner/SKILL.md` | -| Plan files | `plans/<journey>/NN-<title>.md` | -| Domain registry | `references/domain-registry/SKILL.md` | -| Domain routers | `references/domain-registry/references/<domain>/SKILL.md` | - -### Workspace Structure - -| What | Where | -|------|-------| -| Forms | `repo/content/forms/af/<team>/<path>/<name>.form.json` | -| Rule stores | `repo/content/forms/af/<team>/<path>/<name>.rule.json` | -| Fragment scripts | `code/blocks/form/scripts/fragment/<fragment>.js` | -| Form-level scripts | `code/blocks/form/scripts/form/<form>.js` | -| Shared libraries | `code/blocks/form/scripts/script-libs/libs.js` | -| API clients (live) | `code/blocks/form/api-clients/` | -| API clients (staging) | `refs/apis/api-clients/` | -| API definitions | `refs/apis/` | -| Screen docs | `journeys/<journey>/screens/<screen>/Screen.md` | -| Custom components | `code/components/<view-type>/` | -| Plans | `plans/<journey>/NN-<title>.md` | -| Agent memory | `.agent/handover.md`, `.agent/history.md`, `.agent/sessions.md` | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/assets/routing-table.md b/skills/aem/forms/forms-orchestrator/assets/routing-table.md deleted file mode 100644 index 798db755..00000000 --- a/skills/aem/forms/forms-orchestrator/assets/routing-table.md +++ /dev/null @@ -1,241 +0,0 @@ -# Routing Table - -The orchestrator's routing algorithm. Determines how user intents are classified and routed to plans or domains. - ---- - -## Architecture - -``` -User Intent - │ - ▼ -┌────────────────────────────────────────┐ -│ Step 1: Workspace Gate │──→ no workspace? → infra › setup-workspace -└──────────────────┬─────────────────────┘ - │ workspace exists - ▼ -┌────────────────────────────────────────┐ -│ Step 2: Active Plan Check │──→ 🔵 Active plan? → resume → execute steps -└──────────────────┬─────────────────────┘ - │ no active plan - ▼ -┌────────────────────────────────────────┐ -│ Step 3: Plans Check │ -│ plans/<journey>/ │──→ pending plans exist? → activate next → execute -└──────────────────┬─────────────────────┘ - │ no plans exist - ▼ -┌────────────────────────────────────────┐ -│ Step 4: Generate Plans │ -│ references/planner/SKILL.md │──→ user has requirements? → generate plans → Step 3 -└──────────────────┬─────────────────────┘ - │ no requirements / single task - ▼ -┌────────────────────────────────────────┐ -│ Step 5: Domain Fallback │ -│ references/domain-registry/SKILL.md │──→ intent matches a domain? → execute skill -└──────────────────┬─────────────────────┘ - │ no domain matched - ▼ - Ask user to clarify -``` - ---- - -## Step 1 — Check Workspace Gate - -**Priority:** Highest — runs before anything else. - -| Condition | Action | -|-----------|--------| -| `FORMS_WORKSPACE` not set AND no `.env` found | Route to Domain Registry → `infra` › `setup-workspace`. Halt all other routing until setup completes. | -| Workspace exists | Proceed to Step 2 | - -> This gate ensures no skill ever runs without a configured workspace. It is non-negotiable. - ---- - -## Step 2 — Check Active Plan - -**Priority:** Second — resume in-progress work before starting anything new. - -| Condition | Action | -|-----------|--------| -| `.agent/handover.md` exists AND contains a 🔵 Active plan | Read the plan file at `plans/<journey>/NN-<title>.md`. Identify the current step. Execute via **Plan Execution Flow** below. | -| No `.agent/handover.md` OR no active plan | Proceed to Step 3 | - -**How to identify an active plan:** -1. Read `.agent/handover.md` -2. Look at the **Journey Status** table — find a row with `🔵 Active` -3. Look at the **Plan Execution Status** table — find the row with `🔵 Active` -4. Read the plan file referenced in that row -5. The plan file declares ordered steps, each specifying which skill(s) to invoke - ---- - -## Step 3 — Check for Existing Plans - -**Priority:** Third — execute existing plans before trying to generate new ones. - -Check whether plan files exist in `plans/<journey>/` for the active journey. - -| Outcome | Action | -|---------|--------| -| ✅ Pending plans exist (⬚ status) | Pick the next pending plan (lowest `NN` number), mark it 🔵 Active in `.agent/handover.md`, execute via **Plan Execution Flow** below. | -| ✅ All plans are ✅ Done | Journey is complete. Archive via `manage-context`. | -| ❌ No plan files exist | Proceed to **Step 4** | - ---- - -## Step 4 — Generate Plans - -**Priority:** Fourth — user has requirements but no plans yet. - -The user has provided requirements (journey docs, screenshots, Screen.md, etc.) but no plans have been created. Route to the **Planner** at `references/planner/SKILL.md` to generate plans. - -| Outcome | Action | -|---------|--------| -| ✅ Plan Registry generates plans | Plans are written to `plans/<journey>/`. Return to **Step 3** to begin execution. | -| ❌ Insufficient requirements to generate plans | Ask the user for more context (Screen.md, journey description, screenshots, etc.). | -| ❌ Intent is a single isolated task, not a journey | Fall through to **Step 5** | - -The Planner uses a default generation strategy but supports user customization. See `references/planner/SKILL.md` for details. - ---- - -## Step 5 — Match Intent to Domain (Fallback) - -**Priority:** Fifth — handles one-off tasks that don't need plans. - -Route to the **Domain Registry** at `references/domain-registry/SKILL.md`. The registry has an Intent → Domain Routing table. - -| Outcome | Action | -|---------|--------| -| ✅ Single domain matches | Route to that domain's router SKILL.md. The domain router handles skill-level routing internally. | -| ✅ Multiple domains match | Present top 2–3 matching domains to the user, let them choose | -| ❌ No domain matches | Proceed to **Step 6** | - -### When to Use Direct Domain Routing (skip plans) - -Direct domain routing is appropriate when the user's intent is a **single, isolated task** — not part of a multi-step journey: - -| Example Intent | Domain | Why Not a Plan | -|----------------|--------|----------------| -| "Push my form to AEM" | `infra` | Single deploy action, not a build workflow | -| "Add a visibility rule to panelX" | `logic` | Single rule addition, form already exists | -| "Show me the API client for checkEnquiry" | `integration` | Information retrieval, no build needed | -| "Update the project reports" | `context` | Context management, not a build step | -| "Validate my Screen.md" | `analysis` | Single review action | -| "Create a custom date-picker component" | `build` | Single component creation | - ---- - -## Step 6 — No Match - -**Priority:** Last resort. - -No plan, no domain, and no generation strategy matched the user's intent. - -| Action | -|--------| -| Ask the user to clarify their intent. Do not guess. | - ---- - -## Plan Execution Flow - -When a plan is active (from Step 2 or Step 3), execute it using this flow: - -``` -Active plan selected - │ - ▼ -Read plan file from plans/<journey>/NN-<title>.md - │ - ▼ -Identify current step: - ├─ New plan → start at first step - └─ Resumed plan → start at the first incomplete step - │ - ▼ -For the current step, read: - • skill (which specific skill to invoke) - • input (what artifacts this step needs) - • output (what artifacts this step produces) - │ - ▼ -Resolve skill via Domain Registry - (references/domain-registry/SKILL.md → references/domain-registry/references/<domain>/SKILL.md) - │ - ▼ -Execute the skill - │ - ▼ -On step completion → advance to next step in plan -``` - -### Step Resolution - -To resolve a plan step to an executable skill: - -1. Read the step's skill declaration from the plan file -2. Look up the skill in the Domain Registry's Skills Catalog → find which domain owns it -3. Route to the domain's router SKILL.md → the domain router invokes the specific skill - -If a step declares a skill that doesn't exist in the Domain Registry's catalog, **halt and report the error**. Do not guess or substitute. - -### Post-Completion - -After a skill completes: - -1. Mark the current step as done in the plan -2. Check if the plan has more steps → if yes, execute the next step -3. If all steps are complete → mark the plan ✅ Done, run the **post-plan checkpoint** (see below) -4. Check if more plans remain for the journey → if yes, activate the next pending plan (return to Step 3) -5. If all plans are complete → journey is complete. Archive via `manage-context` to `.agent/history.md` - -### Post-Plan Checkpoint - -After each plan completes, present the user with these options. All local changes are preserved regardless of choice — skipped deployments can be done later at any time. - -> *"This plan is complete. How would you like to proceed?"* - -| Option | Deploy? | Update Reports? | Next Action | -|--------|---------|-----------------|-------------| -| **1. Deploy and update reports** | ✅ | ✅ | Deploy all changes, then update `.agent/` reports | -| **2. Update reports only** | ❌ | ✅ | Skip deployment, update `.agent/` reports | -| **3. Update reports and proceed** | ❌ | ✅ | Update `.agent/` reports, then start next plan | -| **4. Proceed to next plan** | ❌ | ❌ | Skip both, start next plan immediately | - -**When deploying (option 1):** -1. **EDS code first** — If any files in the `code/` directory were created or modified: - 1. **Validate** — Run `eds-code-sync validate` to verify the changes pass `npm install` and `npm run lint`. The local `code/` directory does not contain `package.json` — the validate command clones the repo, applies changes, and runs checks automatically. If validation fails, fix the issues in `code/` and re-run validate. - 2. **Push** — Push them to GitHub with `eds-code-sync push --branch <branch-name> --pr`. - 3. **Wait for merge** — Ask the user to review and merge the PR. - 4. **Re-sync** — Once the user confirms the merge, run `eds-code-sync sync` to re-sync the local `code/` directory with the merged main branch before proceeding. -2. **AEM forms second** — If any form or rule files were created or modified (in `repo/`), push them to AEM Author with `form-sync push <form_path>` for each changed form. This must happen after EDS code is deployed, since forms may reference custom functions or components that need to be live first. - -**When updating reports (options 1, 2, 3):** Route to `context` → `manage-context` to update `.agent/handover.md`, `.agent/history.md`, and `.agent/sessions.md`. - ---- - -## Decision Summary - -``` -User Intent - │ - ├─ No workspace? → Step 1 → setup-workspace (hard gate) - │ - ├─ Active plan exists? → Step 2 → resume plan → execute steps - │ - ├─ Pending plans exist? → Step 3 → activate next plan → execute steps - │ - ├─ Has requirements? → Step 4 → generate plans → Step 3 - │ - ├─ Matches a domain? → Step 5 → route to domain → execute skill - │ - └─ Nothing matches? → Step 6 → ask user to clarify -``` - -**Key principle:** Every path either reaches a skill execution or an explicit "ask user" fallback. There are no silent failures or dead ends. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/SKILL.md deleted file mode 100644 index 0091a620..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/SKILL.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -name: domain-registry -description: > - Domain registry and router for AEM Forms skills. Catalogs all domains and their - skills. Routes user intents to the correct domain based on trigger patterns. - Used by the orchestrator to resolve plan step targets and direct domain routing. - Triggers: which domain, which skill, what can you do, list skills, capabilities. -type: router -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Domain Registry - -Domains are skill containers. Each domain has a router SKILL.md that handles skill-level routing internally. This registry catalogs all domains and their skills, and provides intent-based routing. - -> The orchestrator routes here in two scenarios: -> 1. **Plan step execution** — a plan step declares `domain: analysis, skill: analyze-requirements` → this registry resolves the path -> 2. **Direct domain routing** — user intent maps to a single domain → this registry routes to it - ---- - -## Registry - -| Domain | Router | Description | -|--------|--------|-------------| -| `analysis` | [`references/analysis/SKILL.md`](references/analysis/SKILL.md) | Analysis & documentation — requirements, screen docs, migration, review | -| `build` | [`references/build/SKILL.md`](references/build/SKILL.md) | Form structure & components — scaffold, create/modify JSON, custom components | -| `logic` | [`references/logic/SKILL.md`](references/logic/SKILL.md) | Business rules & custom functions — rules, JS functions, optimization | -| `integration` | [`references/integration/SKILL.md`](references/integration/SKILL.md) | API & data integration — FDM sync, OpenAPI, JS API clients | -| `infra` | [`references/infra/SKILL.md`](references/infra/SKILL.md) | Infrastructure — workspace setup, form sync, EDS code sync, git | -| `context` | [`references/context/SKILL.md`](references/context/SKILL.md) | Agent memory & continuity — handover, history, session logs | - ---- - -## Skills & Intent Routing - -Full catalog of all 16 skills across 6 domains, plus intent-based routing for direct domain routing: **[`assets/skills-catalog.md`](assets/skills-catalog.md)** - ---- - -## Skill Resolution - -How plan steps resolve to domain skills (exact-match rules, hard-stop on missing domain/skill): **[`assets/skill-resolution.md`](assets/skill-resolution.md)** - ---- - -## Domain Template & Contribution Guide - -All domain router SKILL.md files must follow the standard domain template. Template, plus instructions for adding new domains and skills: **[`assets/contribution-guide.md`](assets/contribution-guide.md)** - -Template file: [`assets/templates/domain-template.md`](assets/templates/domain-template.md) - ---- - -## Quick Reference - -| What | Where | -|------|-------| -| Skills catalog & intent routing | `assets/skills-catalog.md` | -| Skill resolution algorithm | `assets/skill-resolution.md` | -| Domain template | `assets/templates/domain-template.md` | -| Contribution guide | `assets/contribution-guide.md` | -| Domain routers | `references/<domain>/SKILL.md` | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/contribution-guide.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/contribution-guide.md deleted file mode 100644 index e55f978d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/contribution-guide.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -name: domain-contribution-guide -description: > - How to add new domains and skills to the domain registry. ---- - -# Domain Contribution Guide - -## Domain Template - -All domain router `SKILL.md` files must follow the standard domain template: - -[`templates/domain-template.md`](templates/domain-template.md) - -The template defines these required sections in order: - -| # | Section | Purpose | -|---|---------|---------| -| 1 | YAML frontmatter | `name`, `description`, `type: domain`, `triggers`, `license`, `metadata` | -| 2 | `# <Name> — Domain Router` | Heading with ID, Version, Description | -| 3 | `## Routing Table` | Intent → skill mapping (first match wins) | -| 4 | `## Skills` | Numbered catalog of all skills + Skill Locations sub-table | -| 5 | `## Guard Policies` | Cross-skill constraints in blockquote format | -| 6 | `## File Locations` | Canonical paths for assets managed by this domain | -| 7 | `## Dependencies` | Cross-domain dependencies (omit if none) | -| 8 | `## Plan Integration` | Which plan types commonly invoke this domain's skills (omit if none) | -| 9 | `## Extending This Domain` | Instructions for adding new skills | - ---- - -## Adding a New Domain - -1. Copy the domain template from [`templates/domain-template.md`](templates/domain-template.md) to `references/<domain-name>/SKILL.md` -2. Fill in the YAML frontmatter — set `name`, `description`, and `triggers` -3. Fill in the routing table — one row per skill in the domain -4. Fill in the skills table — catalog every skill with its purpose and triggers -5. Define guard policies — constraints that prevent unsafe operations -6. Fill in file locations — canonical paths for assets this domain manages -7. Map cross-domain dependencies if any exist -8. Map plan types that commonly invoke skills in this domain -9. Create skill sub-folders under `references/<domain-name>/references/<skill-name>/` -10. Register the domain in the **Registry** table in the domain registry's [`SKILL.md`](../SKILL.md) -11. Register each skill in the **Skills Catalog** in [`assets/skills-catalog.md`](skills-catalog.md) -12. Add the domain's intent patterns to the **Intent → Domain Routing** table in [`assets/skills-catalog.md`](skills-catalog.md) - ---- - -## Adding a New Skill to an Existing Domain - -1. Create the skill folder under `references/<domain>/references/<skill-name>/` -2. Add a `SKILL.md` inside the skill folder -3. Update the domain's router `SKILL.md` — add the skill to **Routing Table**, **Skills**, and **Skill Locations** (per the [domain template](templates/domain-template.md)) -4. Register the skill in the **Skills Catalog** in `assets/skills-catalog.md` with its triggers -5. Add the skill's intent patterns to the **Intent → Domain Routing** table in `assets/skills-catalog.md` - ---- - -## Script References in SKILL.md - -When a skill needs to invoke a CLI tool (e.g., `eds-code-sync`, `rule-validate`, `form-sync`), follow these rules: - -### Always use `${CLAUDE_PLUGIN_ROOT}` - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/<tool-name>" <args> -``` - -### Rules - -| # | Rule | -|---|------| -| 1 | **Use `${CLAUDE_PLUGIN_ROOT}` for all script paths** — never construct paths from the skill's base directory. Claude Code injects a `Base directory for this skill:` header into each skill at runtime — this is for resolving skill-local files (`assets/`, `references/`), **not** for locating scripts. | -| 2 | **Always include `forms-orchestrator/`** — `${CLAUDE_PLUGIN_ROOT}` points to the plugin root (the directory containing `.claude-plugin/`). Scripts live one level deeper at `forms-orchestrator/scripts/`. | -| 3 | **Never hardcode absolute paths** — no `/Users/...` or machine-specific paths in any SKILL.md. Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths and `<cwd>/<name>` style placeholders for documentation examples. | -| 4 | **Use relative paths only for skill-local assets** — files within the skill's own directory tree (e.g., `assets/`, `references/`) should use relative paths from the SKILL.md, not `${CLAUDE_PLUGIN_ROOT}`. | - -### Example - -``` -# ✅ Correct — uses CLAUDE_PLUGIN_ROOT with forms-orchestrator segment -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync" sync - -# ❌ Wrong — missing forms-orchestrator segment -"${CLAUDE_PLUGIN_ROOT}/scripts/eds-code-sync" sync - -# ❌ Wrong — hardcoded absolute path -"/Users/alice/forms-skills/skills/aem/forms/forms-orchestrator/scripts/eds-code-sync" sync - -# ❌ Wrong — relative path from skill base directory -"../../../../../../scripts/eds-code-sync" sync -``` diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/skill-resolution.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/skill-resolution.md deleted file mode 100644 index d59571bc..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/skill-resolution.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: skill-resolution -description: > - How plan steps resolve to domain skills. Used by the orchestrator - when executing plan-driven workflows. ---- - -# Resolving a Plan Step to a Skill - -When a plan step declares a skill, resolve it as follows: - -1. Look up the **skill** in the Skills Catalog (`assets/skills-catalog.md`) → confirm it exists and find which domain owns it -2. Look up the **domain** in the Registry table (in `domains/SKILL.md`) → get the router path -3. Route to the domain's router SKILL.md → the domain router handles invocation - -``` -Plan step declares: - skill: add-rules - │ - ▼ -Skills Catalog: - #8: logic › add-rules ✅ exists - │ - ▼ -Domain Registry: - logic → references/logic/SKILL.md - │ - ▼ -Route to logic/SKILL.md → invokes add-rules -``` - -If a plan step declares a skill that doesn't exist in the catalog, halt and report the error. Do not guess. - ---- - -## Resolution Rules - -1. **Exact match only** — the `domain` + `skill` pair must exist in the Skills Catalog. No fuzzy matching. -2. **Domain router delegates** — once resolved, the domain's SKILL.md handles actual skill invocation. This registry does not invoke skills directly. -3. **Missing skill = hard stop** — if the declared skill doesn't exist, halt execution and report the error to the user. Do not attempt to substitute a different skill. -4. **Missing domain = hard stop** — if the declared domain doesn't exist in the Registry, halt and report. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/skills-catalog.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/skills-catalog.md deleted file mode 100644 index 9a0692d2..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/skills-catalog.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: skills-catalog -description: > - Complete catalog of all skills across all domains, plus intent-based routing - for direct domain routing. ---- - -# Skills Catalog - -All 16 skills across 6 domains. - -| # | Domain | Skill | Purpose | Triggers | -|---|--------|-------|---------|----------| -| 1 | `analysis` | `analyze-requirements` | Parse requirements / mockups → form specification | analyze, requirements, create spec, plan form | -| 2 | `analysis` | `analyze-v1-form` | Read legacy v1 form JSON → Screen.md for migration | v1 form, legacy form, migrate, old form | -| 3 | `analysis` | `create-screen-doc` | Create standardized Screen.md (11-section format) | document screen, new screen doc | -| 4 | `analysis` | `review-screen-doc` | Validate Screen.md against form JSON (quality gate) | review screen, check screen, validate doc | -| 5 | `build` | `scaffold-form` | Bootstrap a new empty form template | scaffold, new form, bootstrap | -| 6 | `build` | `create-form` | Create / modify form JSON — fields, panels, fragments | create form, add field, add panel, modify form | -| 7 | `build` | `create-component` | Build custom components / extend OOTB field types | custom component, viewType, extend field | -| 8 | `logic` | `add-rules` | Add business rules (show/hide, validate, navigate, events) | add rule, show hide, validation, visibility | -| 9 | `logic` | `create-function` | Create custom JS functions (calculations, API calls) | custom function, calculation, JS function | -| 10 | `logic` | `optimize-rules` | Refactor & audit rules (visual vs function split) | optimize rules, refactor, too many rules | -| 11 | `integration` | `manage-apis` | Sync FDM, add API definitions, build JS clients | API, FDM, OpenAPI, cURL, api client | -| 12 | `infra` | `setup-workspace` | Initialize project, configure credentials | setup, workspace, credentials, initialize | -| 13 | `infra` | `sync-forms` | Pull / push / list / create forms on AEM | push form, pull form, sync form, form list | -| 14 | `infra` | `sync-eds-code` | Pull / push EDS code, branch, open PR on GitHub | push code, pull code, git push, PR | -| 15 | `infra` | `git-sandbox` | Sandboxed git operations (commit, push, reset) | git commit, git reset, git status | -| 16 | `context` | `manage-context` | Update project reports, save progress, session log | save progress, update reports, handover, session | - ---- - -## Intent → Domain Routing - -When the orchestrator uses direct domain routing, use this table. First match wins. - -| User Intent Pattern | Domain | Typical Skills Invoked | -|---------------------|--------|------------------------| -| Setup, credentials, sync forms/code, git operations, deploy | `infra` | `setup-workspace`, `sync-forms`, `sync-eds-code`, `git-sandbox` | -| Analyze requirements, document screens, review docs, migrate v1 | `analysis` | `analyze-requirements`, `create-screen-doc`, `review-screen-doc`, `analyze-v1-form` | -| Scaffold form, create/modify form JSON, custom components | `build` | `scaffold-form`, `create-form`, `create-component` | -| Add rules, custom functions, optimize rules | `logic` | `add-rules`, `create-function`, `optimize-rules` | -| Sync/add/build APIs, FDM, OpenAPI | `integration` | `manage-apis` | -| Update reports, save progress, session log | `context` | `manage-context` | - -> If the intent is ambiguous, present the top 2–3 matching domains to the user and let them choose. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/templates/domain-template.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/templates/domain-template.md deleted file mode 100644 index 57ba863e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/assets/templates/domain-template.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -name: <domain-id> -description: > - <One-line purpose of this domain> -type: domain -triggers: - - <trigger keyword 1> - - <trigger keyword 2> - - <trigger keyword 3> -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# <Domain Name> — Domain Router - -> **Base pattern:** This template is a forms-specific specialization of the [Skill Router Template](../../../../../../../../../docs/skill-architecture/skill-router-template.md). See the [Skill Architecture Guide](../../../../../../../../../docs/skill-architecture/README.md) for the generalized patterns (directory structure, routing tables, guidelines). - -**ID:** `<domain-id>` -**Version:** 0.1 -**Description:** <One-line purpose of this domain> - -This router does not implement — it delegates. It matches user intents to the correct skill within this domain. - ---- - -## Routing Table - -First match wins. - -| Intent | Examples | Skill | -|--------|----------|-------| -| <Intent category 1> | "<example phrase>", "<example phrase>" | `<skill-id-1>` | -| <Intent category 2> | "<example phrase>", "<example phrase>" | `<skill-id-2>` | -| <Intent category 3> | "<example phrase>", "<example phrase>" | `<skill-id-3>` | - -> If the intent is ambiguous between two skills, present the options to the user and let them choose. - ---- - -## Skills - -All skills owned by this domain. - -| # | Skill | Purpose | Triggers | -|---|-------|---------|----------| -| 1 | `<skill-id-1>` | <One-line purpose> | <comma-separated trigger keywords> | -| 2 | `<skill-id-2>` | <One-line purpose> | <comma-separated trigger keywords> | -| 3 | `<skill-id-3>` | <One-line purpose> | <comma-separated trigger keywords> | - -### Skill Locations - -| Skill | Path | -|-------|------| -| `<skill-id-1>` | [`references/<skill-id-1>/SKILL.md`](references/<skill-id-1>/SKILL.md) | -| `<skill-id-2>` | [`references/<skill-id-2>/SKILL.md`](references/<skill-id-2>/SKILL.md) | -| `<skill-id-3>` | [`references/<skill-id-3>/SKILL.md`](references/<skill-id-3>/SKILL.md) | - ---- - -## Guard Policies - -Guard policies are constraints that apply across all skills in this domain. They prevent unsafe or incorrect operations. - -> **<guard-policy-id>:** <Description of what is forbidden and why. Example: "Never edit `.rule.json` directly. All business logic must go through `add-rules`."> - -> **<guard-policy-id>:** <Description of another constraint.> - -Remove this section if the domain has no guard policies. Most domains should have at least one. - ---- - -## File Locations - -Canonical paths for assets managed by skills in this domain. - -| Asset | Path | -|-------|------| -| <Asset type 1> | `<canonical/path/pattern>` | -| <Asset type 2> | `<canonical/path/pattern>` | -| <Asset type 3> | `<canonical/path/pattern>` | - ---- - -## Dependencies - -Other domains or skills that this domain's skills may delegate to or depend on. - -| Dependency | Direction | Reason | -|------------|-----------|--------| -| `<other-domain>` | This domain → `<other-domain>` | <Why this domain depends on or delegates to the other> | -| `<other-domain>` | `<other-domain>` → This domain | <Why the other domain feeds into this one> | - -Remove this section if the domain has no cross-domain dependencies. - ---- - -## Plan Integration - -Which plan types commonly invoke skills in this domain. - -| Plan Type | Typical Step(s) | Skill(s) Invoked | -|-----------|-----------------|------------------| -| `<plan-type>` | Step <N>: <Name> | `<skill-id>` | -| `<plan-type>` | Step <N>: <Name> | `<skill-id>` | - -Remove this section if no plan types typically invoke this domain's skills. - ---- - -## Extending This Domain - -### Adding a New Skill - -1. Create the skill folder: `references/<domain-id>/references/<skill-name>/` -2. Add a `SKILL.md` inside the skill folder — this is the skill's entry point -3. Add the skill to the **Routing Table** above with its intent patterns -4. Add the skill to the **Skills** table and **Skill Locations** table above -5. Register the skill in the domain registry (`../../../SKILL.md`) — both the **Skills Catalog** (`../../assets/skills-catalog.md`) and **Intent → Domain Routing** tables -6. If the skill manages new file types, add them to the **File Locations** table -7. If needed, add guard policies that apply to the new skill - -### Creating a New Domain from This Template - -1. Copy this file to `references/domain-registry/references/<domain-name>/SKILL.md` -2. Update the YAML frontmatter — set `name`, `description`, and `triggers` -3. Fill in the routing table — one row per skill in the domain -4. Fill in the skills table — catalog every skill with its purpose and triggers -5. Define guard policies — constraints that prevent unsafe operations -6. Fill in file locations — canonical paths for assets this domain manages -7. Map cross-domain dependencies if any exist -8. Map plan types that commonly invoke skills in this domain -9. Create skill sub-folders under `references/<domain-name>/references/<skill-name>/` -10. Register the domain in the domain registry `SKILL.md` (`../../../SKILL.md`) — **Registry**, **Skills Catalog** (`../../assets/skills-catalog.md`), and **Intent → Domain Routing** tables \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/SKILL.md deleted file mode 100644 index 8e50988f..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/SKILL.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -name: analysis -description: > - Domain router for analysis & documentation skills. Routes user intents - to the correct analysis skill based on input source. -type: domain -triggers: - - analyze - - requirements - - create spec - - plan form - - screen doc - - review screen - - v1 form - - legacy form - - migrate - - mockup - - figma -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Analysis — Domain Router - -- **ID:** `analysis` -- **Version:** 0.1 -- **Description:** Routes analysis and documentation intents to the correct skill based on input source. This router does not implement — it delegates. - ---- - -## Routing Table - -First match wins. - -| Intent | Skill | -|--------|-------| -| Parse requirements docs, mockups, or journey specs into a structured form specification | `analyze-requirements` | -| Read legacy v1 adaptive-form JSON and produce Screen.md docs for migration | `analyze-v1-form` | -| Create a standardized Screen.md for a form screen (11-section format) from screenshots or Figma | `create-screen-doc` | -| Validate a Screen.md against actual form JSON — quality gate | `review-screen-doc` | - -``` - ┌─ requirements doc ──→ analyze-requirements ─┐ - ├─ journey.md ────────→ analyze-requirements ─┤ - Input Source ──────────┤ ├──→ Screen.md - ├─ screenshots/figma ─→ create-screen-doc ───┤ - └─ v1 adaptive form ──→ analyze-v1-form ─────┘ - │ - review-screen-doc (quality gate) -``` - ---- - -## Skills - -| # | Skill | Purpose | Triggers | -|---|-------|---------|----------| -| 1 | `analyze-requirements` | Parse requirements docs / mockups into structured form specification | analyze, requirements, create spec, plan form, journey | -| 2 | `analyze-v1-form` | Read legacy v1 AEM form JSON and produce Screen.md docs for migration | v1 form, legacy form, migrate, adaptive form | -| 3 | `create-screen-doc` | Create standardized Screen.md per form screen (11-section format) | screen doc, create screen, screenshots, figma, mockup | -| 4 | `review-screen-doc` | Validate Screen.md against actual form JSON — quality gate | review screen, validate screen, quality gate | - -### Skill Locations - -| Skill | Path | -|-------|------| -| `analyze-requirements` | `references/analyze-requirements/SKILL.md` | -| `analyze-v1-form` | `references/analyze-v1-form/SKILL.md` | -| `create-screen-doc` | `references/create-screen-doc/SKILL.md` | -| `review-screen-doc` | `references/review-screen-doc/SKILL.md` | - ---- - -## Guard Policies - -> **screen-md-convergence:** All paths in this domain converge to produce Screen.md files. Every skill's output is either a Screen.md or feeds into one. - -> **quality-gate:** All Screen.md files MUST pass through `review-screen-doc` as a quality gate before leaving this domain. No Screen.md is considered complete until reviewed. - -> **no-guessing-endpoints:** Never guess API endpoints or service URLs. Mark any unknowns as `TBD` and flag them for the user. - -> **no-currentFormContext:** Never emit `PL.currentFormContext` references in any generated output. Use the documented data-binding patterns instead. - -> **intake-gate:** Before routing, confirm that input files (requirements, screenshots, v1 JSON, etc.) are present on disk. Do NOT proceed until files are confirmed. - ---- - -## File Locations - -| Asset | Path | -|-------|------| -| Screen docs | `refs/screens/<journey>/<screen-name>.md` | -| Plans | `plans/<journey>/NN-<title>.md` | -| Journey specs | `journeys/<journey-name>.md` | -| Screenshots | `journeys/<journey>/screens/<screen>/*.png`, `*.jpg`, `*.pdf` | -| V1 form JSON | `refs/<form-name>.v1.json` | - -### Intake Conventions - -| Source | Place In | Convention | -|--------|----------|------------| -| Screen.md | `journeys/<journey>/screens/<screen>/` | `Screen.md` | -| Journey.md | `journeys/` | `<journey-name>.md` | -| Screenshots | `journeys/<journey>/screens/<screen>/` | `*.png`, `*.jpg`, `*.pdf` | -| V1 Form JSON | `refs/` | `<form-name>.v1.json` | - ---- - -## Dependencies - -| Dependency | Domain | Purpose | -|------------|--------|---------| -| `review-screen-doc` → form JSON | infra (`sync-forms`) | Review skill needs the synced form JSON to validate Screen.md against | - ---- - -## Plan Integration - -How this domain participates in plan-driven execution. - -| When | Skill(s) Invoked | Role | -|------|-------------------|------| -| Plan generation — understanding requirements and producing specs | `analyze-requirements` | Parses requirements and produces initial Screen.md drafts | -| Plan execution — screen doc creation and review | `create-screen-doc`, `review-screen-doc` | Creates Screen.md files and validates them against form JSON before build proceeds | - ---- - -## Extending This Domain - -1. Create a new skill directory under `references/<skill-name>/`. -2. Add a `SKILL.md` inside that directory following the skill template. -3. Update the **Routing Table** above with the new intent → skill mapping. -4. Add the skill to the **Skills** table and **Skill Locations** sub-table. -5. Ensure the new skill's output either produces a Screen.md or feeds into one (per the **screen-md-convergence** policy). -6. If the skill is a quality gate, document it in **Guard Policies**. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/SKILL.md deleted file mode 100644 index 49f895b7..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/SKILL.md +++ /dev/null @@ -1,298 +0,0 @@ ---- -name: analyze-requirements -description: > - Analyze requirements documents, screen mockups, or journey maps to produce structured - form specifications. Use when starting a new form project from a requirements doc, - Screen.md, or journey.md. Produces field inventory, panel structure, rule requirements, - and API dependencies. Triggers: analyze requirements, create spec, plan form, Screen.md. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Analyze Requirements - -Parse requirements documents into structured form specifications ready for form creation. - -## When to Use - -- User provides a requirements document, Screen.md, journey.md, or design mockup -- A new form project needs to be planned before building -- You need to extract field inventory, panel structure, rule requirements, and API dependencies - -## Critical Rules - -1. **Act autonomously** — read the document, produce the spec. Don't ask "should I analyze this?" -2. **Mark unknowns as TBD** — if an API endpoint, data source, or behavior is unclear, mark it TBD rather than guessing -3. **No PL.currentFormContext references** — mark data sources as TBD instead -4. **Don't duplicate** — validation rules should NOT repeat constraints already captured in field properties -5. **Skip container panels** — only include panels that have visibility rules or meaningful grouping -6. **Complete field coverage** — every user-facing field must appear in the specification - -## Input Sources - -| Source Type | What to Look For | -|-------------|------------------| -| Requirements doc | Feature descriptions, field lists, business logic, API references | -| Screen.md | Structured screen documentation with fields, validation, visibility rules | -| Journey.md | Multi-step flow with screen transitions and navigation | -| Design mockup | Visual layout implying fields, sections, and flow | - -## Output: Form Specification Template - -Produce a structured markdown document with ALL of the following sections, in this order: - -### 1. Title and Overview - -``` -# <Form Name> — Form Specification - -**Source:** <input document name> -**Screens/Steps:** <count> -**Estimated Fields:** <count> -**Estimated Rules:** <count> -``` - -### 2. Panel Structure - -Map the form's top-level organization: - -``` -Form Root -├── Panel: <panel-name> — "<Display Title>" -│ ├── Field: <field-name> -│ └── Fragment: <fragment-name> (if reusable) -├── Panel: <panel-name> -│ └── ... -└── Submit Button -``` - -### 3. Field Inventory - -For each section/panel, produce a table: - -| Name | Title | Type | Required | Visible | Properties | -|------|-------|------|----------|---------|------------| -| `field_name` | Display Title | field-type | true/false | true/false | constraints, options, patterns | - -**Valid field types:** `text-input`, `number-input`, `date-input`, `drop-down`, `radio-group`, `checkbox-group`, `checkbox`, `email`, `file-input`, `plain-text`, `panel`, `button` - -**Properties column includes:** -- Validation patterns (regex) -- Min/max values -- Character limits -- Dropdown options (format: `Option1, Option2, Option3`) -- Placeholder text - -### 4. Validation Rules - -Only rules NOT already captured in field Properties: - -| Field | Trigger | Rule | Error Message | -|-------|---------|------|---------------| -| `field_name` | On blur / On change | Description | "Error text" | - -**Do NOT duplicate:** patterns, min/max, character limits, or required already in the field inventory. - -### 5. Visibility Rules - -| Component | Initially Visible | Show/Hide Condition | -|-----------|-------------------|---------------------| -| `field_name` | Yes/No | Condition that triggers show/hide | - -### 6. Business Rules - -Describe logic that goes beyond simple validation/visibility: - -- **On form load:** Pre-fill logic, initialization -- **Calculations:** Computed fields (e.g., total = subtotal + tax) -- **Conditional required:** Fields that become required based on other values -- **State transitions:** What happens when user completes a section - -Mark APIs and data sources as TBD: -- [ ] Pre-fill `field_name` from <source TBD> -- [ ] Call API for <purpose> — *API TBD* - -### 7. API Dependencies - -| Order | API | Purpose | Trigger | -|-------|-----|---------|---------| -| 1 | `api-name` (TBD) | Description | When triggered | - -### 8. Fragment Candidates - -Identify reusable sections that should be fragments: - -| Section | Reason | Reused In | -|---------|--------|-----------| -| Address fields | Common pattern | Multiple forms | - -### 9. Navigation Flow - -For multi-step forms: - -| Step | Panel | Next Condition | Back Condition | -|------|-------|----------------|----------------| -| 1 | Personal Details | On continue click | — | -| 2 | Employment | On continue click | On back click | - -### 10. Summary & Complexity - -| Section | Fields | Validation | Visibility | Business | APIs | Fragments | -|------------------|--------|------------|------------|----------|------|-----------| -| Section Name | X | X | X | X | X | X | -| **Screen Total** | **X** | **X** | **X** | **X** | **X** | **X** | - -**Complexity Check (per screen):** - -| Metric | Value | Threshold | Status | -|--------------------|-------|-----------|--------| -| Fields | X | ≤ 25 | 🟢/🟡/🔴 | -| Validation rules | X | ≤ 15 | 🟢/🟡/🔴 | -| Visibility rules | X | ≤ 10 | 🟢/🟡/🔴 | -| Business rules | X | ≤ 6 | 🟢/🟡/🔴 | -| API calls | X | ≤ 3 | 🟢/🟡/🔴 | -| Fragments | X | ≤ 3 | 🟢/🟡/🔴 | -| Logical sections | X | ≤ 4 | 🟢/🟡/🔴 | - -**Complexity Check (journey aggregate):** - -| Metric | Value | Threshold | Status | -|----------------------------|-------|-----------|--------| -| Total screens | X | ≤ 15 | 🟢/🟡/🔴 | -| Total fields (all screens) | X | ≤ 150 | 🟢/🟡/🔴 | -| Total rules (all types) | X | ≤ 100 | 🟢/🟡/🔴 | -| Total APIs (unique) | X | ≤ 12 | 🟢/🟡/🔴 | -| Total fragments | X | ≤ 10 | 🟢/🟡/🔴 | - -**Severity thresholds:** -- 🟢 Green: within threshold -- 🟡 Amber: up to 50% over threshold — flag for human review -- 🔴 Red: more than 50% over threshold — must split screen/journey or extract fragments - -> **Gate:** If any metric is 🔴, add a Complexity Warning to Open Items (section 11) with a recommended action. - -### 11. Open Items - -- [ ] Item needing clarification -- [ ] API endpoint TBD -- [ ] Data source TBD - -## Workflow - -1. **Read the input document** — understand the full scope -2. **Identify panels/sections** — group fields logically by screen or functional area -3. **Extract all fields** — list every data input with type, label, constraints -4. **Separate validation rules** — only rules not captured in field properties -5. **Map visibility logic** — initially hidden components and their show/hide conditions -6. **Document business rules** — calculations, state transitions, conditional behavior -7. **List API dependencies** — mark all as TBD for verification -8. **Identify fragment candidates** — sections reusable across forms -9. **Map navigation** — step flow for multi-step forms -10. **Compile summary and evaluate complexity** — populate the Summary & Complexity tables, flag any 🟡/🔴 metrics -11. **Generate execution plans** — decompose the specification into sequentially numbered plans at `plans/<journey>/` (see Plan Generation below) - -## What Happens Next - -After the specification is reviewed and approved: -1. **Execution plans** are generated at `plans/<journey>/` — one plan per functional concern -2. Plans execute sequentially — each plan invokes the appropriate skill(s) -3. After each plan completes, `.agent/handover.md` is updated with the Plan Execution Status dashboard - -## Plan Generation - -After the form specification is reviewed, generate sequentially numbered plan files at `plans/<journey>/`. - -### Plan File Convention - -- **Path:** `plans/<journey>/NN-<short-title>.md` -- **Numbering:** Zero-padded two digits: `01`, `02`, ..., `10`, `11` -- **Naming:** Lowercase, hyphen-separated: `01-form-structure.md`, `07-api-prefill.md` -- **Execution order:** Sequential — each plan declares its dependencies explicitly - -### Plan Template - -Each plan file must follow this structure: - -``` -# Plan NN: <Title> - -**Source:** `journeys/<journey>.md` section X.X / `Screen.md` references -**Skills:** <primary skills invoked: create-form, add-rules, create-function, manage-apis, create-component> -**Depends on:** Plan NN (description) — or "None (first plan)" - ---- - -## Objective - -<1-2 sentences: what this plan delivers and why> - -## Scope - -### In Scope - -- <specific deliverable 1> -- <specific deliverable 2> - -### Out of Scope - -- <explicitly excluded item> (covered in Plan NN) - -## Specification - -<The detailed spec — varies by plan type:> -<- For Build plans: panel structure tree, field specification tables> -<- For Logic plans: rule tables, custom function signatures, event flows> -<- For Integrate plans: API definitions, request/response, mapping tables> -<- For Deploy plans: deployment targets, verification steps> - -## Steps to Execute - -1. <Step 1 with specific skill/tool invocation> -2. <Step 2> -3. ... -N. **Validate and push** - -## Acceptance Criteria - -- [ ] <Testable criterion 1> -- [ ] <Testable criterion 2> -- [ ] <Form passes validation> -- [ ] <Renders/deploys without errors> -``` - -### Plan Decomposition Guidelines - -When breaking a form specification into plans: - -| Principle | Guideline | -|-----------|-----------| -| **One concern per plan** | Each plan addresses one functional area — don't mix form structure with API integration | -| **Deployable increment** | After each plan, the form should be in a valid, deployable state (even if incomplete) | -| **Explicit dependencies** | Every plan declares which prior plans it depends on — no implicit assumptions | -| **First plan = skeleton** | Plan 01 always creates the full form structure (all panels, even empty placeholders for later plans) | -| **APIs before rules** | Integration plans (API clients) come before logic plans that consume those APIs | -| **Error handling last** | Cross-cutting concerns like error handling and session management come at the end | -| **Max 15 plans per journey** | If you need more, the journey is likely too complex — check journey-level complexity thresholds | - -### Typical Plan Sequence - -| Order | Focus | Primary Skills | Example | -|-------|-------|---------------|---------| -| 01 | Form structure + primary fields | `create-form`, `scaffold-form` | Panels, field types, basic validation | -| 02–05 | Screen-by-screen logic | `create-form`, `add-rules`, `create-function` | Visibility rules, business rules per screen | -| 06–08 | API integration | `manage-apis`, `create-function`, `add-rules` | API clients, prefill, save/submit | -| 09 | Complex workflows | `create-function`, `add-rules` | Multi-step flows (e.g., OTP, verification) | -| 10 | Error handling & edge cases | `create-function`, `add-rules` | Session management, error modals, fallbacks | - -## Exclusions - -Do NOT include in the specification: -1. Container panels that are just wrappers with no visibility rules -2. Duplicate validation (already in field Properties) -3. Screenshots or visual mockups -4. Source code references -5. CSS/styling details -6. Detailed API request/response payloads (document separately) \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/eval/eval-plan.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/eval/eval-plan.md deleted file mode 100644 index b02db971..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/eval/eval-plan.md +++ /dev/null @@ -1,33 +0,0 @@ -# analyze-requirements — Eval Plan - -## Automated - -No automated tests — this skill is pure reasoning with no CLI tools. - -## Manual (E2E) - -### Prompt -> Analyze these requirements for a Contact Us form: -> - Full Name (required, 2-50 chars) -> - Email (required, valid email) -> - Phone (optional) -> - Inquiry Type (dropdown: General, Support, Sales) -> - Message (multiline, required when Inquiry Type is "Support") -> - On form submit, show thank-you message - -### Expected Behavior -- Produces a structured specification with all 11 sections -- Field inventory lists all 5 fields with correct types -- Rule requirements mention show/hide for message based on inquiry type -- No hallucinated APIs or extra fields -- Does NOT ask clarifying questions for clearly specified fields -- Marks any unknowns as TBD - -### Checklist -- [ ] Output has structured sections (field inventory, panel structure, rules, etc.) -- [ ] All 5 fields listed with correct types -- [ ] Rule requirements mention visibility for message field -- [ ] No hallucinated content - -### Fixture -See [fixtures/sample-requirements.md](fixtures/sample-requirements.md) for a sample requirements document. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/eval/fixtures/sample-requirements.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/eval/fixtures/sample-requirements.md deleted file mode 100644 index 7894b85c..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-requirements/eval/fixtures/sample-requirements.md +++ /dev/null @@ -1,29 +0,0 @@ -# Contact Us Form — Requirements - -## Overview -A simple contact form that allows website visitors to submit inquiries. - -## Fields - -### Contact Information Panel -| Field | Type | Required | Validation | -|-------|------|----------|------------| -| Full Name | Text | Yes | Min 2, Max 50 characters | -| Email | Email | Yes | Valid email format | -| Phone | Phone | No | — | - -### Inquiry Panel -| Field | Type | Required | Validation | -|-------|------|----------|------------| -| Inquiry Type | Dropdown | Yes | Options: General, Support, Sales | -| Message | Text (multiline) | Yes | Min 10 characters | - -## Business Rules -1. When Inquiry Type is "Support", show a prominent message field with required validation -2. When Inquiry Type is "Sales", prefill message with "I'm interested in learning more about..." - -## API Integrations -None for this form. - -## Submit Action -Display a thank-you message on successful submission. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-v1-form/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-v1-form/SKILL.md deleted file mode 100644 index be520d88..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/analyze-v1-form/SKILL.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -name: analyze-v1-form -description: > - Analyze legacy v1 AEM Adaptive Form JSON files through direct human-like reading to - identify screens, extract fields and rules, and compare across journeys. Use when - migrating from v1 AEM forms — NOT for analyzing journey documents or requirements - (use analyze-requirements for that). Does NOT use code or scripts — pure reasoning only. - Triggers: v1 form, legacy form, migrate form, v1 JSON, old form, AEM migration, - extract screens, extract fields, compare journeys. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Analyze v1 Form - -Analyze legacy AEM v1 Adaptive Form JSON files through **direct reading and human reasoning** to -identify screens, extract fields and business rules, and produce structured Screen.md -documentation for migration to Edge Delivery forms. - -## When to Use - -- User asks to analyze a v1 AEM form JSON file -- User wants to identify screens in a legacy journey -- User needs fields, rules, or fragments extracted from form JSON -- User wants to compare two or more journeys side by side -- User references a `.json` file from a v1 adaptive form export - -## Critical Rules - -1. **Read JSON directly** — open the file, read it section by section like a human analyst. NEVER write scripts, parsers, or automated heuristics to process the JSON -2. **Distinguish screens from non-screens** — popups, helpers, loaders, and nested sub-panels are NOT screens (see Screen Definition below) -3. **Document everything in Screen.md format** — every screen gets a structured markdown file following the Output Template -4. **Use `name` not panel keys** — panel keys like `panel_1239854573` are auto-generated; always use the `name` property to identify panels -5. **Mark unknowns as TBD** — if an API endpoint, field purpose, or rule behavior is unclear, mark it TBD rather than guessing -6. **Complete field coverage** — every user-facing field in each screen must appear in the documentation - -## JSON Navigation - -### How to Find Screens in the JSON Hierarchy - -The top-level structure of every v1 form JSON is: - -``` -guideContainer -├── prefillService, schemaRef, themeRef (form metadata) -└── rootPanel - ├── initScript (form-level initialization rules) - └── items - ├── header (SKIP — not a screen) - └── PLPanel - └── NavigationPanel ← SCREENS ARE DIRECT CHILDREN HERE - └── items - ├── multipleAccountPanel ← Screen 01 - ├── basicDetailsScreen ← Screen 02 - └── ... -``` - -### Navigation Structure Variations - -Different journeys use different navigation patterns. Identify which pattern applies -before enumerating screens: - -| Journey Type | Path to Screens | Layout | Typical Screen Count | -|-------------|-----------------|--------|---------------------| -| Full (ETBWO, NTB) | `rootPanel → PLPanel → NavigationPanel → items` | Navigation tabs | 16–17 | -| Wizard (ETB10SEC) | `rootPanel → PLLoanPagePanel → PLNavigationPanel → items` | `fd/af/layouts/panel/wizard` | 4 | -| Partner (A2A) | `rootPanel → LoanFormPanel → LoanFormA2A → items` | `fd/af/layouts/panel/wizard` | 3 | - -For wizard layouts, look for `"sling:resourceType": "fd/af/layouts/panel/wizard"` — -direct children of that panel are the screens. - -## Screen Definition - -### What IS a Screen - -A screen is a **logical step in the user journey** — what the user sees at a specific -point in time. Screens have these characteristics: - -- **User-facing purpose** — represents a discrete step (e.g., "Select your account", "Verify details") -- **Progress indicator** — typically shows "Step XX — XX% complete" -- **Contains related fields/fragments** — groups inputs needed for that journey step -- **Navigation target** — the form navigates TO this panel after user actions -- **Initially hidden** — most have `"visible": false`, shown conditionally based on progress - -### What is NOT a Screen - -| Category | Examples | How to Identify | -|----------|----------|-----------------| -| Popups | `bre2failurepopupPanel`, `errorPopup`, `keyFacPanel`, `OVDpopup` | Name contains "popup", "error", "failure" | -| Helper panels | `formRenderingFragment`, `loanStepsPanel` | Technical/progress components, no user inputs | -| Nested sub-panels | Panels inside screens that organize content | Not direct children of navigation panel | -| Loaders/spinners | BRE Loader panels | Loading states that auto-transition | - -## Analysis Workflow - -### Step 1: Understand the JSON Structure - -Read the JSON from the top. Note form-level metadata (`prefillService`, `schemaRef`, -`themeRef`) and the `initScript` on `rootPanel` — this contains form-level initialization -rules. - -### Step 2: Locate the Navigation Panel - -Follow the hierarchy to find the navigation container. Identify which navigation -variation applies (full, wizard, or partner). The direct children of this panel are -screen candidates. - -### Step 3: Identify Screens vs Non-Screens - -For each direct child of the navigation panel, ask: - -1. Does it have a user-facing purpose? → Likely a screen -2. Does the name contain "popup", "error", "failure"? → NOT a screen -3. Is it a progress indicator or technical helper? → NOT a screen -4. Does it represent a step in the user journey? → Screen - -### Step 4: Extract Screen Details - -For each confirmed screen, read its full nested content and extract: - -- **Basic info** — `name`, `jcr:title`, `visible`, CSS class, layout -- **Fragments** — any node with a `fragRef` property (note the fragment path) -- **Fields** — all user input components (see Field Extraction) -- **Rules** — all business logic scripts (see Rule Extraction) -- **Navigation** — back/continue button targets - -### Step 5: Document Each Screen - -Write a Screen.md file for each screen following the Output Template below. - -### Step 6: Cross-Journey Comparison (if applicable) - -When comparing journeys, match screens by purpose, compare fragments and rules, -and note differences (see Cross-Journey Comparison). - -## Field Extraction - -Identify fields by their `sling:resourceType` property: - -| resourceType | Field Type | -|-------------|------------| -| `fd/af/components/guidetextbox` | text-input | -| `fd/af/components/guidenumericbox` | number-input | -| `fd/af/components/guidedropdownlist` | drop-down | -| `fd/af/components/guideradiobutton` | radio-group | -| `fd/af/components/guidecheckbox` | checkbox | -| `fd/af/components/guidebutton` | button | -| `fd/af/components/guidedatepicker` | date-input | - -For each field, capture: `name`, `jcr:title`, `mandatory`, `bindRef`, `visible`, -`maxChars`, `validatePictureClause` (pattern), and any enum/options. - -## Rule Extraction - -Rules are embedded as script properties on panels and fields. Look for these properties: - -| Property | Trigger | Purpose | -|----------|---------|---------| -| `initScript` | Panel/field initialization | Set initial values, call prefill APIs, configure state | -| `valueCommitScript` | Field value change (on blur) | Validate input, call APIs, update dependent fields | -| `clickExp` | Button click | Navigate, submit, call APIs | -| `validateExp` | Field validation | Custom validation beyond pattern/required | -| `visibleExp` | Visibility condition | Show/hide based on other field values | - -For each rule, document: - -| Aspect | What to Capture | -|--------|----------------| -| **Component** | Which field or panel owns the rule | -| **Trigger** | When it fires (init, blur, click, etc.) | -| **Intent** | What the rule is trying to accomplish | -| **Depends On** | Which other fields/values it reads | -| **Affects** | Which fields/panels it modifies | - -## Cross-Journey Comparison - -When comparing two or more journeys: - -1. **Match screens by purpose** — not all screens exist in all journeys. Match by what the screen does, not its panel name -2. **Compare fragments** — identify shared vs unique fragments across journeys -3. **Compare rules** — the same field may have different rules per journey (e.g., PAN validation differs between NTB and ETBWO) -4. **Note structural differences** — different navigation types, screen counts, and flow variations - -## Output Template - -Each screen produces a Screen.md with this structure: - -``` -# Screen XX: [Screen Name] - -**Progress:** Step XX — "[Title]" (XX% complete) -**Journey:** [Journey Name] -**Form Path:** [Form path from JSON] - ---- - -## Panel Structure - -### Main Panel: [Panel Name] (Key: [panel_key]) - -| Property | Value | -|----------|-------| -| **Panel Name** | `panelName` | -| **Title** | "Panel Title" | -| **Visible** | false | -| **Layout** | gridFluidLayout2 | - ---- - -## Navigation - -| Action | Destination | -|--------|-------------| -| **Back Button** | Previous screen name | -| **Continue Button** | Next screen name | - ---- - -## Content - -### [Section Name] - -| Name | Title | Type | dataRef | Required | Visible | Properties | -|------|-------|------|---------|----------|---------|------------| -| `fieldName` | Field Title | text-input | `$.path` | true | true | maxChars: 20 | - ---- - -## Validation Rules - -| Field | Trigger | Rule | Error Message | -|-------|---------|------|---------------| -| `fieldName` | On blur | Required field | "Please enter value" | - ---- - -## Visibility Rules - -| Component | Initially Visible | Shown When | -|-----------|-------------------|------------| -| `panelName` | No | Screen becomes active | - ---- - -## Business Rules - -### On Screen Load -- Initialize field values -- Call prefill API -- Pre-fill fields from response - -### On Button Click -- Validate fields -- Call API -- Navigate to next screen - ---- - -## API Calls - -| Order | API | Purpose | Trigger | -|-------|-----|---------|---------| -| 1 | `apiName.json` | Description | On screen load | - ---- - -## Fragment References - -| Fragment Name | Fragment Path | Purpose | -|---------------|---------------|---------| -| `fragmentName` | `/content/dam/formsanddocuments/.../fragment` | Description | - ---- - -## Summary - -| Section | Fields | Validation | Visibility | Business | APIs | Fragments | -|------------------|--------|------------|------------|----------|------|-----------| -| Section Name | X | X | X | X | X | X | -| **Screen Total** | **X** | **X** | **X** | **X** | **X** | **X** | - -### Complexity Check - -| Metric | Value | Threshold | Status | -|--------------------|-------|-----------|--------| -| Fields | X | ≤ 25 | 🟢/🟡/🔴 | -| Validation rules | X | ≤ 15 | 🟢/🟡/🔴 | -| Visibility rules | X | ≤ 10 | 🟢/🟡/🔴 | -| Business rules | X | ≤ 6 | 🟢/🟡/🔴 | -| API calls | X | ≤ 3 | 🟢/🟡/🔴 | -| Fragments | X | ≤ 3 | 🟢/🟡/🔴 | -| Logical sections | X | ≤ 4 | 🟢/🟡/🔴 | - ---- - -## Open Items - -- [ ] Item needing clarification -- [ ] API endpoint TBD -``` - -## Output Structure - -When analyzing a complete journey, produce: - -``` -{output-directory}/{journey-name}/ -├── README.md # Journey overview with screen list -├── WORKFLOW.md # User flow, API sequence, business rules -└── screens/ - ├── 01-{screen-name}/ - │ └── Screen.md - ├── 02-{screen-name}/ - │ └── Screen.md - └── ... -``` - -## What This Skill Does NOT Do - -- Does NOT write code, scripts, or parsers -- Does NOT generate form JSON or AEM components -- Does NOT modify the source JSON files -- Does NOT use tool commands — this is pure analysis and documentation \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/create-screen-doc/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/create-screen-doc/SKILL.md deleted file mode 100644 index edb4b5b1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/create-screen-doc/SKILL.md +++ /dev/null @@ -1,358 +0,0 @@ ---- -name: create-screen-doc -description: > - Creates Screen.md documentation for a particular form screen based on - reference documentation and form JSON. Extracts fields, validation rules, - visibility logic, business rules, and API calls into a standardised - 11-section document. Use when creating new screen documentation from scratch. - Triggers: create screen doc, document screen, new screen documentation, - Screen.md, write screen doc. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Screen Documentation Creator - -Creates `Screen.md` documentation files for form screens based on reference documentation and the actual form JSON definition. - ---- - -## When to Use - -- Creating a new `Screen.md` from scratch for a screen that has no documentation yet -- Documenting a screen after identifying it in a journey analysis -- Generating initial screen documentation from a form JSON definition -- Building out the `journey/<journey-name>/screens/<screen-name>/Screen.md` file for a specific screen - ---- - -## Critical Rules - -1. **Always derive from the actual JSON** — every field name, type, dataRef, required flag, visible flag, and constraint must come from the form JSON, not from assumptions -2. **No duplicate information** — if a constraint (pattern, min/max, character limit) appears in the Content Properties column, do NOT repeat it in Validation Rules -3. **No container panels** — omit panels that are purely structural wrappers with no visibility rules -4. **No code references** — never include `PL.currentFormContext` setter/getter references; mark data sources as TBD instead -5. **No UI/UX details** — skip CSS classes, styling notes, layout specifics, and screenshot references -6. **Mark unknowns as TBD** — anything that cannot be resolved from the JSON (API endpoints, pre-fill sources, ambiguous business logic) goes into Open Items with a clear TBD marker -7. **Follow the 11-section structure exactly** — all sections must appear in order even if some are empty - ---- - -## Workflow - -1. **Read reference documentation** — locate the reference doc (e.g., `refs/afv1/README.md`) for the specific screen and journey flow -2. **Read the form JSON** — load the form definition (e.g., `refs/afv1/<form>.json`) and find all fields belonging to the target screen -3. **Identify screen sections** — group fields logically (Personal Details, Address, Employment, Bank Use, etc.) -4. **Extract fields** — list all fields with their properties from JSON; skip container panels -5. **Document validation** — only rules NOT already captured in Content Properties -6. **Document visibility** — hidden components and dynamic show/hide rules -7. **Document business logic** — mark APIs and data sources as TBD -8. **Write the Screen.md** — output to `journey/<journey-name>/screens/<screen-name>/Screen.md` -9. **Add Open Items** — list everything that needs verification - ---- - -## Document Structure (11 Sections, In Order) - -### 1. Title and Progress - -``` -# <Screen Name> - -**Progress:** Step XX - "<Step description>" (XX% complete) - ---- -``` - -### 2. Navigation - -``` -## Navigation - -| Action | Destination | -|--------|-------------| -| **Back Button** | <destination> | -| **Continue Button** | <what it triggers, then destination> | - ---- -``` - -### 3. Content Screen - -Organise fields by logical sections (Personal Details, Address, Employment, etc.). - -``` -## Content Screen - -### <Section Name> - -| Name | Title | Type | dataRef | Required | Visible | Properties | -|------|-------|------|---------|----------|---------|------------| -| `fieldName` | Display Title | field-type | `$.path` | true/false | true/false | constraints, options | -``` - -**Field Types:** text-input, number-input, date-input, drop-down, radio-group, checkbox, toggle, hidden, text-display, panel - -**Properties column includes:** -- Validation patterns -- Min/max values -- Character limits (maxChars / minLength) -- Dropdown options (format: Option1, Option2, Option3) -- Special behaviours - -### 4. Validation Rules - -Only include rules NOT already in Content Properties column. - -``` -## Validation Rules - -### <Field Name> - -| Trigger | Rule | Error Message | -|---------|------|---------------| -| On blur | Required field | "Error message" | -| On input | <behaviour not in Content> | "Error message" | -``` - -**DO NOT duplicate:** -- Patterns already in Content Properties -- Min/max values already in Content Properties -- Character limits already in Content Properties -- Dropdown options already in Content Properties - -### 5. Visibility Rules - -``` -## Visibility Rules - -### Initially Hidden Components - -| Component | Reason | Shown When | -|-----------|--------|------------| -| `fieldName` | Why hidden | Condition to show | - -### Dynamic Visibility Rules - -| Trigger | Action | -|---------|--------| -| `field` = value | Show/hide fields, change required | - -### Read-Only Conditions - -| Field | Becomes Read-Only When | -|-------|------------------------| -| `fieldName` | Condition | -``` - -### 6. Business Rules - -``` -## Business Rules - -### On Screen Load - -- [ ] Pre-fill `fieldName` (transformation) - *source TBD* -- [ ] Other initialisation logic - -### <Flow Name> (e.g., PAN Verification Flow) - -- [ ] Trigger condition - *API TBD* -- [ ] On success: actions -- [ ] On failure: actions -``` - -Mark all APIs as TBD. Do not use `PL.currentFormContext` references. - -### 7. API Calls - -``` -## API Calls - -### <Trigger Event> - -| Order | API | Purpose | -|-------|-----|---------| -| 1 | `api-name.json` | Description | -``` - -### 8. Error Popups - -``` -## Error Popups - -| Trigger | Popup Title | Message | Actions | -|---------|-------------|---------|---------| -| Condition | Title | "Message" | Button actions | -``` - -### 9. Form Context Variables - -``` -## Form Context Variables - -| Variable | Purpose | Source | -|----------|---------|--------| -| `variableName` | What it stores | Where it comes from | -``` - -### 10. Summary & Complexity - -``` -## Summary - -| Section | Fields | Validation | Visibility | Business | APIs | Fragments | -|------------------|--------|------------|------------|----------|------|-----------| -| Section Name | X | X | X | X | X | X | -| **Screen Total** | **X** | **X** | **X** | **X** | **X** | **X** | -``` - -After the totals table, add a **Complexity Check** sub-section: - -``` -### Complexity Check - -| Metric | Value | Threshold | Status | -|--------------------|-------|-----------|--------| -| Fields | X | ≤ 25 | 🟢/🟡/🔴 | -| Validation rules | X | ≤ 15 | 🟢/🟡/🔴 | -| Visibility rules | X | ≤ 10 | 🟢/🟡/🔴 | -| Business rules | X | ≤ 6 | 🟢/🟡/🔴 | -| API calls | X | ≤ 3 | 🟢/🟡/🔴 | -| Fragments | X | ≤ 3 | 🟢/🟡/🔴 | -| Logical sections | X | ≤ 4 | 🟢/🟡/🔴 | -``` - -**Severity thresholds:** -- 🟢 Green: within threshold -- 🟡 Amber: up to 50% over threshold — flag for human review -- 🔴 Red: more than 50% over threshold — must split screen or extract fragments before proceeding to build - -> **Gate:** If any metric is 🔴, add a Complexity Warning to Open Items with a recommended action (split screen, extract fragment, or consolidate rules into custom functions). - -### 11. Open Items - -``` -## Open Items / To Be Clarified - -### Missing Sections - -- [ ] Pre-fill data source - What is the source for on-screen-load pre-population? - -### API Endpoints TBD - -| API | Purpose | Reference API (to verify) | Needs | -|-----|---------|---------------------------|-------| -| API name | Purpose | `reference-api.json` | Verify endpoint, success/error response | - -### Other Missing Items - -- [ ] Item description -``` - ---- - -## JSON Resolution Patterns - -When resolving values from the form JSON: - -| Pattern | Where to Look | How to Document | -|---------|---------------|-----------------| -| **Dropdowns** | `enum` and `enumNames` arrays on the field object | Properties: `Options: Display1, Display2, ...` | -| **Patterns** | `pattern` property on the field | Properties column; do NOT duplicate in Validation | -| **Character limits** | `maxLength` / `minLength` properties | Properties: `maxChars: N` / `minLength: N` | -| **Number ranges** | `minimum` / `maximum` properties | Properties: `min: N, max: N` | -| **Required** | `required: true` on the field | Required column = `true` | -| **Hidden fields** | `visible: false` on the field | Visible column = `false`; add "Initially Hidden" in Visibility Rules | - ---- - -## What NOT to Include - -1. **Container panels** — panels that are just wrappers with no visibility rules -2. **Duplicate validation** — patterns/constraints already in Content Properties -3. **Screenshots** — skip for now -4. **Source traceability** — no JSON line references or JS file references -5. **API request/response payloads** — document separately if needed -6. **`PL.currentFormContext` references** — mark data sources as TBD instead -7. **UI/UX details** — CSS classes, styling notes, layout specifics -8. **Journey state logging** — internal logging implementation details - ---- - -## What TO Include - -1. **Only meaningful panels** — panels with visibility rules (initially hidden, conditional show) -2. **All user-facing fields** — input fields, dropdowns, radio groups, checkboxes -3. **Hidden fields** — that store computed or formatted values -4. **Error messages** — exact text for validation failures -5. **API references** — from reference doc, marked as TBD for verification -6. **Dropdown options** — complete list if known from JSON, or mark as TBD -7. **Pre-fill data sources** — as TBD checkboxes if not documented -8. **Validation error messages** — for any rule that has user-facing text - ---- - -## Example Output - -Output location: - -``` -journey/etbwo/screens/personal-details/Screen.md -``` - -Example structure: - -``` -# Personal Details Screen - -**Progress:** Step 01 - "Please verify your details" (10% complete) - ---- - -## Navigation -... - -## Content Screen -... - -## Validation Rules -... - -## Visibility Rules -... - -## Business Rules -... - -## API Calls -... - -## Error Popups -... - -## Form Context Variables -... - -## Summary -... - -## Open Items / To Be Clarified -... -``` - ---- - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Cannot find the screen in the form JSON | Search for a unique field name you know belongs to the screen; screens are usually nested inside a wizard panel | -| Dropdown options show as TBD | Look for `enum` / `enumNames` arrays on the field object in the JSON; if absent, keep as TBD in Open Items | -| Unsure which fields belong to this screen | Trace the panel hierarchy in the JSON — each wizard step typically maps to a top-level panel under the wizard | -| Field type unclear | Map JSON `fieldType` values: `text-input`, `number-input`, `date-input`, `drop-down`, `radio-group`, `checkbox`, `plain-text` → `text-display` | -| Business rule references code | Strip the code reference; describe the behaviour in plain language and mark the data source as TBD | -| Reference doc is missing sections | Document what you can from JSON; add all gaps to Open Items with TBD markers | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/review-screen-doc/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/review-screen-doc/SKILL.md deleted file mode 100644 index 6c8a1873..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/analysis/references/review-screen-doc/SKILL.md +++ /dev/null @@ -1,208 +0,0 @@ ---- -name: review-screen-doc -description: > - Reviews and critiques Screen.md documentation by cross-referencing against - actual v1 form JSON. Adds missing sections, removes duplicates, resolves - dropdowns, and validates field properties. Use when reviewing existing screen - documentation. Triggers: review screen doc, check Screen.md, validate - documentation, critique screen doc, missing sections. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Screen Documentation Reviewer - -Reviews and improves existing `Screen.md` files by validating every claim against the actual form JSON definition, removing duplicated information, and ensuring all required sections are present. - ---- - -## When to Use - -- Reviewing an existing `Screen.md` for correctness and completeness -- Validating documented fields, types, and constraints against a form JSON -- Cleaning up duplicate information between Content and Validation sections -- Resolving placeholder dropdown options with actual enum values from JSON -- Ensuring the standard 11-section structure is followed - ---- - -## Critical Rules - -1. **Always cross-reference against actual JSON** — never trust the Screen.md at face value; verify every field name, type, dataRef, required flag, visible flag, and constraint -2. **Remove duplicates** — if a validation rule merely restates a property already in the Content table (pattern, min/max, character limits), delete it from Validation Rules -3. **Mark unknowns in Open Items** — anything that cannot be resolved from the JSON (API endpoints, pre-fill sources, ambiguous business logic) goes into Open Items with a clear TBD marker -4. **No code references** — remove all `PL.currentFormContext` setter references; mark data sources as TBD instead -5. **No container panels** — remove panels that are just structural wrappers with no visibility rules - ---- - -## Review Workflow - -1. **Read the Screen.md** at `journey/<journey-name>/screens/<screen-name>/Screen.md` -2. **Read the form JSON** (e.g., `refs/afv1/pletb-wo.json`) and search for every field mentioned in the Screen.md -3. **Identify issues** — build a list of: missing fields, incorrect properties, duplicate validations, unresolved dropdowns, unnecessary container panels, unverified APIs -4. **Apply fixes** — update Content tables, remove duplicates from Validation, strip container panels, resolve dropdown options from JSON enums -5. **Update Open Items** — ensure every unresolved item is captured with a checkbox, and add an API Endpoints TBD table for any APIs needing verification - ---- - -## Structure Check - -Verify the document contains all 11 sections in this order: - -| # | Section | Purpose | -|---|---------|---------| -| 1 | Title and Progress | Screen name, step indicator position | -| 2 | Navigation | Back/Next buttons, targets | -| 3 | Content Screen | Field table: Name, Type, dataRef, Required, Visible, Properties | -| 4 | Validation Rules | Only rules NOT already captured in Content Properties | -| 5 | Visibility Rules | Conditions that show/hide fields or panels | -| 6 | Business Rules | Logic beyond simple validation (calculations, dependencies) | -| 7 | API Calls | Endpoints called on this screen | -| 8 | Error Popups | Modal/toast error definitions | -| 9 | Form Context Variables | Variables read or written on this screen | -| 10 | Summary & Complexity | Per-section metrics table + complexity check against thresholds | -| 11 | Open Items / To Be Clarified | Unresolved questions, TBD tables | - ---- - -## Content Validation - -For every field in the Content table, verify against the JSON: - -| Check | What to verify | -|-------|---------------| -| **Field exists** | Field name is present in the JSON | -| **Type is correct** | Matches JSON type (text-input, drop-down, date-input, etc.) | -| **dataRef is accurate** | Path matches the JSON `dataRef` property | -| **Required flag** | Matches JSON `required` value | -| **Visible flag** | Matches JSON `visible` value; if `false`, must appear in Visibility Rules as "Initially Hidden" | -| **Constraints** | pattern, maxLength, minLength, min, max from JSON are in Properties | -| **Dropdown options** | enum/enumNames from JSON are listed in Properties | - ---- - -## Common Issues - -| Issue | How to Fix | -|-------|-----------| -| Validation rule duplicates a Content Property (pattern, min/max, char limits) | Delete the rule from Validation; keep only triggers, error messages, and behaviors not in Content | -| Dropdown shows "TBD" but JSON has enum/enumNames | Extract options from JSON and update Content Properties: `Options: Value1, Value2, Value3` | -| Container panel listed in Content with no visibility rule | Remove the panel row entirely | -| `PL.currentFormContext` references in Business Rules or Form Context | Remove the reference; replace with a TBD note in Open Items | -| Field in JSON missing from Content table | Add the field row with all properties from JSON | -| API endpoint listed without verification | Move to Open Items → API Endpoints TBD table | -| UI/UX details (CSS, styling, screenshots) present | Remove — these do not belong in Screen.md | - ---- - -## What to Remove - -- **Container panels** that are purely structural wrappers (always visible, no conditions) -- **Duplicate validation rules** that restate pattern, min/max, or character limits already in Content Properties -- **`PL.currentFormContext`** setter/getter references — replace with TBD -- **UI/UX details** — CSS classes, styling notes, layout specifics -- **Journey state logging** — internal logging implementation details -- **Screenshot references** — image links or references to visual assets - ---- - -## What to Add - -- **Missing fields** discovered in JSON but absent from the Content table -- **Resolved dropdown options** extracted from JSON `enum` / `enumNames` arrays -- **API Endpoints TBD table** in Open Items for every API that lacks endpoint verification: - -``` -| API | Purpose | Reference API (to verify) | Needs | -|-----|---------|---------------------------|-------| -| <api> | <purpose> | `<reference>.json` | Verify endpoint, success/error response | -``` - -- **Pre-fill data source** as a TBD checkbox if not documented -- **Validation error messages** for any rule that is missing its user-facing message -- **Missing sections** — any of the 11 required sections not present in the document - ---- - -## JSON Resolution Patterns - -When resolving values from the form JSON: - -- **Dropdowns**: look for `enum` and `enumNames` arrays on the field object → list as `Options: Display1, Display2, ...` -- **Patterns**: look for `pattern` property → add to Content Properties, remove from Validation if duplicated -- **Character limits**: look for `maxLength` / `minLength` → add to Content Properties as `maxChars` / `minLength` -- **Required**: look for `required: true` → set Required column to `true` -- **Hidden fields**: look for `visible: false` → set Visible column to `false` and add "Initially Hidden" entry in Visibility Rules - ---- - -## Output Quality - -After review, the Screen.md must: - -- Follow the correct 11-section order -- Contain no duplicate information between Content and Validation -- Have no unnecessary container panels -- Have resolved dropdown options wherever JSON provides them -- List all unverified APIs in an Open Items TBD table -- Contain zero `PL.currentFormContext` references -- Have every field property verified against the actual JSON -- Have a Summary table with per-section breakdown of Fields, Validation, Visibility, Business, APIs, Fragments -- Have a Complexity Check table with thresholds evaluated - ---- - -## Complexity Gate - -After validating structure and content, evaluate the Summary metrics against complexity thresholds. - -### Screen-Level Thresholds - -| Metric | Green (≤) | Amber (≤) | Red (>) | -|--------------------|-----------|-----------|----------| -| Fields | 25 | 37 | 37 | -| Validation rules | 15 | 22 | 22 | -| Visibility rules | 10 | 15 | 15 | -| Business rules | 6 | 9 | 9 | -| API calls | 3 | 4 | 4 | -| Fragments | 3 | 4 | 4 | -| Logical sections | 4 | 6 | 6 | - -### Journey-Level Thresholds (aggregate across all screens) - -| Metric | Green (≤) | Amber (≤) | Red (>) | -|----------------------------|-----------|-----------|----------| -| Total screens | 15 | 22 | 22 | -| Total fields (all screens) | 150 | 225 | 225 | -| Total rules (all types) | 100 | 150 | 150 | -| Total APIs (unique) | 12 | 18 | 18 | -| Total fragments | 10 | 15 | 15 | - -### Severity Actions - -| Severity | Meaning | Action | -|----------|---------|--------| -| 🟢 Green | Within threshold | Pass — no action needed | -| 🟡 Amber | Up to 50% over threshold | Flag in Open Items for human review — may be acceptable with justification | -| 🔴 Red | More than 50% over threshold | **Block** — add Complexity Warning to Open Items with recommended action | - -### Recommended Actions for Red Flags - -| Metric Exceeded | Recommended Action | -|-----------------|--------------------| -| Fields > 37 | Split screen into multiple wizard panels | -| Validation rules > 22 | Consolidate into custom functions via `optimize-rules` | -| Visibility rules > 15 | Consolidate into a single custom function with a visibility map | -| Business rules > 9 | Extract into custom functions; review if screen is doing too much | -| API calls > 4 | Centralize API orchestration into a shared custom function | -| Fragments > 4 | Review if fragments can be merged or if screen should be split | -| Logical sections > 6 | Split screen — each section likely warrants its own wizard panel | -| Total screens > 22 | Split journey into sub-journeys (separate forms) | -| Total fields > 225 | Split journey into sub-journeys (separate forms) | -| Total rules > 150 | Split journey or aggressively extract custom functions | - -> **Gate:** Do NOT proceed to the build phase if any screen-level metric is 🔴. Journey-level 🔴 flags should be escalated to the user for a split/keep decision. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/SKILL.md deleted file mode 100644 index bef78c6b..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/SKILL.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -name: build -description: Domain router for form structure & component skills -type: domain -triggers: - - create form - - add field - - add panel - - scaffold - - fragment - - layout - - custom component - - viewType -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Build — Domain Router - -| | | -|---|---| -| **ID** | `build` | -| **Version** | 0.1 | -| **Description** | Routes form-building intents to the correct skill — scaffolding, form creation/modification, and custom component development. | - -## Routing Table - -> **First match wins.** - -| Intent Pattern | Skill | -|---|---| -| Scaffold new empty form, bootstrap form template | `scaffold-form` | -| Create / modify form JSON, add field, add panel, add fragment, layout | `create-form` | -| Custom component, extend OOTB field type, custom viewType | `create-component` | - -## Skills - -| # | Skill | Purpose | Triggers | -|---|---|---|---| -| 1 | `scaffold-form` | Bootstrap a new empty form template | scaffold, bootstrap form, new form template | -| 2 | `create-form` | Create / modify form JSON — fields, panels, fragments | create form, add field, add panel, fragment, layout | -| 3 | `create-component` | Build custom components / extend OOTB field types | custom component, viewType, extend field type | - -### Skill Locations - -| Skill | Path | -|---|---| -| `scaffold-form` | `skills/aem/forms/skills/references/domains/references/build/scaffold-form/` | -| `create-form` | `skills/aem/forms/skills/references/domains/references/build/create-form/` | -| `create-component` | `skills/aem/forms/skills/references/domains/references/build/create-component/` | - -## Guard Policies - -> Never hand-write `form.json` from scratch. -> -> Fields/panels → `create-form`. -> Empty forms → `scaffold-form`. -> Custom components → `create-component`. - -## File Locations - -| Asset | Canonical Path | -|---|---| -| Forms | `repo/content/forms/af/<team>/<path>/<name>.form.json` | -| Rule stores | `repo/content/forms/af/<team>/<path>/<name>.rule.json` | -| Custom components | `code/components/<view-type>/` | - -## Dependencies - -| Domain | Relationship | -|---|---| -| **analysis** | Consumes `Screen.md` artifacts as input for form creation | -| **logic** | Rules are applied to forms created by build skills | - -## Plan Integration - -How this domain participates in plan-driven execution. - -| Plan Type | Skill(s) Invoked | Role | -|-----------|-------------------|------| -| Structure plans | `scaffold-form`, `create-form` | Scaffolds new forms and generates/modifies form JSON from analyzed requirements | -| Workflow plans | `create-form`, `create-component` | Adds panels/fields for workflow screens and builds custom components for non-standard field types | - -## Extending This Domain - -1. **Create the skill folder** under this domain's directory with a `SKILL.md` and any supporting assets. -2. **Register the skill** by adding a row to the *Skills* table and the *Skill Locations* sub-table above. -3. **Add a routing entry** in the *Routing Table* — place it in priority order (first match wins). -4. **Update Guard Policies** if the new skill introduces constraints that other skills must respect. -5. **Update triggers** in the YAML front-matter so the domain router can match new intents. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/SKILL.md deleted file mode 100644 index f1a56c1d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/SKILL.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -name: create-component -description: > - Create custom form components for Edge Delivery by extending OOTB field types. - Use when out-of-the-box fields don't satisfy requirements, or when you need to - extend existing field functionality with a custom widget. Handles scaffolding, - mapping registration, and decorate function setup. - Triggers: custom component, extend field, custom widget, fd:viewType, custom view type. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Custom Component Creator - -You create custom form components by extending out-of-the-box (OOTB) field types in Edge Delivery forms. - -## When to Use - -- OOTB form fields don't satisfy the use case -- You need to extend an existing field with additional functionality or custom UI - -## Critical Rules - -1. **Always use `cct create`** to scaffold — never manually create component files -2. **Always register in `mappings.js`** — add the `fd:viewType` to the `customComponents` array in `code/blocks/form/mappings.js` -3. **Always add `fd:viewType`** to the field in `form.json` — this links the field to its custom component -4. **`decorate()` extends, not replaces** — `fieldDiv` already contains the base field's HTML; modify it, don't rebuild from scratch -5. **Refer to HTML structures** — use [references/field-html-structure.md](references/field-html-structure.md) to understand the DOM you receive in `decorate()` - -## Workflow - -### 1. Identify base type and view type - -- **`base_type`**: the OOTB field to extend (see Base Types table below) -- **`fd:viewType`**: custom identifier — lowercase, hyphen-separated (e.g., `countdown-timer`) - -### 2. Add field to form.json - -Add a field using the `base_type`'s `fieldType` and `sling:resourceType`, then add `fd:viewType`: - -```json -"my_field": { - "fieldType": "<base_type>", - "sling:resourceType": "<base sling:resourceType>", - "fd:viewType": "<your-view-type>", - "name": "my_field", - "jcr:title": "My Custom Field" -} -``` - -### 3. Scaffold the component - -```bash -cct create <base_type> <fd:viewType> -``` - -This creates three files in `components/<fd:viewType>/`: - -| File | Purpose | -|------|---------| -| `<fd:viewType>.js` | Component logic — exports `decorate()` | -| `<fd:viewType>.css` | Component styling | -| `_<fd:viewType>.json` | Custom authoring properties | - -### 4. Register in mappings.js - -Add your `fd:viewType` to the `customComponents` array in `code/blocks/form/mappings.js`: - -```js -let customComponents = ['range', 'employer-search', '<fd:viewType>']; -``` - -### 5. Implement `decorate()` - -Edit `<fd:viewType>.js` — see decorate() Pattern below. - -### 6. Define custom authoring properties - -Edit `_<fd:viewType>.json` to add any additional properties in the `models` section. - -### 7. Style the component - -Edit `<fd:viewType>.css` with the required styles. - -## Tool Commands - -| Action | Command | -|--------|---------| -| Scaffold component | `cct create <base_type> <fd:viewType>` | - -The `cct` tool is available as a CLI. Run from the project root. - -## Base Types - -| base_type | Use For | -|-----------|---------| -| `text-input` | Single-line text entry | -| `number-input` | Numeric values | -| `email` | Email addresses | -| `telephone-input` | Phone numbers | -| `date-input` | Date values | -| `text` | Display-only text | -| `drop-down` | Select from options | -| `checkbox` | Single boolean toggle | -| `checkbox-group` | Multiple selections | -| `radio-group` | Single selection from options | -| `file-input` | File uploads | -| `button` | Clickable actions | -| `panel` | Container / grouping | -| `image` | Image display | - -## File Structure (after scaffolding) - -``` -components/ -└── <fd:viewType>/ - ├── <fd:viewType>.js # decorate() function - ├── <fd:viewType>.css # Styles - └── _<fd:viewType>.json # Authoring properties -``` - -## decorate() Pattern - -```js -export default async function decorate(fieldDiv, fieldJson) { - // fieldDiv → the base component's HTML (already rendered) - // fieldJson → field properties (enabled, visible, placeholder, etc.) - // fieldJson.properties → any custom authoring properties from _<viewType>.json - - // Example: add a custom wrapper - const wrapper = document.createElement('div'); - wrapper.classList.add('my-custom-wrapper'); - fieldDiv.append(wrapper); -} -``` - -**Key points:** -- `fieldDiv` is the already-rendered HTML of the base field type — extend it, don't replace it -- `fieldJson.properties` contains custom authoring properties defined in `_<fd:viewType>.json` -- Refer to [references/field-html-structure.md](references/field-html-structure.md) for the exact HTML structure of each base type - -## Examples - -### Countdown Timer (extends `number-input`) - -- **base_type**: `number-input` — captures a numeric duration value -- **fd:viewType**: `countdown-timer` - -```bash -cct create number-input countdown-timer -``` - -Then register: add `'countdown-timer'` to `customComponents` in `mappings.js`. - -### Card Choice (extends `radio-group`) - -- **base_type**: `radio-group` — single selection from a set of options -- **fd:viewType**: `card-choice` - -```bash -cct create radio-group card-choice -``` - -Then register: add `'card-choice'` to `customComponents` in `mappings.js`. - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Component not rendering | Check that `fd:viewType` is added to `customComponents` in `mappings.js` | -| `decorate()` not called | Verify `fd:viewType` in `form.json` matches the component folder name exactly | -| Invalid base_type error | Use only valid base types from the table above | -| Styles not loading | Ensure CSS file name matches `<fd:viewType>.css` exactly | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/references/field-html-structure.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/references/field-html-structure.md deleted file mode 100644 index 8a5aca55..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/references/field-html-structure.md +++ /dev/null @@ -1,189 +0,0 @@ -# Field HTML Structure Reference - -The `decorate(fieldDiv, fieldJson)` function receives `fieldDiv` — the already-rendered HTML of the base field type. This reference documents the exact DOM structure for each base type so you know what elements to query and extend. - -## General Input Fields (text-input, number-input, email, telephone-input, date-input) - -All simple input types share the same structure, differing only in wrapper class and input type attribute. - -```html -<div class="{type}-wrapper field-{name} field-wrapper" data-required="{required}"> - <label for="{fieldId}" class="field-label">{Label Text}</label> - <input type="{type}" placeholder="{placeholder}" maxlength="{max}" - id="{fieldId}" name="{name}" - aria-describedby="{fieldId}-description"> - <div class="field-description" aria-live="polite" id="{fieldId}-description"> - {Description / hint text} - </div> -</div> -``` - -**Wrapper classes by type:** - -| base_type | Wrapper class | Input type attr | -|-----------|--------------|-----------------| -| text-input | text-wrapper | text | -| number-input | number-wrapper | number | -| email | email-wrapper | email | -| telephone-input | tel-wrapper | tel | -| date-input | date-wrapper | date | - -**Example (text-input):** - -```html -<div class="text-wrapper field-first-name field-wrapper" data-required="true"> - <label for="firstName" class="field-label">First Name</label> - <input type="text" placeholder="Enter your first name" maxlength="50" - id="firstName" name="firstName" - aria-describedby="firstName-description"> - <div class="field-description" aria-live="polite" id="firstName-description"> - Please enter your legal first name. - </div> -</div> -``` - -**Key selectors for decorate():** -- Label: `fieldDiv.querySelector('.field-label')` -- Input: `fieldDiv.querySelector('input')` -- Description: `fieldDiv.querySelector('.field-description')` - ---- - -## Dropdown (drop-down) - -```html -<div class="drop-down-wrapper field-{name} field-wrapper" data-required="{required}"> - <label for="{fieldId}" class="field-label">{Label Text}</label> - <select id="{fieldId}" name="{name}"> - <option value="">Select</option> - <option value="us">United States</option> - </select> - <div class="field-description" aria-live="polite" id="{fieldId}-description"> - {Description text} - </div> -</div> -``` - -**Key difference:** Uses `<select>` instead of `<input>`. - -**Key selectors:** -- Select element: `fieldDiv.querySelector('select')` -- Options: `fieldDiv.querySelectorAll('option')` - ---- - -## Radio Button Group (radio-group) - -```html -<fieldset class="radio-group-wrapper field-{name} field-wrapper" data-required="{required}"> - <legend class="field-label">{Group Label}</legend> - <!-- repeated for each option --> - <div class="radio-wrapper field-{name}"> - <input type="radio" id="{fieldId}" name="{name}" value="{value}"> - <label for="{fieldId}" class="field-label">{Option Label}</label> - </div> - <!-- end repeat --> - <div class="field-description" aria-live="polite" id="{fieldId}-description"> - {Description text} - </div> -</fieldset> -``` - -**Key points:** -- Outer element is `<fieldset>`, not `<div>` -- Group label uses `<legend>`, not `<label>` -- Each option is in a `radio-wrapper` div - -**Key selectors:** -- All radio inputs: `fieldDiv.querySelectorAll('input[type="radio"]')` -- Each option wrapper: `fieldDiv.querySelectorAll('.radio-wrapper')` -- Group label: `fieldDiv.querySelector('legend')` - ---- - -## Checkbox Group (checkbox-group) - -```html -<fieldset class="checkbox-group-wrapper field-{name} field-wrapper" data-required="{required}"> - <legend class="field-label">{Group Label}</legend> - <!-- repeated for each option --> - <div class="checkbox-wrapper field-{name}"> - <input type="checkbox" id="{fieldId}" name="{name}" value="{value}"> - <label for="{fieldId}" class="field-label">{Option Label}</label> - </div> - <!-- end repeat --> - <div class="field-description" aria-live="polite" id="{fieldId}-description"> - {Description text} - </div> -</fieldset> -``` - -**Key points:** -- Identical structure to radio-group, but with `type="checkbox"` -- Uses `checkbox-group-wrapper` and `checkbox-wrapper` classes - -**Key selectors:** -- All checkboxes: `fieldDiv.querySelectorAll('input[type="checkbox"]')` -- Each option wrapper: `fieldDiv.querySelectorAll('.checkbox-wrapper')` - ---- - -## Single Checkbox (checkbox) - -```html -<div class="checkbox-wrapper field-{name} field-wrapper" data-required="{required}"> - <input type="checkbox" id="{fieldId}" name="{name}" value="{value}"> - <label for="{fieldId}" class="field-label">{Label Text}</label> - <div class="field-description" aria-live="polite" id="{fieldId}-description"> - {Description text} - </div> -</div> -``` - ---- - -## File Upload (file-input) - -```html -<div id="{fieldId}" name="{name}" class="file-wrapper field-{name} field-wrapper" - data-required="{required}" data-max-file-size="2MB"> - <legend for="{fieldId}" class="field-label">{Label Text}</legend> - <div class="file-drag-area"> - <div class="file-dragIcon"></div> - <div class="file-dragText">Drag and Drop To Upload</div> - <button class="file-attachButton" type="button">Attach</button> - <input type="file" multiple="" - accept="audio/*, video/*, image/*, text/*, application/pdf" - id="{fieldId}" name="{name}" - aria-describedby="{fieldId}-description"> - </div> - <div class="field-description" aria-live="polite" id="{fieldId}-description"> - {Description text} - </div> - <div class="files-list"></div> -</div> -``` - -**Key points:** -- Has a drag-and-drop area with `file-drag-area` class -- `files-list` is populated dynamically via JavaScript -- Supports `data-max-file-size` attribute - -**Key selectors:** -- File input: `fieldDiv.querySelector('input[type="file"]')` -- Drag area: `fieldDiv.querySelector('.file-drag-area')` -- File list: `fieldDiv.querySelector('.files-list')` - ---- - -## Common Class Patterns - -| Class | Purpose | -|-------|---------| -| `{type}-wrapper` | Identifies field by type (e.g., `text-wrapper`, `number-wrapper`) | -| `field-{name}` | Identifies field by name (alphanumeric, dashes normalized) | -| `field-wrapper` | Generic class on all field wrappers | -| `field-label` | Label element class | -| `field-description` | Description / hint text class | - -All `{fieldId}` values are auto-generated unique identifiers. diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct-create b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct-create deleted file mode 100755 index a0c10ed9..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct-create +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m cct.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/__init__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/__init__.py deleted file mode 100644 index cd782255..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Custom Component Tool (CCT) - CLI tool for managing form custom components.""" - -__version__ = "0.1.0" - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/cli.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/cli.py deleted file mode 100644 index 151bd541..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/cli.py +++ /dev/null @@ -1,116 +0,0 @@ -"""CLI entry point for Custom Component Tool (CCT).""" - -import sys -from pathlib import Path -import click -from . import __version__ -from .exceptions import CCTError -from .create import create_component - - -@click.group() -@click.version_option(version=__version__, prog_name="cct") -def cli(): - """Custom Component Tool (CCT) - Manage form custom components. - - \b - This tool helps you create and manage custom form components for Edge Delivery. - It ensures proper file structure and authoring configuration. - - \b - Examples: - cct create text-input countdown-timer - """ - pass - - -@cli.command() -@click.argument('base_type') -@click.argument('view_type') -@click.option('--verbose', '-v', is_flag=True, help='Enable verbose output') -def create(base_type: str, view_type: str, verbose: bool): - """Create a new custom component. - - \b - Arguments: - BASE_TYPE: OOTB form field type to extend (e.g., text-input, radio-group) - VIEW_TYPE: Custom view type identifier (e.g., countdown-timer, card-choice) - - \b - Valid base types: - button, checkbox, checkbox-group, date-input, drop-down, email, - file-input, image, number-input, panel, radio-group, telephone-input, - text, text-input - - \b - This command will: - • Create component directory: components/<view_type>/ - • Generate <view_type>.js with default implementation - • Generate <view_type>.css with basic styles - • Generate _<view_type>.json with authoring properties - - \b - Examples: - # Create a countdown timer extending number-input - cct create number-input countdown-timer - - # Create a card choice extending radio-group - cct create radio-group card-choice - - # Create a password field extending text-input - cct create text-input password - """ - try: - # Create progress callback - def on_progress(message: str) -> None: - if verbose: - click.echo(f" {message}") - - click.echo(f"Creating custom component: {view_type}") - click.echo(f" Base type: {base_type}") - - # Create the component - component_dir = create_component( - base_type=base_type, - view_type=view_type, - base_path=Path.cwd(), - on_progress=on_progress if verbose else None, - ) - - # Success output - click.echo(f"\n✓ Component created at: {component_dir}") - click.echo(f"✓ Files generated:") - click.echo(f" - {view_type}.js") - click.echo(f" - {view_type}.css") - click.echo(f" - _{view_type}.json") - - click.echo(f"\n✓ Configuration files updated:") - click.echo(f" - authoring/_form.json") - click.echo(f" - authoring/_component-definition.json") - - click.echo("\nNext steps:") - click.echo(f" 1. Edit {view_type}.js to add your custom logic") - click.echo(f" 2. Edit {view_type}.css to add custom styles") - click.echo(f" 3. Update _{view_type}.json to add authoring properties") - - click.secho("\nSUCCESS: Component created and registered", fg="green") - - except CCTError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", - fg="red", - err=True, - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -if __name__ == "__main__": - cli() - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/create.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/create.py deleted file mode 100644 index 515db6c7..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/create.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Create command implementation.""" - -from pathlib import Path -from typing import Optional, Callable -from .exceptions import ComponentError -from .validator import ( - validate_base_type, - validate_view_type, - validate_directories, - validate_authoring_files, - get_component_files, -) -from .templates import ( - get_component_js_template, - get_component_css_template, - get_component_authoring_json, - format_json, -) -from .json_updater import ( - update_form_json, - update_component_definition_json, -) - - -def create_component( - base_type: str, - view_type: str, - base_path: Optional[Path] = None, - on_progress: Optional[Callable[[str], None]] = None, -) -> Path: - """Create a new custom component. - - Args: - base_type: The base component type to extend - view_type: The custom view type (fd:viewType) - base_path: Base directory (defaults to current working directory) - on_progress: Optional callback for progress messages - - Returns: - Path to the created component directory - - Raises: - ValidationError: If input is invalid - DirectoryError: If required directories don't exist - ComponentError: If component creation fails - """ - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Validate inputs - log("Validating inputs...") - validate_base_type(base_type) - validate_view_type(view_type) - - # Use current directory if no base_path provided - if base_path is None: - base_path = Path.cwd() - - # Validate directories exist - log("Checking directories...") - components_dir, authoring_dir = validate_directories(base_path) - log(f"✓ Components directory: {components_dir}") - log(f"✓ Authoring directory: {authoring_dir}") - - # Validate required authoring files exist - log("Checking required authoring files...") - validate_authoring_files(authoring_dir) - log("✓ Required authoring files found") - - # Get component file paths - component_dir, js_file, css_file, json_file = get_component_files( - components_dir, view_type - ) - - # Check if component already exists - if component_dir.exists(): - raise ComponentError( - f"Component '{view_type}' already exists at: {component_dir}\n" - f"Please choose a different name or remove the existing component." - ) - - # Create component directory - log(f"Creating component directory: {component_dir}") - try: - component_dir.mkdir(parents=True, exist_ok=False) - except Exception as e: - raise ComponentError(f"Failed to create component directory: {e}") - - # Create JS file - log(f"Creating {js_file.name}...") - try: - js_content = get_component_js_template(view_type, base_type) - js_file.write_text(js_content, encoding='utf-8') - except Exception as e: - raise ComponentError(f"Failed to create JS file: {e}") - - # Create CSS file - log(f"Creating {css_file.name}...") - try: - css_content = get_component_css_template(view_type) - css_file.write_text(css_content, encoding='utf-8') - except Exception as e: - raise ComponentError(f"Failed to create CSS file: {e}") - - # Create authoring JSON file - log(f"Creating {json_file.name}...") - try: - json_data = get_component_authoring_json(view_type, base_type, base_path) - json_content = format_json(json_data) - json_file.write_text(json_content, encoding='utf-8') - except FileNotFoundError as e: - raise ComponentError(f"Base type JSON file not found: {e}") - except Exception as e: - raise ComponentError(f"Failed to create authoring JSON file: {e}") - - log("Component files created successfully!") - - # Update authoring configuration files - log("Updating authoring configuration files...") - - # Update _form.json - try: - update_form_json(authoring_dir, view_type, on_progress) - except Exception as e: - # Clean up created component directory on failure - import shutil - shutil.rmtree(component_dir, ignore_errors=True) - raise ComponentError(f"Failed to update _form.json: {e}") - - # Update _component-definition.json - try: - update_component_definition_json(authoring_dir, view_type, on_progress) - except Exception as e: - # Clean up created component directory on failure - import shutil - shutil.rmtree(component_dir, ignore_errors=True) - raise ComponentError(f"Failed to update _component-definition.json: {e}") - - log("All configuration files updated successfully!") - - return component_dir - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/exceptions.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/exceptions.py deleted file mode 100644 index 8e43996e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/exceptions.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Custom exceptions for CCT.""" - - -class CCTError(Exception): - """Base exception for all CCT errors.""" - pass - - -class ConfigurationError(CCTError): - """Raised when configuration is invalid or missing.""" - pass - - -class DirectoryError(CCTError): - """Raised when required directories are missing or invalid.""" - pass - - -class ComponentError(CCTError): - """Raised when component operations fail.""" - pass - - -class ValidationError(CCTError): - """Raised when validation fails.""" - pass - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/json_updater.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/json_updater.py deleted file mode 100644 index 74cf25c1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/json_updater.py +++ /dev/null @@ -1,178 +0,0 @@ -"""JSON file updater for authoring configuration files.""" - -import json -from pathlib import Path -from typing import Optional, Callable -from .exceptions import ComponentError - - -def update_form_json( - authoring_dir: Path, - view_type: str, - on_progress: Optional[Callable[[str], None]] = None, -) -> None: - """Update _form.json to include the new component. - - Adds the component to the filters section. - - Args: - authoring_dir: Path to authoring directory - view_type: The custom view type - on_progress: Optional callback for progress messages - - Raises: - ComponentError: If file doesn't exist or update fails - """ - def log(message: str) -> None: - if on_progress: - on_progress(message) - - form_json_path = authoring_dir / "_form.json" - - if not form_json_path.exists(): - raise ComponentError( - f"_form.json not found at: {form_json_path}\n" - f"This file is required for component registration." - ) - - log(f"Updating {form_json_path.name}...") - - try: - # Read current _form.json - with open(form_json_path, 'r', encoding='utf-8') as f: - form_data = json.load(f) - - # Add to filters section - if 'filters' not in form_data: - form_data['filters'] = [] - - # Find the form filter - form_filter = None - for filter_item in form_data['filters']: - if filter_item.get('id') == 'form': - form_filter = filter_item - break - - if form_filter is None: - # Create form filter if it doesn't exist - form_filter = { - "id": "form", - "components": [] - } - form_data['filters'].append(form_filter) - - # Add component to filter if not present - if 'components' not in form_filter: - form_filter['components'] = [] - - if view_type not in form_filter['components']: - # Insert in alphabetical order - form_filter['components'].append(view_type) - form_filter['components'].sort() - log(f" Added {view_type} to filters") - else: - log(f" {view_type} already in filters") - - # Write back to file - with open(form_json_path, 'w', encoding='utf-8') as f: - json.dump(form_data, f, indent=2, ensure_ascii=False) - f.write('\n') # Add trailing newline - - log(" ✓ _form.json updated") - - except json.JSONDecodeError as e: - raise ComponentError(f"Invalid JSON in _form.json: {e}") - except Exception as e: - raise ComponentError(f"Failed to update _form.json: {e}") - - -def update_component_definition_json( - authoring_dir: Path, - view_type: str, - on_progress: Optional[Callable[[str], None]] = None, -) -> None: - """Update _component-definition.json to include the new component. - - Adds the component to the custom-components group. - - Args: - authoring_dir: Path to authoring directory - view_type: The custom view type - on_progress: Optional callback for progress messages - - Raises: - ComponentError: If file doesn't exist or update fails - """ - def log(message: str) -> None: - if on_progress: - on_progress(message) - - comp_def_path = authoring_dir / "_component-definition.json" - - if not comp_def_path.exists(): - raise ComponentError( - f"_component-definition.json not found at: {comp_def_path}\n" - f"This file is required for component registration." - ) - - log(f"Updating {comp_def_path.name}...") - - try: - # Read current _component-definition.json - with open(comp_def_path, 'r', encoding='utf-8') as f: - comp_def_data = json.load(f) - - # Find the custom-components group - if 'groups' not in comp_def_data: - comp_def_data['groups'] = [] - - custom_group = None - for group in comp_def_data['groups']: - if group.get('id') == 'custom-components': - custom_group = group - break - - # Create custom-components group if it doesn't exist - if custom_group is None: - custom_group = { - "title": "Custom Form Components", - "id": "custom-components", - "components": [] - } - comp_def_data['groups'].append(custom_group) - log(" Created custom-components group") - - # Ensure components array exists - if 'components' not in custom_group: - custom_group['components'] = [] - - # Create the component reference - component_ref = { - "...": f"../blocks/form/components/{view_type}/_{view_type}.json#/definitions" - } - - # Check if it already exists - component_exists = any( - isinstance(item, dict) and - item.get("...") == component_ref["..."] - for item in custom_group['components'] - ) - - if not component_exists: - custom_group['components'].append(component_ref) - log(f" Added {view_type} to custom-components") - else: - log(f" {view_type} already in custom-components") - - # Write back to file - with open(comp_def_path, 'w', encoding='utf-8') as f: - json.dump(comp_def_data, f, indent=2, ensure_ascii=False) - f.write('\n') # Add trailing newline - - log(" ✓ _component-definition.json updated") - - except json.JSONDecodeError as e: - raise ComponentError(f"Invalid JSON in _component-definition.json: {e}") - except Exception as e: - raise ComponentError(f"Failed to update _component-definition.json: {e}") - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/templates.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/templates.py deleted file mode 100644 index c6540d78..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/templates.py +++ /dev/null @@ -1,235 +0,0 @@ -"""Template generators for component files.""" - -import json -from pathlib import Path -from typing import Dict, Any - - -def get_component_js_template(view_type: str, base_type: str) -> str: - """Generate JavaScript template for custom component. - - Args: - view_type: The custom view type - base_type: The base component type - - Returns: - JavaScript code as string - """ - return f"""/** - * Custom component: {view_type} - * Base type: {base_type} - */ - -export default async function decorate(fieldDiv, fieldJson) {{ - // fieldDiv: HTML of the base component ({base_type}) - // fieldJson: Field properties (enabled, visible, placeholder, etc.) - - // Add your custom logic here to extend the {base_type} component - console.log('Decorating {view_type}', fieldJson); - - // Example: Add a custom class - fieldDiv.classList.add('{view_type}'); - - // Example: Access field properties - // const placeholder = fieldJson.placeholder; - // const label = fieldJson.label; - - // Your customization logic goes here... -}} -""" - - -def get_component_css_template(view_type: str) -> str: - """Generate CSS template for custom component. - - Args: - view_type: The custom view type - - Returns: - CSS code as string - """ - return f"""/* Custom component styles: {view_type} */ -""" - - -def transform_paths(obj: Any) -> Any: - """Transform JSON reference paths from base type location to component location. - - Transforms paths like: - "../form-common/_basic-input-fields.json#/fields" - to: - "../../models/form-common/_basic-input-fields.json#/fields" - - Args: - obj: Any JSON-serializable object (dict, list, str, etc.) - - Returns: - Transformed object with updated paths - """ - if isinstance(obj, dict): - result = {} - for key, value in obj.items(): - # Check if this is a JSON reference key ("...") - if key == "..." and isinstance(value, str): - # Transform the path - if value.startswith("../form-common/"): - # Replace ../form-common/ with ../../models/form-common/ - result[key] = value.replace("../form-common/", "../../models/form-common/") - else: - result[key] = value - else: - # Recursively transform nested objects - result[key] = transform_paths(value) - return result - elif isinstance(obj, list): - # Recursively transform list items - return [transform_paths(item) for item in obj] - else: - # Return primitive values as-is - return obj - - -def get_base_json_path(base_type: str, base_path: Path) -> Path: - """Get the path to the base type JSON file. - - Args: - base_type: The base component type - base_path: Base directory (current working directory or sandbox root) - - Returns: - Path to the base type JSON file - """ - # Check if we're in a sandbox directory with code/ subdirectory - code_dir = base_path / "code" - if code_dir.exists() and code_dir.is_dir(): - # We're in sandbox root, use code/ as base - actual_base = code_dir - else: - # We're in code/ directory or other location - actual_base = base_path - - # Construct path to base type JSON - base_json_path = actual_base / "authoring" / "models" / "form-components" / f"_{base_type}.json" - - return base_json_path - - -def load_base_json(base_type: str, base_path: Path) -> Dict[str, Any]: - """Load the base type JSON file. - - Args: - base_type: The base component type - base_path: Base directory (current working directory or sandbox root) - - Returns: - Dictionary containing the base JSON data - - Raises: - FileNotFoundError: If the base type JSON file doesn't exist - json.JSONDecodeError: If the JSON file is invalid - """ - base_json_path = get_base_json_path(base_type, base_path) - - if not base_json_path.exists(): - raise FileNotFoundError( - f"Base type JSON not found: {base_json_path}\n" - f"Expected location: authoring/models/form-components/_{base_type}.json" - ) - - with open(base_json_path, 'r', encoding='utf-8') as f: - return json.load(f) - - -def format_component_name(component_name: str) -> str: - """Format component name from kebab-case to Title Case. - - Args: - component_name: Component name in kebab-case (e.g., "countdown-timer") - - Returns: - Formatted title (e.g., "Countdown Timer") - """ - # Capitalize first character and replace hyphens with spaces - return component_name[0].upper() + component_name[1:].replace('-', ' ') - - -def get_component_authoring_json(view_type: str, base_type: str, base_path: Path) -> Dict[str, Any]: - """Generate authoring JSON configuration for custom component. - - This function loads the base type JSON and transforms it for the custom component: - 1. Loads the base JSON from authoring/models/form-components/_<base_type>.json - 2. Updates the title, id, and fd:viewType with the custom component name - 3. Transforms JSON reference paths from base location to component location - - Args: - view_type: The custom view type (component name) - base_type: The base component type - base_path: Base directory (current working directory or sandbox root) - - Returns: - Dictionary representing the authoring JSON - - Raises: - FileNotFoundError: If the base type JSON file doesn't exist - json.JSONDecodeError: If the JSON file is invalid - """ - # Load the base JSON - base_json = load_base_json(base_type, base_path) - - # Format the component name for display - formatted_title = format_component_name(view_type) - - # Transform definitions - custom_definitions = [] - for definition in base_json.get("definitions", []): - custom_def = { - **definition, - "title": formatted_title, - "id": view_type, - } - - # Update plugins.xwalk.page.template with custom values - if "plugins" in definition: - custom_def["plugins"] = { - **definition["plugins"], - "xwalk": { - **definition["plugins"].get("xwalk", {}), - "page": { - **definition["plugins"].get("xwalk", {}).get("page", {}), - "template": { - **definition["plugins"].get("xwalk", {}).get("page", {}).get("template", {}), - "jcr:title": formatted_title, - "fd:viewType": view_type, - } - } - } - } - - custom_definitions.append(custom_def) - - # Transform models with path updates - custom_models = [] - for model in base_json.get("models", []): - custom_model = transform_paths({ - **model, - "id": view_type, - }) - custom_models.append(custom_model) - - return { - **base_json, - "definitions": custom_definitions, - "models": custom_models, - } - - -def format_json(data: Dict[str, Any]) -> str: - """Format dictionary as pretty JSON string. - - Args: - data: Dictionary to format - - Returns: - Pretty-printed JSON string - """ - return json.dumps(data, indent=2) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/validator.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/validator.py deleted file mode 100644 index c9bd1d18..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts/cct/validator.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Validation utilities for CCT.""" - -from pathlib import Path -from typing import List, Tuple -from .exceptions import DirectoryError, ValidationError - - -# List of valid base types -VALID_BASE_TYPES = [ - 'button', - 'checkbox', - 'checkbox-group', - 'date-input', - 'drop-down', - 'email', - 'file-input', - 'image', - 'number-input', - 'panel', - 'radio-group', - 'telephone-input', - 'text', - 'text-input', -] - - -def validate_base_type(base_type: str) -> None: - """Validate that the base_type is valid. - - Args: - base_type: The base component type - - Raises: - ValidationError: If base_type is invalid - """ - if base_type not in VALID_BASE_TYPES: - raise ValidationError( - f"Invalid base_type '{base_type}'. Must be one of: {', '.join(VALID_BASE_TYPES)}" - ) - - -def validate_view_type(view_type: str) -> None: - """Validate that the view_type follows naming conventions. - - Args: - view_type: The custom view type (fd:viewType) - - Raises: - ValidationError: If view_type is invalid - """ - if not view_type: - raise ValidationError("view_type cannot be empty") - - # Check for lowercase and hyphens - if not all(c.islower() or c == '-' for c in view_type): - raise ValidationError( - f"view_type '{view_type}' must be lowercase with hyphens as separators" - ) - - # Check it doesn't start or end with hyphen - if view_type.startswith('-') or view_type.endswith('-'): - raise ValidationError( - f"view_type '{view_type}' cannot start or end with a hyphen" - ) - - -def validate_directories(base_path: Path) -> Tuple[Path, Path]: - """Validate that required directories exist and are not empty. - - Args: - base_path: Base directory to check (usually current working directory) - - Returns: - Tuple of (components_dir, authoring_dir) - - Raises: - DirectoryError: If directories don't exist or are empty - """ - # Check if we're in a sandbox directory with code/ subdirectory - code_dir = base_path / "code" - if code_dir.exists() and code_dir.is_dir(): - # We're in sandbox root, use code/ as base - actual_base = code_dir - else: - # We're in code/ directory or other location - actual_base = base_path - - # Check for components directory - components_dir = actual_base / "components" - if not components_dir.exists(): - raise DirectoryError( - f"Components directory not found: {components_dir}\n" - f"Please ensure you're running this command from a sandbox directory." - ) - - if not components_dir.is_dir(): - raise DirectoryError( - f"'components' exists but is not a directory: {components_dir}" - ) - - # Check if components directory is empty - if not any(components_dir.iterdir()): - raise DirectoryError( - f"Components directory is empty: {components_dir}\n" - f"Please add at least one component before running this command." - ) - - # Check for authoring directory - authoring_dir = actual_base / "authoring" - if not authoring_dir.exists(): - raise DirectoryError( - f"Authoring directory not found: {authoring_dir}\n" - f"Please ensure you're running this command from a sandbox directory." - ) - - if not authoring_dir.is_dir(): - raise DirectoryError( - f"'authoring' exists but is not a directory: {authoring_dir}" - ) - - # Check if authoring directory is empty - if not any(authoring_dir.iterdir()): - raise DirectoryError( - f"Authoring directory is empty: {authoring_dir}\n" - f"Please add authoring configuration files before running this command." - ) - - return components_dir, authoring_dir - - -def validate_authoring_files(authoring_dir: Path) -> None: - """Validate that required authoring JSON files exist. - - Args: - authoring_dir: Path to authoring directory - - Raises: - DirectoryError: If required files are missing - """ - required_files = [ - "_form.json", - "_component-definition.json", - ] - - missing_files = [] - for filename in required_files: - file_path = authoring_dir / filename - if not file_path.exists(): - missing_files.append(filename) - - if missing_files: - files_list = "\n - ".join(missing_files) - raise DirectoryError( - f"Required authoring files not found in {authoring_dir}:\n" - f" - {files_list}\n\n" - f"These files are required for component registration." - ) - - -def get_component_files(components_dir: Path, view_type: str) -> Tuple[Path, Path, Path, Path]: - """Get component file paths for a given view_type. - - Args: - components_dir: Path to components directory - view_type: The custom view type - - Returns: - Tuple of (component_dir, js_file, css_file, json_file) - """ - component_dir = components_dir / view_type - js_file = component_dir / f"{view_type}.js" - css_file = component_dir / f"{view_type}.css" - json_file = component_dir / f"_{view_type}.json" - - return component_dir, js_file, css_file, json_file - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/SKILL.md deleted file mode 100644 index 57904183..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/SKILL.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -name: create-form -description: > - Create and modify AEM Adaptive Form JSON files with proper field types, panel structure, - colspan layout, and fragment integration. Handles fragment-first workflow and custom field - creation. Use when building a new form, adding fields, modifying panels, or integrating - fragments. Triggers: create form, add field, add panel, add fragment, modify form, layout. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# Form Architect - -You design and modify `form.json` files to create well-structured AEM Adaptive Forms. - -## Critical Rules - -1. **Always check for fragments first** — before creating custom fields, check `refs/metadata.json` for existing fragments -2. **Act autonomously** — never ask "Should I add this?" or "Where should I place this?" — just do it -3. **Prefer fragments over custom fields** — if a fragment matches, use it instead of creating individual fields -4. **Report after, not before** — make changes first, then explain what you did -5. **Form location** — main form is always in `form/<form-name>.form.json` -6. **Variables belong in rules** — when variables need initializing, delegate to the **add-rules** skill. Do NOT create hidden fields for variables -7. **Always validate** — run the form validator after every edit - -## Project Structure - -``` -<workspace>/ -├── form/ -│ ├── <form-name>.form.json # Main form content -│ ├── <form-name>.rule.json # Business logic (add-rules skill) -│ └── metadata.json # Form sync metadata -├── refs/ -│ ├── metadata.json # Fragment registry -│ ├── <fragment>.form.json # Fragment content -│ └── <fragment>.rule.json # Fragment rules -└── code/ # Custom functions (create-function skill) -``` - -## Decision Tree - -``` -User requests fields - ↓ -Read refs/metadata.json - ↓ -┌─────────────────────────────────────┐ -│ Does a fragment match the request? │ -└─────────────────────────────────────┘ - ↓ ↓ - YES NO - ↓ ↓ - Fragment Workflow Custom Field Workflow -``` - -## Fragment Workflow - -**When:** A fragment in `refs/metadata.json` matches the user's request. - -### Step 1: Read fragment metadata - -```json -// refs/metadata.json -{ - "loginScreen": { - "folderPath": "/content/dam/formsanddocuments/.../fragments", - "originalPath": "/content/forms/af/.../fragments/loginScreen", - "localFile": "loginScreen.form.json", - "localRuleFile": "loginScreen.rule.json" - } -} -``` - -### Step 2: Verify fragment contents - -Read `refs/<localFile>` to confirm it has the needed fields. - -### Step 3: Add fragment to form.json - -```json -"<unique_name>": { - "sling:resourceType": "core/fd/components/form/fragment/v1/fragment", - "fieldType": "panel", - "aueComponentId": "form-fragment", - "name": "<unique_name>", - "jcr:title": "<Display Title>", - "fragmentPath": "<originalPath from metadata>", - "minOccur": 1 -} -``` - -### Step 4: Handle edge cases -- **Name conflict** → use alternative name (e.g., `home_address` if `address` exists) -- **Replacing existing fields** → remove old fields, place fragment in same position -- **Placement unclear** → add at end of form, before any submit button - -### Step 5: Validate -```bash -form-validate <path-to-form.json> -``` - -## Custom Field Workflow - -**When:** No fragment matches, or user explicitly wants custom fields. - -### Step 1: Read current form -Read `form/<form-name>.form.json`. - -### Step 2: Add/modify fields -Use valid field types from [references/field-types.md](references/field-types.md). - -### Step 3: Validate -```bash -form-validate <path-to-form.json> -``` - -The validator checks: -- Valid fieldTypes -- Required properties (name, fieldType) -- Property types (string, boolean, number, array) -- Enum values (colspan, orientation, etc.) -- Constraints (minLength <= maxLength, etc.) -- Name format (must start with letter, alphanumeric + underscore only) - -If validation fails, fix the reported errors before proceeding. - -### Step 4: Report changes - -## Form Structure - -``` -form -└── panelcontainer - └── main_form_panel ← fields go here -``` - -Minimal form.json root: -```json -{ - "jcr:primaryType": "nt:unstructured", - "fieldType": "form", - "sling:resourceType": "fd/franklin/components/form/v1/form", - "fd:version": "2.1" -} -``` - -## Layout: Colspan - -`colspan` controls field width (1–12 columns, **as string**). - -| colspan | Width | -|---------|-------| -| "12" | Full width | -| "6" | Half width | -| "4" | Third width | -| "3" | Quarter width | - -**Nesting:** colspan multiplies. A `"colspan": "6"` field inside a `"colspan": "6"` panel = 1/4 total width. - -## Constraints - -- Field names: **unique**, **snake_case** -- All fields must have `jcr:title` -- Radio/checkbox groups: **minimum 2 options** -- Pattern: valid JavaScript regex -- Min < max -- Dates: ISO 8601 format -- Dropdowns use `enum` (values) + `enumNames` (display labels) - -## Examples - -### Custom field — phone number: -```json -"phone_number": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/textinput/v1/textinput", - "fieldType": "text-input", - "name": "phone_number", - "jcr:title": "Phone Number", - "placeholder": "+1234567890", - "pattern": "^\\+?[1-9]\\d{1,14}$", - "required": false, - "colspan": "6" -} -``` - -### Dropdown with options: -```json -"country": { - "sling:resourceType": "core/fd/components/form/dropdown/v1/dropdown", - "fieldType": "drop-down", - "name": "country", - "jcr:title": "Country", - "required": true, - "enum": ["us", "uk", "ca"], - "enumNames": ["United States", "United Kingdom", "Canada"] -} -``` - -### Fragment reference: -```json -"otp_screen": { - "sling:resourceType": "core/fd/components/form/fragment/v1/fragment", - "fieldType": "panel", - "aueComponentId": "form-fragment", - "name": "otp_screen", - "jcr:title": "OTP Authentication", - "fragmentPath": "/content/forms/af/.../fragments/otpAuthenticationScreen", - "minOccur": 1 -} -``` - -## Tool Commands - -| Tool | Command | -|------|---------| -| Validate form | `form-validate <path-to-form.json>` | - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| No fragments available | `refs/metadata.json` empty or missing → create custom fields | -| Fragment name conflict | Use alternative unique name | -| Validator reports errors | Fix all errors before proceeding — see validator output | -| User wants custom, not fragment | Skip fragment check, create custom fields | -| Multiple fragments match | Pick the one with best field coverage | -| Can't find form file | Check `form/` folder for `<form-name>.form.json` | - -## Field Types Reference - -See [references/field-types.md](references/field-types.md) for the complete catalog of 14 valid field types with their `sling:resourceType`, `fieldType`, and key properties. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-form-validate.sh b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-form-validate.sh deleted file mode 100755 index 57d3cbf9..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-form-validate.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env bash -# Eval: Form Validator smoke test for create-form skill -# Verifies eds_form_validator can validate a sample form. -# -# Usage: bash skills/create-form/eval/eval-form-validate.sh - -set -euo pipefail - -EVAL_DIR="$(cd "$(dirname "$0")" && pwd)" -SKILL_DIR="$(cd "$EVAL_DIR/.." && pwd)" -FIXTURES="$EVAL_DIR/fixtures" -PASS=0; FAIL=0; TOTAL=0 - -pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo " ✅ $1"; } -fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo " ❌ $1: $2"; } -skip() { TOTAL=$((TOTAL + 1)); echo " ⏭️ $1 (skipped: $2)"; } - -TMPDIR_EVAL="$(mktemp -d)" -trap 'rm -rf "$TMPDIR_EVAL"' EXIT - -echo "Form Validator Eval" -echo "===================" - -# ── Prerequisites ── - -HAS_NODE=false -if command -v node &>/dev/null; then - pass "Node.js available ($(node --version))" - HAS_NODE=true -else - skip "Node.js" "node not found in PATH" -fi - -FIXTURE_FORM="$FIXTURES/sample-contact.form.json" -if [[ ! -f "$FIXTURE_FORM" ]]; then - echo "FATAL: Required fixture missing: $FIXTURE_FORM" - exit 1 -fi - -# ── Form Validator ── - -echo "" -echo "── Form Validator (validate.cjs) ──" - -if [[ "$HAS_NODE" == true ]]; then - STDOUT_FILE="$TMPDIR_EVAL/validate_stdout.txt" - STDERR_FILE="$TMPDIR_EVAL/validate_stderr.txt" - - EXIT_CODE=0 - node "$SKILL_DIR/scripts/eds_form_validator/validate.cjs" "$FIXTURE_FORM" --json \ - >"$STDOUT_FILE" 2>"$STDERR_FILE" || EXIT_CODE=$? - - if [[ "$EXIT_CODE" -eq 0 ]]; then - pass "validate.cjs exits with code 0" - else - fail "validate.cjs exit code $EXIT_CODE" "$(head -5 "$STDERR_FILE")" - fi - - if grep -q '"success"' "$STDOUT_FILE" 2>/dev/null || grep -q '"valid"' "$STDOUT_FILE" 2>/dev/null; then - pass "validate.cjs output contains result key" - else - fail "validate.cjs output missing result key" "$(head -3 "$STDOUT_FILE")" - fi -else - skip "validate.cjs" "Node.js not available" -fi - -# ── Summary ── - -echo "" -echo "════════════════════════════════" -echo " $PASS/$TOTAL passed, $FAIL failed" -echo "════════════════════════════════" -[[ "$FAIL" -gt 0 ]] && exit 1 || exit 0 diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-plan.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-plan.md deleted file mode 100644 index a59b81fc..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-plan.md +++ /dev/null @@ -1,35 +0,0 @@ -# create-form — Eval Plan - -## Automated - -Run the form validator smoke test: - -```bash -bash skills/create-form/eval/eval-form-validate.sh -``` - -## Manual (E2E) - -### Prompt -> Create the form JSON for a Contact Us form with these fields: -> - Full Name (required, 2-50 chars) -> - Email (required, valid email) -> - Phone (optional) -> - Inquiry Type (dropdown: General, Support, Sales) -> - Message (multiline, required when Inquiry Type is "Support") - -### Expected Behavior -- Creates `form/contact-us.form.json` -- Correct field types (text-input, email, telephone-input, drop-down) -- Proper validation constraints -- Runs `form-validate` after creation -- Validator reports no errors - -### Checklist -- [ ] form.json was created -- [ ] JSON is valid and parseable -- [ ] All 5 fields present with correct types -- [ ] Validator was run -- [ ] Validator reports success -- [ ] Drop-down has correct enum values -- [ ] No `fd:rules` in form.json (rules are separate) \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/fixtures/sample-contact.form.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/fixtures/sample-contact.form.json deleted file mode 100644 index 069ee2a1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/fixtures/sample-contact.form.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "fd/franklin/components/form/v1/form", - "fieldType": "form", - "fd:version": "2.1", - "title": "Contact Us", - "contactInfoPanel": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/panelcontainer/v1/panelcontainer", - "fieldType": "panel", - "name": "contactInfoPanel", - "jcr:title": "Contact Information", - "fullName": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/textinput/v1/textinput", - "fieldType": "text-input", - "name": "fullName", - "jcr:title": "Full Name", - "required": true, - "colspan": "6", - "minLength": 2, - "minLengthMessage": "Minimum 2 characters required", - "maxLength": 50, - "maxLengthMessage": "Maximum 50 characters allowed", - "mandatoryMessage": "Full Name is required" - }, - "email": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/emailinput/v1/emailinput", - "fieldType": "email", - "name": "email", - "jcr:title": "Email", - "required": true, - "colspan": "6", - "mandatoryMessage": "Email is required" - }, - "phone": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/telephoneinput/v1/telephoneinput", - "fieldType": "telephone-input", - "name": "phone", - "jcr:title": "Phone", - "required": false, - "colspan": "6" - } - }, - "inquiryPanel": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/panelcontainer/v1/panelcontainer", - "fieldType": "panel", - "name": "inquiryPanel", - "jcr:title": "Inquiry Details", - "inquiryType": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/dropdown/v1/dropdown", - "fieldType": "drop-down", - "name": "inquiryType", - "jcr:title": "Inquiry Type", - "required": true, - "enum": ["General", "Support", "Sales"], - "enumNames": ["General", "Support", "Sales"], - "mandatoryMessage": "Please select an inquiry type" - }, - "message": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/textinput/v1/textinput", - "fieldType": "text-input", - "name": "message", - "jcr:title": "Message", - "required": true, - "multiLine": true, - "minLength": 10, - "minLengthMessage": "Message must be at least 10 characters", - "mandatoryMessage": "Message is required" - } - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/references/field-types.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/references/field-types.md deleted file mode 100644 index 68ad71fe..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/references/field-types.md +++ /dev/null @@ -1,80 +0,0 @@ -# AEM Adaptive Forms — Field Types Reference - -Complete catalog of valid field types for form.json. - -## Field Type Catalog - -| Type | fieldType | sling:resourceType | Key Properties | -|------|-----------|-------------------|----------------| -| Text display | `plain-text` | `core/fd/components/form/text/v1/text` | name, label | -| Text input | `text-input` | `core/fd/components/form/textinput/v1/textinput` | name, label, required, pattern, placeholder | -| Number | `number-input` | `core/fd/components/form/numberinput/v1/numberinput` | name, label, min, max, step | -| Date | `date-input` | `core/fd/components/form/datepicker/v1/datepicker` | name, label, min, max | -| Email | `email` | `core/fd/components/form/emailinput/v1/emailinput` | name, label, required, pattern | -| File upload | `file-input` | `core/fd/components/form/fileinput/v2/fileinput` | name, label, accept, maxSize | -| Dropdown | `drop-down` | `core/fd/components/form/dropdown/v1/dropdown` | name, label, enum, enumNames | -| Radio group | `radio-group` | `core/fd/components/form/radiobutton/v1/radiobutton` | name, label, enum, enumNames | -| Checkbox group | `checkbox-group` | `core/fd/components/form/checkboxgroup/v1/checkboxgroup` | name, label, enum, enumNames | -| Single checkbox | `checkbox` | `core/fd/components/form/checkbox/v1/checkbox` | name, label | -| Panel/Section | `panel` | `core/fd/components/form/panelcontainer/v1/panelcontainer` | title, fields | -| Button | `button` | `core/fd/components/form/button/v1/button` | name, label, type | -| Fragment | `panel` | `core/fd/components/form/fragment/v1/fragment` | name, fragmentPath, minOccur | - -**Note:** Fragment and Panel share `fieldType: "panel"` — distinguished by `sling:resourceType`. - -## Common Properties - -| Property | Type | Description | -|----------|------|-------------| -| `name` | string | Unique field identifier (snake_case) | -| `jcr:title` | string | Display label | -| `jcr:primaryType` | string | Always `"nt:unstructured"` | -| `sling:resourceType` | string | Component type identifier | -| `fieldType` | string | Field type from catalog above | -| `required` | boolean | Whether field is mandatory | -| `colspan` | string | Layout width (1–12, as string) | -| `placeholder` | string | Placeholder text | -| `pattern` | string | Validation regex (JavaScript format) | -| `visible` | boolean | Initial visibility | -| `enabled` | boolean | Whether field is editable | -| `default` | varies | Default value | - -## Dropdown/Radio/Checkbox Options - -Options use parallel arrays: -```json -{ - "enum": ["value1", "value2", "value3"], - "enumNames": ["Display 1", "Display 2", "Display 3"] -} -``` - -- `enum` — machine-readable values -- `enumNames` — human-readable display labels -- Arrays must be same length -- Minimum 2 options for radio/checkbox groups - -## Number Field Properties - -| Property | Type | Description | -|----------|------|-------------| -| `minimum` | number | Minimum value | -| `maximum` | number | Maximum value | -| `step` | number | Step increment | -| `minimumMessage` | string | Error for below minimum | -| `maximumMessage` | string | Error for above maximum | - -## Text Field Properties - -| Property | Type | Description | -|----------|------|-------------| -| `minLength` | number | Minimum character count | -| `maxLength` | number | Maximum character count | -| `pattern` | string | Regex validation pattern | - -## File Input Properties - -| Property | Type | Description | -|----------|------|-------------| -| `accept` | string | Accepted MIME types (e.g., ".pdf,.jpg") | -| `maxFileSize` | string | Maximum file size | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/FormFieldValidator.cjs b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/FormFieldValidator.cjs deleted file mode 100644 index 11435a10..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/FormFieldValidator.cjs +++ /dev/null @@ -1,1081 +0,0 @@ -#!/usr/bin/env node -/** - * EDS Form Field Validator - * - * Self-contained validator for Adobe EDS form fields. - * Validates form.json against hardcoded field schemas. - * Generates LLM-friendly error messages for correction. - */ - -// ============================================================================ -// FIELD SCHEMAS - All field types from _form.json filters -// ============================================================================ - -/** - * Valid fieldTypes from _form.json filters - */ -const VALID_FIELD_TYPES = [ - 'form', - 'captcha', - 'checkbox', - 'checkbox-group', - 'date-input', - 'drop-down', - 'email', - 'file-input', - 'form-accordion', - 'form-button', - 'form-fragment', - 'form-image', - 'form-modal', - 'form-reset-button', - 'form-submit-button', - 'number-input', - 'panel', - 'password', - 'plain-text', - 'radio-group', - 'rating', - 'telephone-input', - 'text-input', - 'tnc', - 'wizard', - 'range', - 'multiline-input', - 'accordion', - 'modal', - 'button', // Alias for form-button -]; - -/** - * Property type definitions - */ -const PROPERTY_TYPES = { - name: 'string', - 'jcr:title': 'string', - fieldType: 'string', - hideTitle: 'boolean', - dataRef: 'string', - unboundFormElement: 'boolean', - visible: 'boolean', - enabled: 'boolean', - readOnly: 'boolean', - colspan: 'string', - placeholder: 'string', - default: 'any', - description: 'string', - tooltip: 'string', - required: 'boolean', - mandatoryMessage: 'string', - validateExpMessage: 'string', - minLength: 'number', - minLengthMessage: 'string', - maxLength: 'number', - maxLengthMessage: 'string', - pattern: 'string', - validatePictureClauseMessage: 'string', - validatePatternMessage: 'string', - multiLine: 'boolean', - minimum: 'number', - minimumMessage: 'string', - maximum: 'number', - maximumMessage: 'string', - stepValue: 'number', - minimumDate: 'string', - maximumDate: 'string', - enum: 'array', - enumNames: 'array', - type: 'string', - orientation: 'string', - variant: 'string', - multiSelect: 'boolean', - checkedValue: 'string', - enableUncheckedValue: 'boolean', - uncheckedValue: 'string', - buttonText: 'string', - dragDropText: 'string', - maxFileSize: 'number', - maxFileSizeMessage: 'string', - accept: 'array', - acceptMessage: 'string', - repeatable: 'boolean', - minOccur: 'number', - maxOccur: 'number', - repeatAddButtonLabel: 'string', - repeatDeleteButtonLabel: 'string', - fileReference: 'string', - altText: 'string', - fragmentPath: 'string', - editFragment: 'boolean', - showLink: 'boolean', - displayFormat: 'string', -}; - -/** - * Enum values for properties with restricted options - */ -const ENUM_VALUES = { - colspan: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], - orientation: ['horizontal', 'vertical'], - 'variant:checkbox-group': ['default', 'cards'], - 'variant:radio-group': ['default', 'cards'], - 'variant:panel': ['noButtons', 'addDeleteButtons'], - 'type:number-input': ['integer', 'number'], - 'type:drop-down': ['string', 'boolean', 'number', 'string[]', 'boolean[]', 'number[]'], - 'type:checkbox': ['string', 'boolean', 'number'], - 'type:checkbox-group': ['string[]', 'boolean[]', 'number[]'], - 'type:radio-group': ['string', 'boolean', 'number'], - 'displayFormat:date-input': ['', 'd MMMM, y', 'MMMM d, y', 'EEEE, d MMMM, y', 'EEEE, MMMM d, y', 'd/M/y'], - 'displayFormat:number-input': ['', '¤#,##0.00', '¤####0.00', '#,###,##0.000', '#,###,##0%'], -}; - -/** - * Field schemas - allowed properties for each fieldType - */ -const FIELD_SCHEMAS = { - 'form': { - properties: ['name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'journeyName', - 'customFunctionsPath', 'schemaType', 'track', 'action', 'dataUrl', - 'redirectUrl', 'thankYouMessage', 'submitType', 'prefillService'], - required: ['fieldType'], - }, - - 'text-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', 'multiLine', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'email': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'multiline-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', 'multiLine', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'telephone-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'number-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', 'type', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', - 'displayFormat', 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'date-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimumDate', 'minimumMessage', 'maximumDate', 'maximumMessage', - 'displayFormat', 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'drop-down': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'enum', 'enumNames', 'multiSelect', 'type', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'checkbox': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'default', - 'type', 'checkedValue', 'enableUncheckedValue', 'uncheckedValue', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'checkbox-group': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'default', - 'enum', 'enumNames', 'variant', 'type', 'orientation', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'radio-group': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'default', - 'enum', 'enumNames', 'variant', 'type', 'orientation', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'file-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'type', - 'buttonText', 'dragDropText', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'maxFileSize', 'maxFileSizeMessage', 'accept', 'acceptMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'panel': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'form-button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'form-submit-button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'form-reset-button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'plain-text': { - properties: ['name', 'fieldType', 'dataRef', 'visible', 'colspan'], - required: ['fieldType', 'name'], - }, - - 'form-image': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'fileReference', 'altText', - 'dataRef', 'visible', 'colspan' - ], - required: ['fieldType', 'name'], - }, - - 'form-fragment': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'fragmentPath', 'editFragment', - 'repeatable', 'minOccur', 'maxOccur', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'captcha': { - properties: ['name', 'fieldType'], - required: ['fieldType', 'name'], - }, - - 'form-accordion': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - isContainer: true, - }, - - 'accordion': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - isContainer: true, - }, - - 'form-modal': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - isContainer: true, - }, - - 'modal': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - isContainer: true, - }, - - 'wizard': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - isContainer: true, - }, - - 'password': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'rating': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'range': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', 'stepValue', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'tnc': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'showLink', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, -}; - -/** - * System properties allowed on all fields (AEM/JCR specific) - */ -const SYSTEM_PROPERTIES = [ - 'jcr:primaryType', - 'jcr:lastModified', - 'jcr:lastModifiedBy', - 'jcr:created', - 'jcr:createdBy', - 'sling:resourceType', - 'cq:responsive', - 'fd:rules', - 'fd:events', - 'fd:version', - 'fd:viewType', // Determines actual component type for custom components (wizard, accordion, modal) - 'id', - 'items', - 'layout', - 'wrapData', - 'textIsRich', - 'autocomplete', - 'tooltipVisible', - 'dorExclusion', - 'buttonType', - 'typeIndex', - 'aueComponentId', - 'title', - 'thankYouOption', - 'themeRef', - 'dorType', - 'label', -]; - -/** - * Valid fd:viewType values for custom components - * These override the fieldType for rendering purposes - * - * Format: viewType -> { baseFieldType, schema } - */ -const VIEW_TYPE_CONFIG = { - // Panel-based custom components - 'wizard': { baseFieldType: 'panel', schema: 'wizard' }, - 'accordion': { baseFieldType: 'panel', schema: 'accordion' }, - 'modal': { baseFieldType: 'panel', schema: 'modal' }, - 'tnc': { baseFieldType: 'panel', schema: 'tnc' }, - - // Text-input-based custom components - 'password': { baseFieldType: 'text-input', schema: 'password' }, - 'masked-card': { baseFieldType: 'text-input', schema: 'text-input' }, - - // Number-input-based custom components - 'rating': { baseFieldType: 'number-input', schema: 'rating' }, - 'range': { baseFieldType: 'number-input', schema: 'range' }, - - // Checkbox-group-based custom components - 'toggleable-link': { baseFieldType: 'checkbox-group', schema: 'checkbox-group' }, -}; - -const VALID_VIEW_TYPES = Object.keys(VIEW_TYPE_CONFIG); - -/** - * fieldTypes that require fd:viewType for proper rendering - * These should use their base fieldType with fd:viewType instead - * - * Format: incorrectFieldType -> { correctFieldType, viewType } - */ -const FIELD_TYPES_REQUIRING_VIEW_TYPE = { - 'wizard': { correctFieldType: 'panel', viewType: 'wizard' }, - 'accordion': { correctFieldType: 'panel', viewType: 'accordion' }, - 'modal': { correctFieldType: 'panel', viewType: 'modal' }, - 'form-accordion': { correctFieldType: 'panel', viewType: 'accordion' }, - 'form-modal': { correctFieldType: 'panel', viewType: 'modal' }, - 'password': { correctFieldType: 'text-input', viewType: 'password' }, - 'rating': { correctFieldType: 'number-input', viewType: 'rating' }, - 'range': { correctFieldType: 'number-input', viewType: 'range' }, - 'tnc': { correctFieldType: 'panel', viewType: 'tnc' }, -}; - -// ============================================================================ -// VALIDATION LOGIC -// ============================================================================ - -/** - * Name validation pattern: starts with letter, then letters/numbers/underscores - */ -const NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/; - -/** - * Calculate Levenshtein distance for fuzzy matching - */ -function levenshteinDistance(a, b) { - const matrix = Array(b.length + 1).fill(null).map(() => Array(a.length + 1).fill(0)); - for (let i = 0; i <= a.length; i++) matrix[0][i] = i; - for (let j = 0; j <= b.length; j++) matrix[j][0] = j; - for (let j = 1; j <= b.length; j++) { - for (let i = 1; i <= a.length; i++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - matrix[j][i] = Math.min( - matrix[j][i - 1] + 1, - matrix[j - 1][i] + 1, - matrix[j - 1][i - 1] + cost - ); - } - } - return matrix[b.length][a.length]; -} - -/** - * Find similar property names for suggestions - */ -function findSimilarProperties(propName, allowedProps) { - const matches = []; - const propLower = propName.toLowerCase(); - - for (const allowed of allowedProps) { - const allowedLower = allowed.toLowerCase(); - if (allowedLower.includes(propLower) || propLower.includes(allowedLower)) { - matches.push(allowed); - } else if (levenshteinDistance(propLower, allowedLower) <= 3) { - matches.push(allowed); - } - } - - return matches.slice(0, 3); -} - -/** - * Check if a key represents a child field (nested component) - */ -function isChildField(key, value) { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - return false; - } - if (value.fieldType) return true; - const systemObjects = ['cq:responsive', 'fd:rules', 'fd:events', 'default']; - if (systemObjects.includes(key)) return false; - return false; -} - -/** - * Validate a single field - * @param {object} field - The field to validate - * @param {string} fieldPath - The path to the field - * @param {Set<string>} customComponents - Set of custom component IDs from _form.json filters (optional) - */ -function validateField(field, fieldPath, customComponents = null) { - const errors = []; - - // 1. Check fieldType exists - if (!field.fieldType) { - errors.push({ - path: fieldPath, - field: fieldPath.split('.').pop(), - property: 'fieldType', - errorType: 'MISSING_REQUIRED', - message: `Missing required property 'fieldType'. Every form field must have a fieldType that specifies its component type.`, - suggestion: `Add 'fieldType' property with one of the valid values: ${VALID_FIELD_TYPES.slice(0, 10).join(', ')}...`, - validOptions: VALID_FIELD_TYPES, - }); - return errors; - } - - const fieldType = field.fieldType; - const viewType = field['fd:viewType']; - const fieldName = field.name || fieldPath.split('.').pop() || 'unknown'; - - // 2. Check fieldType is valid - let schema = FIELD_SCHEMAS[fieldType]; - if (!schema) { - const similar = findSimilarProperties(fieldType, VALID_FIELD_TYPES); - let suggestion = `Change fieldType to one of the valid types.`; - if (similar.length > 0) { - suggestion = `Did you mean '${similar[0]}'? Change fieldType to a valid value.`; - } - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fieldType', - errorType: 'INVALID_VALUE', - message: `Invalid fieldType '${fieldType}'. This is not a recognized form component type.`, - suggestion: suggestion, - validOptions: VALID_FIELD_TYPES, - }); - return errors; - } - - // 2b. Check if fieldType requires fd:viewType for proper rendering - const viewTypeRequirement = FIELD_TYPES_REQUIRING_VIEW_TYPE[fieldType]; - if (viewTypeRequirement && !viewType) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fieldType', - errorType: 'MISSING_VIEW_TYPE', - message: `fieldType '${fieldType}' will not render correctly. It requires fieldType: "${viewTypeRequirement.correctFieldType}" with fd:viewType: "${viewTypeRequirement.viewType}".`, - suggestion: `Change fieldType to "${viewTypeRequirement.correctFieldType}" and add "fd:viewType": "${viewTypeRequirement.viewType}" for proper rendering.`, - }); - } - - // 3. Check fd:viewType if present - this determines actual component type - let effectiveType = fieldType; - let skipFieldValidation = false; - if (viewType) { - const viewTypeConfig = VIEW_TYPE_CONFIG[viewType]; - if (!viewTypeConfig) { - // Unknown fd:viewType - check if it's a valid custom component from _form.json - if (customComponents && customComponents.has(viewType)) { - // It's a valid custom component, skip validation - return { - errors: [], - skipped: { - path: fieldPath, - field: fieldName, - fieldType: fieldType, - viewType: viewType, - reason: `fd:viewType '${viewType}' is a custom component. Skipping validation.`, - }, - }; - } else { - // Unknown viewType and not in custom components - throw error - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fd:viewType', - errorType: 'INVALID_VIEW_TYPE', - message: `Invalid fd:viewType '${viewType}'. This is not a recognized view type.`, - suggestion: customComponents - ? `Change fd:viewType to one of the valid values: ${VALID_VIEW_TYPES.join(', ')}, or add it to the _form.json filters.` - : `Change fd:viewType to one of the valid values: ${VALID_VIEW_TYPES.join(', ')}`, - validOptions: VALID_VIEW_TYPES, - }); - } - } else { - // Validate that fieldType matches expected base type for this viewType - if (fieldType !== viewTypeConfig.baseFieldType) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fieldType', - errorType: 'INVALID_FIELD_TYPE_FOR_VIEW_TYPE', - message: `fd:viewType '${viewType}' requires fieldType '${viewTypeConfig.baseFieldType}', but found '${fieldType}'.`, - suggestion: `Change fieldType to "${viewTypeConfig.baseFieldType}" when using fd:viewType: "${viewType}".`, - }); - } - // Use the viewType schema if available - if (viewTypeConfig.schema && FIELD_SCHEMAS[viewTypeConfig.schema]) { - schema = FIELD_SCHEMAS[viewTypeConfig.schema]; - effectiveType = viewType; - } - } - } - - const allowedProps = [...schema.properties, ...SYSTEM_PROPERTIES]; - - // 3. Check name exists (if required) - if (schema.required.includes('name') && !field.name) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'name', - errorType: 'MISSING_REQUIRED', - message: `Missing required property 'name' for fieldType '${fieldType}'. The name property is used for data binding and field identification.`, - suggestion: `Add 'name' property with a valid identifier. Format: starts with a letter, followed by letters, numbers, or underscores. Examples: 'firstName', 'email_address', 'field1'`, - }); - } - - // 4. Validate name format - if (field.name !== undefined) { - if (typeof field.name !== 'string') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'name', - errorType: 'INVALID_TYPE', - message: `Property 'name' must be a string, but got ${typeof field.name} (value: ${JSON.stringify(field.name)}).`, - suggestion: `Change 'name' to a string value like "firstName" or "emailAddress".`, - }); - } else if (!NAME_PATTERN.test(field.name)) { - let issue = ''; - if (/^[0-9]/.test(field.name)) { - issue = 'Name cannot start with a number.'; - } else if (/^_/.test(field.name)) { - issue = 'Name cannot start with an underscore.'; - } else if (/[^a-zA-Z0-9_]/.test(field.name)) { - issue = 'Name contains invalid characters (only letters, numbers, and underscores are allowed).'; - } - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'name', - errorType: 'INVALID_FORMAT', - message: `Invalid name format '${field.name}'. ${issue}`, - suggestion: `Change name to match the pattern: starts with a letter (a-z, A-Z), followed by letters, numbers, or underscores. Examples: 'firstName', 'email_address', 'field1'`, - }); - } - } - - // 5. Validate each property - for (const [propName, propValue] of Object.entries(field)) { - // Skip child fields - if (isChildField(propName, propValue)) continue; - // Skip system nested objects - if (['cq:responsive', 'fd:rules', 'fd:events'].includes(propName)) continue; - - // Check if property is allowed - if (!allowedProps.includes(propName)) { - const similar = findSimilarProperties(propName, schema.properties); - let suggestion; - - if (similar.length > 0) { - suggestion = `Did you mean '${similar[0]}'? Remove '${propName}' or replace it with one of: ${similar.join(', ')}`; - } else { - const propsPreview = schema.properties.slice(0, 8).join(', '); - const hasMore = schema.properties.length > 8 ? ` (and ${schema.properties.length - 8} more)` : ''; - suggestion = `Remove property '${propName}'. It is not valid for fieldType '${fieldType}'. Valid properties: ${propsPreview}${hasMore}`; - } - - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_PROPERTY', - message: `Property '${propName}' is not valid for fieldType '${fieldType}'.`, - suggestion: suggestion, - validOptions: schema.properties, - }); - continue; - } - - // Validate property type - const expectedType = PROPERTY_TYPES[propName]; - if (expectedType && expectedType !== 'any' && propValue !== undefined && propValue !== null) { - const actualType = Array.isArray(propValue) ? 'array' : typeof propValue; - - if (expectedType === 'number' && actualType !== 'number') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be a number, but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to a numeric value. Example: "${propName}": 5`, - }); - } else if (expectedType === 'boolean' && actualType !== 'boolean') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be a boolean (true/false), but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to true or false. Example: "${propName}": true`, - }); - } else if (expectedType === 'string' && actualType !== 'string') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be a string, but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to a string value. Example: "${propName}": "value"`, - }); - } else if (expectedType === 'array' && actualType !== 'array') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be an array, but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to an array. Example: "${propName}": ["value1", "value2"]`, - }); - } - } - - // Validate enum values - const enumKey = `${propName}:${fieldType}`; - const enumValues = ENUM_VALUES[enumKey] || ENUM_VALUES[propName]; - - if (enumValues && propValue !== undefined && propValue !== '' && propValue !== null) { - if (!enumValues.includes(String(propValue))) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_VALUE', - message: `Invalid value '${propValue}' for property '${propName}'. This value is not in the list of allowed values.`, - suggestion: `Change '${propName}' to one of the valid values: ${enumValues.join(', ')}`, - validOptions: enumValues, - }); - } - } - } - - // 6. Validate constraints - if (schema.constraints) { - for (const constraint of schema.constraints) { - if (constraint === 'minLength <= maxLength') { - if (field.minLength !== undefined && field.maxLength !== undefined) { - if (field.minLength > field.maxLength) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'minLength/maxLength', - errorType: 'INVALID_CONSTRAINT', - message: `Constraint violation: minLength (${field.minLength}) is greater than maxLength (${field.maxLength}). minLength must be less than or equal to maxLength.`, - suggestion: `Fix the constraint by either: (1) decreasing minLength to ${field.maxLength} or less, OR (2) increasing maxLength to ${field.minLength} or more.`, - }); - } - } - } else if (constraint === 'minimum <= maximum') { - if (field.minimum !== undefined && field.maximum !== undefined) { - if (field.minimum > field.maximum) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'minimum/maximum', - errorType: 'INVALID_CONSTRAINT', - message: `Constraint violation: minimum (${field.minimum}) is greater than maximum (${field.maximum}). minimum must be less than or equal to maximum.`, - suggestion: `Fix the constraint by either: (1) decreasing minimum to ${field.maximum} or less, OR (2) increasing maximum to ${field.minimum} or more.`, - }); - } - } - } else if (constraint === 'minOccur <= maxOccur') { - if (field.minOccur !== undefined && field.maxOccur !== undefined) { - if (field.minOccur > field.maxOccur) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'minOccur/maxOccur', - errorType: 'INVALID_CONSTRAINT', - message: `Constraint violation: minOccur (${field.minOccur}) is greater than maxOccur (${field.maxOccur}). minOccur must be less than or equal to maxOccur.`, - suggestion: `Fix the constraint by either: (1) decreasing minOccur to ${field.maxOccur} or less, OR (2) increasing maxOccur to ${field.minOccur} or more.`, - }); - } - } - } - } - } - - // 7. Check for 'items' wrapper in containers (panels, wizards, etc.) - // The UE patch API expects children as direct siblings of the panel, NOT nested under 'items'. - // An 'items' key containing child components indicates incorrect structure that will cause - // panels to render without their children. - if (schema.isContainer && field.items && typeof field.items === 'object' && !Array.isArray(field.items)) { - const itemsChildKeys = Object.keys(field.items).filter(k => { - const v = field.items[k]; - return typeof v === 'object' && v !== null && !Array.isArray(v) && (v.fieldType || v['sling:resourceType']); - }); - if (itemsChildKeys.length > 0) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'items', - errorType: 'ITEMS_WRAPPER_NOT_ALLOWED', - message: `Container '${fieldName}' has children nested under an 'items' wrapper (found: ${itemsChildKeys.join(', ')}). The UE patch API expects children as direct properties of the panel, not under 'items'. This will cause the panel to render without its fields.`, - suggestion: `Move all children (${itemsChildKeys.join(', ')}) from inside '${fieldName}.items' to be direct properties of '${fieldName}', then remove the 'items' key.`, - }); - } - } - - // 8. Validate pattern is valid regex - if (field.pattern !== undefined && field.pattern !== '') { - try { - new RegExp(field.pattern); - } catch (e) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'pattern', - errorType: 'INVALID_VALUE', - message: `Invalid regex pattern '${field.pattern}'. Error: ${e.message}`, - suggestion: `Fix the regular expression syntax in 'pattern'. Ensure special characters are properly escaped.`, - }); - } - } - - return errors; -} - -/** - * Recursively validate all fields in a form - * @param {object} obj - The object to validate - * @param {string} basePath - The base path for error reporting - * @param {Array} skippedFields - Array to collect skipped fields - * @param {Set<string>} customComponents - Set of custom component IDs from _form.json filters - */ -function validateFormRecursive(obj, basePath = 'root', skippedFields = [], customComponents = null) { - const errors = []; - - // Validate current object if it has fieldType - if (obj.fieldType) { - const result = validateField(obj, basePath, customComponents); - // Check if result is the new format with skipped info - if (result && result.skipped) { - skippedFields.push(result.skipped); - } else if (Array.isArray(result)) { - errors.push(...result); - } - } - - // Recursively validate nested objects - for (const [key, value] of Object.entries(obj)) { - if (typeof value === 'object' && value !== null && !Array.isArray(value)) { - if (['cq:responsive', 'fd:rules', 'fd:events'].includes(key)) continue; - const childPath = basePath === 'root' ? key : `${basePath}.${key}`; - const childResult = validateFormRecursive(value, childPath, skippedFields, customComponents); - errors.push(...childResult.errors); - } - } - - return { errors, skippedFields }; -} - -/** - * Main validation function - * @param {object} form - The form to validate - * @param {object} options - Optional configuration - * @param {Set<string>|Array<string>} options.customComponents - Custom component IDs from _form.json filters - */ -function validate(form, options = {}) { - // Convert array to Set if needed - let customComponents = null; - if (options.customComponents) { - customComponents = options.customComponents instanceof Set - ? options.customComponents - : new Set(options.customComponents); - } - - const result = validateFormRecursive(form, 'root', [], customComponents); - const errors = result.errors; - const skippedFields = result.skippedFields; - - const llmReport = { - success: errors.length === 0, - errorCount: errors.length, - errors: errors.map(e => ({ - location: e.path, - fieldName: e.field, - fieldType: e.fieldType || 'unknown', - property: e.property, - errorType: e.errorType, - problem: e.message, - solution: e.suggestion, - validOptions: e.validOptions, - })), - skippedFields: skippedFields.length > 0 ? skippedFields : undefined, - instructions: errors.length > 0 - ? 'Fix the errors listed above. Each error includes a "solution" field describing exactly how to fix it. If "validOptions" are provided, use one of those values.' - : 'Form validation passed. No changes needed.', - }; - - return { - isValid: errors.length === 0, - errors: errors, - skippedFields: skippedFields, - summary: generateSummary(errors, skippedFields), - llmReport: llmReport, - }; -} - -/** - * Generate human-readable summary - */ -function generateSummary(errors, skippedFields = []) { - const lines = []; - - // Skipped fields notice - if (skippedFields.length > 0) { - lines.push(`⚠ Skipped ${skippedFields.length} field(s) with unknown fd:viewType (custom components):`); - for (const skipped of skippedFields) { - lines.push(` - [${skipped.path}] ${skipped.reason}`); - } - lines.push(''); - } - - if (errors.length === 0) { - lines.push('✓ Form validation passed. All validated fields have valid properties.'); - return lines.join('\n'); - } - - lines.push(`✗ Form validation failed with ${errors.length} error(s):\n`); - - // Group by error type - const byType = new Map(); - for (const error of errors) { - const group = byType.get(error.errorType) || []; - group.push(error); - byType.set(error.errorType, group); - } - - for (const [errorType, typeErrors] of byType) { - lines.push(`## ${errorType} (${typeErrors.length}):`); - for (const error of typeErrors) { - lines.push(` - [${error.path}] ${error.message}`); - lines.push(` Fix: ${error.suggestion}`); - if (error.validOptions && error.validOptions.length <= 10) { - lines.push(` Valid options: ${error.validOptions.join(', ')}`); - } - } - lines.push(''); - } - - return lines.join('\n'); -} - -// ============================================================================ -// EXPORTS -// ============================================================================ - -module.exports = { - validate, - validateField, - VALID_FIELD_TYPES, - FIELD_SCHEMAS, - SYSTEM_PROPERTIES, - PROPERTY_TYPES, - ENUM_VALUES, -}; diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/FormFieldValidator.js b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/FormFieldValidator.js deleted file mode 100644 index 05296cf3..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/FormFieldValidator.js +++ /dev/null @@ -1,1016 +0,0 @@ -/** - * EDS Form Field Validator - * - * Self-contained validator for Adobe EDS form fields. - * Validates form.json against hardcoded field schemas. - * Generates LLM-friendly error messages for correction. - */ - -// ============================================================================ -// FIELD SCHEMAS - All field types from _form.json filters -// ============================================================================ - -/** - * Valid fieldTypes from _form.json filters - */ -export const VALID_FIELD_TYPES = [ - 'form', - 'captcha', - 'checkbox', - 'checkbox-group', - 'date-input', - 'drop-down', - 'email', - 'file-input', - 'form-accordion', - 'form-button', - 'form-fragment', - 'form-image', - 'form-modal', - 'form-reset-button', - 'form-submit-button', - 'number-input', - 'panel', - 'password', - 'plain-text', - 'radio-group', - 'rating', - 'telephone-input', - 'text-input', - 'tnc', - 'wizard', - 'range', - 'multiline-input', - 'accordion', - 'modal', - 'button', // Alias for form-button - 'image', // Alias for form-image -]; - -/** - * Property type definitions - */ -export const PROPERTY_TYPES = { - name: 'string', - 'jcr:title': 'string', - fieldType: 'string', - hideTitle: 'boolean', - dataRef: 'string', - unboundFormElement: 'boolean', - visible: 'boolean', - enabled: 'boolean', - readOnly: 'boolean', - colspan: 'string', - placeholder: 'string', - default: 'any', - description: 'string', - tooltip: 'string', - required: 'boolean', - mandatoryMessage: 'string', - validateExpMessage: 'string', - minLength: 'number', - minLengthMessage: 'string', - maxLength: 'number', - maxLengthMessage: 'string', - pattern: 'string', - validatePictureClauseMessage: 'string', - validatePatternMessage: 'string', - multiLine: 'boolean', - minimum: 'number', - minimumMessage: 'string', - maximum: 'number', - maximumMessage: 'string', - stepValue: 'number', - minimumDate: 'string', - maximumDate: 'string', - enum: 'array', - enumNames: 'array', - type: 'string', - orientation: 'string', - variant: 'string', - multiSelect: 'boolean', - checkedValue: 'string', - enableUncheckedValue: 'boolean', - uncheckedValue: 'string', - buttonText: 'string', - dragDropText: 'string', - maxFileSize: 'number', - maxFileSizeMessage: 'string', - accept: 'array', - acceptMessage: 'string', - repeatable: 'boolean', - minOccur: 'number', - maxOccur: 'number', - repeatAddButtonLabel: 'string', - repeatDeleteButtonLabel: 'string', - fileReference: 'string', - altText: 'string', - fragmentPath: 'string', - editFragment: 'boolean', - showLink: 'boolean', - displayFormat: 'string', -}; - -/** - * Enum values for properties with restricted options - */ -export const ENUM_VALUES = { - colspan: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], - orientation: ['horizontal', 'vertical'], - 'variant:checkbox-group': ['default', 'cards'], - 'variant:radio-group': ['default', 'cards'], - 'variant:panel': ['noButtons', 'addDeleteButtons'], - 'type:number-input': ['integer', 'number'], - 'type:drop-down': ['string', 'boolean', 'number', 'string[]', 'boolean[]', 'number[]'], - 'type:checkbox': ['string', 'boolean', 'number'], - 'type:checkbox-group': ['string[]', 'boolean[]', 'number[]'], - 'type:radio-group': ['string', 'boolean', 'number'], - 'displayFormat:date-input': ['', 'd MMMM, y', 'MMMM d, y', 'EEEE, d MMMM, y', 'EEEE, MMMM d, y', 'd/M/y'], - 'displayFormat:number-input': ['', '¤#,##0.00', '¤####0.00', '#,###,##0.000', '#,###,##0%', '¤/INR#,##0', '¤#,##0', '#,##0.00', '#,##0'], -}; - -/** - * Field schemas - allowed properties for each fieldType - */ -export const FIELD_SCHEMAS = { - 'form': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', - 'customFunctionsPath', 'schemaType', 'track', 'action', 'dataUrl', - 'redirectUrl', 'thankYouMessage', 'submitType', 'prefillService', - 'journeyName' - ], - required: ['fieldType'], - }, - - 'text-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', 'multiLine', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip', 'isTitleRichText', 'type' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'email': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'multiline-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', 'multiLine', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'telephone-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', - 'pattern', 'validatePictureClauseMessage', 'validatePatternMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'number-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', 'type', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', - 'displayFormat', 'description', 'tooltip', 'lang', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'date-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimumDate', 'minimumMessage', 'maximumDate', 'maximumMessage', - 'displayFormat', 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'drop-down': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'placeholder', 'default', - 'enum', 'enumNames', 'multiSelect', 'type', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'checkbox': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'default', - 'type', 'checkedValue', 'enableUncheckedValue', 'uncheckedValue', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'checkbox-group': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'default', - 'enum', 'enumNames', 'variant', 'type', 'orientation', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'radio-group': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'default', - 'enum', 'enumNames', 'variant', 'type', 'orientation', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'file-input': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'type', - 'buttonText', 'dragDropText', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'maxFileSize', 'maxFileSizeMessage', 'accept', 'acceptMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'panel': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'form-button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip', 'isTitleRichText', 'type', - 'analyticsFilePath', 'devLaunchScript', 'prodLaunchScript' - ], - required: ['fieldType', 'name'], - }, - - 'form-submit-button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'form-reset-button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'colspan', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'plain-text': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'dataRef', 'visible', 'colspan', - 'value', 'richText', 'enabled', 'hideTitle', 'type', 'readOnly' - ], - required: ['fieldType', 'name'], - }, - - 'form-image': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'fileReference', 'altText', - 'dataRef', 'visible', 'colspan' - ], - required: ['fieldType', 'name'], - }, - - 'image': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'fileReference', 'altText', - 'dataRef', 'visible', 'colspan' - ], - required: ['fieldType', 'name'], - }, - - 'form-fragment': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'fragmentPath', 'editFragment', - 'repeatable', 'minOccur', 'maxOccur', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'captcha': { - properties: ['name', 'fieldType'], - required: ['fieldType', 'name'], - }, - - 'form-accordion': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'accordion': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'form-modal': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'modal': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'wizard': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'repeatable', 'minOccur', 'maxOccur', 'variant', - 'repeatAddButtonLabel', 'repeatDeleteButtonLabel', - 'description', 'tooltip', 'isTitleRichText' - ], - required: ['fieldType', 'name'], - constraints: ['minOccur <= maxOccur'], - isContainer: true, - }, - - 'password': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minLength', 'minLengthMessage', 'maxLength', 'maxLengthMessage', - 'pattern', 'validatePictureClauseMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minLength <= maxLength'], - }, - - 'rating': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'range': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', - 'required', 'mandatoryMessage', 'validateExpMessage', - 'minimum', 'minimumMessage', 'maximum', 'maximumMessage', 'stepValue', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - constraints: ['minimum <= maximum'], - }, - - 'tnc': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'hideTitle', 'dataRef', 'unboundFormElement', - 'visible', 'enabled', 'readOnly', 'colspan', 'showLink', - 'description', 'tooltip' - ], - required: ['fieldType', 'name'], - }, - - 'button': { - properties: [ - 'name', 'fieldType', 'jcr:title', 'visible', 'enabled', 'readOnly', 'colspan', - 'description', 'tooltip', 'isTitleRichText', 'type', - 'analyticsFilePath', 'devLaunchScript', 'prodLaunchScript' - ], - required: ['fieldType', 'name'], - }, -}; - -/** - * System properties allowed on all fields (AEM/JCR specific) - */ -export const SYSTEM_PROPERTIES = [ - 'jcr:primaryType', - 'jcr:lastModified', - 'jcr:lastModifiedBy', - 'jcr:created', - 'jcr:createdBy', - 'sling:resourceType', - 'cq:responsive', - 'fd:rules', - 'fd:events', - 'fd:version', - 'fd:viewType', - 'id', - 'items', - 'layout', - 'wrapData', - 'textIsRich', - 'autocomplete', - 'tooltipVisible', - 'dorExclusion', - 'buttonType', - 'typeIndex', - 'aueComponentId', - 'title', - 'thankYouOption', - 'themeRef', - 'dorType', - 'label', -]; - -/** - * Valid fd:viewType values for custom components - */ -const VIEW_TYPE_CONFIG = { - 'wizard': { baseFieldType: 'panel', schema: 'wizard' }, - 'accordion': { baseFieldType: 'panel', schema: 'accordion' }, - 'modal': { baseFieldType: 'panel', schema: 'modal' }, - 'tnc': { baseFieldType: 'panel', schema: 'tnc' }, - 'password': { baseFieldType: 'text-input', schema: 'password' }, - 'masked-card': { baseFieldType: 'text-input', schema: 'text-input' }, - 'rating': { baseFieldType: 'number-input', schema: 'rating' }, - 'range': { baseFieldType: 'number-input', schema: 'range' }, - 'toggleable-link': { baseFieldType: 'checkbox-group', schema: 'checkbox-group' }, - 'state-button': { baseFieldType: 'button', schema: 'button' }, - 'analytics': { baseFieldType: 'button', schema: 'button' }, -}; - -const VALID_VIEW_TYPES = Object.keys(VIEW_TYPE_CONFIG); - -/** - * fieldTypes that require fd:viewType for proper rendering - */ -const FIELD_TYPES_REQUIRING_VIEW_TYPE = { - 'wizard': { correctFieldType: 'panel', viewType: 'wizard' }, - 'accordion': { correctFieldType: 'panel', viewType: 'accordion' }, - 'modal': { correctFieldType: 'panel', viewType: 'modal' }, - 'form-accordion': { correctFieldType: 'panel', viewType: 'accordion' }, - 'form-modal': { correctFieldType: 'panel', viewType: 'modal' }, - 'password': { correctFieldType: 'text-input', viewType: 'password' }, - 'rating': { correctFieldType: 'number-input', viewType: 'rating' }, - 'range': { correctFieldType: 'number-input', viewType: 'range' }, - 'tnc': { correctFieldType: 'panel', viewType: 'tnc' }, -}; - -// ============================================================================ -// VALIDATION LOGIC -// ============================================================================ - -const NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/; - -function levenshteinDistance(a, b) { - const matrix = Array(b.length + 1).fill(null).map(() => Array(a.length + 1).fill(0)); - for (let i = 0; i <= a.length; i++) matrix[0][i] = i; - for (let j = 0; j <= b.length; j++) matrix[j][0] = j; - for (let j = 1; j <= b.length; j++) { - for (let i = 1; i <= a.length; i++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - matrix[j][i] = Math.min( - matrix[j][i - 1] + 1, - matrix[j - 1][i] + 1, - matrix[j - 1][i - 1] + cost - ); - } - } - return matrix[b.length][a.length]; -} - -function findSimilarProperties(propName, allowedProps) { - const matches = []; - const propLower = propName.toLowerCase(); - - for (const allowed of allowedProps) { - const allowedLower = allowed.toLowerCase(); - if (allowedLower.includes(propLower) || propLower.includes(allowedLower)) { - matches.push(allowed); - } else if (levenshteinDistance(propLower, allowedLower) <= 3) { - matches.push(allowed); - } - } - - return matches.slice(0, 3); -} - -function isChildField(key, value) { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - return false; - } - if (value.fieldType) return true; - const systemObjects = ['cq:responsive', 'fd:rules', 'fd:events', 'default']; - if (systemObjects.includes(key)) return false; - return false; -} - -export function validateField(field, fieldPath, customComponents = null) { - const errors = []; - - if (!field.fieldType) { - errors.push({ - path: fieldPath, - field: fieldPath.split('.').pop(), - property: 'fieldType', - errorType: 'MISSING_REQUIRED', - message: `Missing required property 'fieldType'. Every form field must have a fieldType that specifies its component type.`, - suggestion: `Add 'fieldType' property with one of the valid values: ${VALID_FIELD_TYPES.slice(0, 10).join(', ')}...`, - validOptions: VALID_FIELD_TYPES, - }); - return errors; - } - - const fieldType = field.fieldType; - const viewType = field['fd:viewType']; - const fieldName = field.name || fieldPath.split('.').pop() || 'unknown'; - - // Detect if this is actually a fragment (panel with fragment properties) - const isFragment = field['sling:resourceType']?.includes('fragment') || - field.aueComponentId === 'form-fragment' || - field.fragmentPath !== undefined; - - let schema = FIELD_SCHEMAS[fieldType]; - - // If this is a fragment, use the form-fragment schema instead - if (isFragment && fieldType === 'panel') { - schema = FIELD_SCHEMAS['form-fragment']; - } - - if (!schema) { - const similar = findSimilarProperties(fieldType, VALID_FIELD_TYPES); - let suggestion = `Change fieldType to one of the valid types.`; - if (similar.length > 0) { - suggestion = `Did you mean '${similar[0]}'? Change fieldType to a valid value.`; - } - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fieldType', - errorType: 'INVALID_VALUE', - message: `Invalid fieldType '${fieldType}'. This is not a recognized form component type.`, - suggestion: suggestion, - validOptions: VALID_FIELD_TYPES, - }); - return errors; - } - - const viewTypeRequirement = FIELD_TYPES_REQUIRING_VIEW_TYPE[fieldType]; - if (viewTypeRequirement && !viewType) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fieldType', - errorType: 'MISSING_VIEW_TYPE', - message: `fieldType '${fieldType}' will not render correctly. It requires fieldType: "${viewTypeRequirement.correctFieldType}" with fd:viewType: "${viewTypeRequirement.viewType}".`, - suggestion: `Change fieldType to "${viewTypeRequirement.correctFieldType}" and add "fd:viewType": "${viewTypeRequirement.viewType}" for proper rendering.`, - }); - } - - let effectiveType = fieldType; - if (viewType) { - const viewTypeConfig = VIEW_TYPE_CONFIG[viewType]; - if (!viewTypeConfig) { - if (customComponents && customComponents.has(viewType)) { - return { - errors: [], - skipped: { - path: fieldPath, - field: fieldName, - fieldType: fieldType, - viewType: viewType, - reason: `fd:viewType '${viewType}' is a custom component. Skipping validation.`, - }, - }; - } else { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fd:viewType', - errorType: 'INVALID_VIEW_TYPE', - message: `Invalid fd:viewType '${viewType}'. This is not a recognized view type.`, - suggestion: customComponents - ? `Change fd:viewType to one of the valid values: ${VALID_VIEW_TYPES.join(', ')}, or add it to the _form.json filters.` - : `Change fd:viewType to one of the valid values: ${VALID_VIEW_TYPES.join(', ')}`, - validOptions: VALID_VIEW_TYPES, - }); - } - } else { - if (fieldType !== viewTypeConfig.baseFieldType) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'fieldType', - errorType: 'INVALID_FIELD_TYPE_FOR_VIEW_TYPE', - message: `fd:viewType '${viewType}' requires fieldType '${viewTypeConfig.baseFieldType}', but found '${fieldType}'.`, - suggestion: `Change fieldType to "${viewTypeConfig.baseFieldType}" when using fd:viewType: "${viewType}".`, - }); - } - if (viewTypeConfig.schema && FIELD_SCHEMAS[viewTypeConfig.schema]) { - schema = FIELD_SCHEMAS[viewTypeConfig.schema]; - effectiveType = viewType; - } - } - } - - const allowedProps = [...schema.properties, ...SYSTEM_PROPERTIES]; - - if (schema.required.includes('name') && !field.name) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'name', - errorType: 'MISSING_REQUIRED', - message: `Missing required property 'name' for fieldType '${fieldType}'. The name property is used for data binding and field identification.`, - suggestion: `Add 'name' property with a valid identifier. Format: starts with a letter, followed by letters, numbers, or underscores. Examples: 'firstName', 'email_address', 'field1'`, - }); - } - - if (field.name !== undefined) { - if (typeof field.name !== 'string') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'name', - errorType: 'INVALID_TYPE', - message: `Property 'name' must be a string, but got ${typeof field.name} (value: ${JSON.stringify(field.name)}).`, - suggestion: `Change 'name' to a string value like "firstName" or "emailAddress".`, - }); - } else if (!NAME_PATTERN.test(field.name)) { - let issue = ''; - if (/^[0-9]/.test(field.name)) { - issue = 'Name cannot start with a number.'; - } else if (/^_/.test(field.name)) { - issue = 'Name cannot start with an underscore.'; - } else if (/[^a-zA-Z0-9_]/.test(field.name)) { - issue = 'Name contains invalid characters (only letters, numbers, and underscores are allowed).'; - } - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'name', - errorType: 'INVALID_FORMAT', - message: `Invalid name format '${field.name}'. ${issue}`, - suggestion: `Change name to match the pattern: starts with a letter (a-z, A-Z), followed by letters, numbers, or underscores. Examples: 'firstName', 'email_address', 'field1'`, - }); - } - } - - for (const [propName, propValue] of Object.entries(field)) { - if (isChildField(propName, propValue)) continue; - if (['cq:responsive', 'fd:rules', 'fd:events'].includes(propName)) continue; - - if (!allowedProps.includes(propName)) { - const similar = findSimilarProperties(propName, schema.properties); - let suggestion; - - if (similar.length > 0) { - suggestion = `Did you mean '${similar[0]}'? Remove '${propName}' or replace it with one of: ${similar.join(', ')}`; - } else { - const propsPreview = schema.properties.slice(0, 8).join(', '); - const hasMore = schema.properties.length > 8 ? ` (and ${schema.properties.length - 8} more)` : ''; - suggestion = `Remove property '${propName}'. It is not valid for fieldType '${fieldType}'. Valid properties: ${propsPreview}${hasMore}`; - } - - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_PROPERTY', - message: `Property '${propName}' is not valid for fieldType '${fieldType}'.`, - suggestion: suggestion, - validOptions: schema.properties, - }); - continue; - } - - const expectedType = PROPERTY_TYPES[propName]; - if (expectedType && expectedType !== 'any' && propValue !== undefined && propValue !== null) { - const actualType = Array.isArray(propValue) ? 'array' : typeof propValue; - - if (expectedType === 'number' && actualType !== 'number') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be a number, but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to a numeric value. Example: "${propName}": 5`, - }); - } else if (expectedType === 'boolean' && actualType !== 'boolean') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be a boolean (true/false), but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to true or false. Example: "${propName}": true`, - }); - } else if (expectedType === 'string' && actualType !== 'string') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be a string, but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to a string value. Example: "${propName}": "value"`, - }); - } else if (expectedType === 'array' && actualType !== 'array') { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_TYPE', - message: `Property '${propName}' must be an array, but got ${actualType} (value: ${JSON.stringify(propValue)}).`, - suggestion: `Change '${propName}' to an array. Example: "${propName}": ["value1", "value2"]`, - }); - } - } - - const enumKey = `${propName}:${fieldType}`; - const enumValues = ENUM_VALUES[enumKey] || ENUM_VALUES[propName]; - - if (enumValues && propValue !== undefined && propValue !== '' && propValue !== null) { - if (!enumValues.includes(String(propValue))) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: propName, - errorType: 'INVALID_VALUE', - message: `Invalid value '${propValue}' for property '${propName}'. This value is not in the list of allowed values.`, - suggestion: `Change '${propName}' to one of the valid values: ${enumValues.join(', ')}`, - validOptions: enumValues, - }); - } - } - } - - if (schema.constraints) { - for (const constraint of schema.constraints) { - if (constraint === 'minLength <= maxLength') { - if (field.minLength !== undefined && field.maxLength !== undefined) { - if (field.minLength > field.maxLength) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'minLength/maxLength', - errorType: 'INVALID_CONSTRAINT', - message: `Constraint violation: minLength (${field.minLength}) is greater than maxLength (${field.maxLength}). minLength must be less than or equal to maxLength.`, - suggestion: `Fix the constraint by either: (1) decreasing minLength to ${field.maxLength} or less, OR (2) increasing maxLength to ${field.minLength} or more.`, - }); - } - } - } else if (constraint === 'minimum <= maximum') { - if (field.minimum !== undefined && field.maximum !== undefined) { - if (field.minimum > field.maximum) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'minimum/maximum', - errorType: 'INVALID_CONSTRAINT', - message: `Constraint violation: minimum (${field.minimum}) is greater than maximum (${field.maximum}). minimum must be less than or equal to maximum.`, - suggestion: `Fix the constraint by either: (1) decreasing minimum to ${field.maximum} or less, OR (2) increasing maximum to ${field.minimum} or more.`, - }); - } - } - } else if (constraint === 'minOccur <= maxOccur') { - if (field.minOccur !== undefined && field.maxOccur !== undefined) { - if (field.minOccur > field.maxOccur) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'minOccur/maxOccur', - errorType: 'INVALID_CONSTRAINT', - message: `Constraint violation: minOccur (${field.minOccur}) is greater than maxOccur (${field.maxOccur}). minOccur must be less than or equal to maxOccur.`, - suggestion: `Fix the constraint by either: (1) decreasing minOccur to ${field.maxOccur} or less, OR (2) increasing maxOccur to ${field.minOccur} or more.`, - }); - } - } - } - } - } - - if (field.pattern !== undefined && field.pattern !== '') { - try { - new RegExp(field.pattern); - } catch (e) { - errors.push({ - path: fieldPath, - field: fieldName, - fieldType: fieldType, - property: 'pattern', - errorType: 'INVALID_VALUE', - message: `Invalid regex pattern '${field.pattern}'. Error: ${e.message}`, - suggestion: `Fix the regular expression syntax in 'pattern'. Ensure special characters are properly escaped.`, - }); - } - } - - return errors; -} - -function validateFormRecursive(obj, basePath = 'root', skippedFields = [], customComponents = null) { - const errors = []; - - if (obj.fieldType) { - const result = validateField(obj, basePath, customComponents); - if (result && result.skipped) { - skippedFields.push(result.skipped); - } else if (Array.isArray(result)) { - errors.push(...result); - } - } - - for (const [key, value] of Object.entries(obj)) { - if (typeof value === 'object' && value !== null && !Array.isArray(value)) { - if (['cq:responsive', 'fd:rules', 'fd:events'].includes(key)) continue; - const childPath = basePath === 'root' ? key : `${basePath}.${key}`; - const childResult = validateFormRecursive(value, childPath, skippedFields, customComponents); - errors.push(...childResult.errors); - } - } - - return { errors, skippedFields }; -} - -export function validate(form, options = {}) { - let customComponents = null; - if (options.customComponents) { - customComponents = options.customComponents instanceof Set - ? options.customComponents - : new Set(options.customComponents); - } - - const result = validateFormRecursive(form, 'root', [], customComponents); - const errors = result.errors; - const skippedFields = result.skippedFields; - - const llmReport = { - success: errors.length === 0, - errorCount: errors.length, - errors: errors.map(e => ({ - location: e.path, - fieldName: e.field, - fieldType: e.fieldType || 'unknown', - property: e.property, - errorType: e.errorType, - problem: e.message, - solution: e.suggestion, - validOptions: e.validOptions, - })), - skippedFields: skippedFields.length > 0 ? skippedFields : undefined, - instructions: errors.length > 0 - ? 'Fix the errors listed above. Each error includes a "solution" field describing exactly how to fix it. If "validOptions" are provided, use one of those values.' - : 'Form validation passed. No changes needed.', - }; - - return { - isValid: errors.length === 0, - errors: errors, - skippedFields: skippedFields, - summary: generateSummary(errors, skippedFields), - llmReport: llmReport, - }; -} - -function generateSummary(errors, skippedFields = []) { - const lines = []; - - if (skippedFields.length > 0) { - lines.push(`⚠ Skipped ${skippedFields.length} field(s) with unknown fd:viewType (custom components):`); - for (const skipped of skippedFields) { - lines.push(` - [${skipped.path}] ${skipped.reason}`); - } - lines.push(''); - } - - if (errors.length === 0) { - lines.push('✓ Form validation passed. All validated fields have valid properties.'); - return lines.join('\n'); - } - - lines.push(`✗ Form validation failed with ${errors.length} error(s):\n`); - - const byType = new Map(); - for (const error of errors) { - const group = byType.get(error.errorType) || []; - group.push(error); - byType.set(error.errorType, group); - } - - for (const [errorType, typeErrors] of byType) { - lines.push(`## ${errorType} (${typeErrors.length}):`); - for (const error of typeErrors) { - lines.push(` - [${error.path}] ${error.message}`); - lines.push(` Fix: ${error.suggestion}`); - if (error.validOptions && error.validOptions.length <= 10) { - lines.push(` Valid options: ${error.validOptions.join(', ')}`); - } - } - lines.push(''); - } - - return lines.join('\n'); -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/validate.cjs b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/validate.cjs deleted file mode 100644 index 93d40ad5..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/validate.cjs +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env node -/** - * EDS Form Validator CLI - * - * Self-contained validator with optional _form.json for custom components. - * - * Usage: - * node validate.cjs <form.json> - * node validate.cjs <form.json> <_form.json> - * node validate.cjs <form.json> --json - */ - -const fs = require('fs'); -const path = require('path'); -const { validate } = require('./FormFieldValidator.cjs'); - -function main() { - const args = process.argv.slice(2); - const nonFlagArgs = args.filter(a => !a.startsWith('--')); - const jsonOnly = args.includes('--json'); - - if (args.includes('--help') || args.includes('-h') || nonFlagArgs.length < 1) { - console.log(` -EDS Form Field Validator -======================== - -A self-contained validator for Adobe EDS form fields. -Validates form.json against built-in field schemas. - -Usage: - node validate.cjs <form.json> Validate a form file - node validate.cjs <form.json> <_form.json> Validate with custom components from _form.json - node validate.cjs <form.json> --json Output JSON report only (for LLM) - node validate.cjs <form.json> <_form.json> --json Both options combined - node validate.cjs --help Show this help - -Arguments: - form.json Path to the form definition file to validate - _form.json (Optional) Path to _form.json containing custom component filters - If provided, unknown fd:viewType values that match components in - the filters will be skipped (custom components). - If not provided, unknown fd:viewType values will cause errors. - -What it validates: - - fieldType: Must be present and valid - - fd:viewType: Must be valid (or match custom component in _form.json) - - name: Must be present, start with letter, contain only letters/numbers/underscores - - Property names: Must be valid for the field type - - Property types: string, number, boolean, array as expected - - Property values: Must be in allowed enum values where applicable - - Constraints: minLength <= maxLength, minimum <= maximum, etc. - - Regex patterns: Must be valid regular expressions - -Examples: - node validate.cjs ./form.json - node validate.cjs ./form.json ./authoring/_form.json - node validate.cjs /path/to/my-form.json --json -`); - process.exit(args.includes('--help') || args.includes('-h') ? 0 : 1); - } - - const formPath = nonFlagArgs[0]; - const formJsonPath = nonFlagArgs[1]; // Optional _form.json path - - // Load form - let form; - try { - form = JSON.parse(fs.readFileSync(formPath, 'utf-8')); - } catch (e) { - console.error(`Error loading form from ${formPath}: ${e.message}`); - process.exit(1); - } - - // Load _form.json if provided to get custom components - let customComponents = null; - if (formJsonPath) { - try { - const formJson = JSON.parse(fs.readFileSync(formJsonPath, 'utf-8')); - // Extract components from filters - if (formJson.filters && formJson.filters[0] && formJson.filters[0].components) { - customComponents = formJson.filters[0].components; - if (!jsonOnly) { - console.log(`Loaded ${customComponents.length} custom components from ${formJsonPath}`); - } - } - } catch (e) { - console.error(`Error loading _form.json from ${formJsonPath}: ${e.message}`); - process.exit(1); - } - } - - // Validate - const options = customComponents ? { customComponents } : {}; - const result = validate(form, options); - - // Output - if (jsonOnly) { - console.log(JSON.stringify(result.llmReport, null, 2)); - } else { - console.log('\n' + result.summary); - console.log('\n--- JSON Report (for LLM) ---'); - console.log(JSON.stringify(result.llmReport, null, 2)); - } - - process.exit(result.isValid ? 0 : 1); -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/validate.js b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/validate.js deleted file mode 100644 index 5e081685..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/eds_form_validator/validate.js +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env node -/** - * EDS Form Validator CLI - * - * Self-contained validator with optional _form.json for custom components. - * - * Usage: - * node validate.js <form.json> - * node validate.js <form.json> <_form.json> - * node validate.js <form.json> --json - */ - -import fs from 'fs'; -import path from 'path'; -import { fileURLToPath } from 'url'; -import { validate } from './FormFieldValidator.js'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -function main() { - const args = process.argv.slice(2); - const nonFlagArgs = args.filter(a => !a.startsWith('--')); - const jsonOnly = args.includes('--json'); - - if (args.includes('--help') || args.includes('-h') || nonFlagArgs.length < 1) { - console.log(` -EDS Form Field Validator -======================== - -A self-contained validator for Adobe EDS form fields. -Validates form.json against built-in field schemas. - -Usage: - node validate.js <form.json> Validate a form file - node validate.js <form.json> <_form.json> Validate with custom components from _form.json - node validate.js <form.json> --json Output JSON report only (for LLM) - node validate.js <form.json> <_form.json> --json Both options combined - node validate.js --help Show this help - -Arguments: - form.json Path to the form definition file to validate - _form.json (Optional) Path to _form.json containing custom component filters - If provided, unknown fd:viewType values that match components in - the filters will be skipped (custom components). - If not provided, unknown fd:viewType values will cause errors. - -What it validates: - - fieldType: Must be present and valid - - fd:viewType: Must be valid (or match custom component in _form.json) - - name: Must be present, start with letter, contain only letters/numbers/underscores - - Property names: Must be valid for the field type - - Property types: string, number, boolean, array as expected - - Property values: Must be in allowed enum values where applicable - - Constraints: minLength <= maxLength, minimum <= maximum, etc. - - Regex patterns: Must be valid regular expressions - - Fragments: Auto-detects panel fields that are fragments (via sling:resourceType, - aueComponentId, or fragmentPath) and validates using form-fragment schema - -Examples: - node validate.js ./form.json - node validate.js ./form.json ./authoring/_form.json - node validate.js /path/to/my-form.json --json -`); - process.exit(args.includes('--help') || args.includes('-h') ? 0 : 1); - } - - const formPath = nonFlagArgs[0]; - const formJsonPath = nonFlagArgs[1]; // Optional _form.json path - - // Load form - let form; - try { - form = JSON.parse(fs.readFileSync(formPath, 'utf-8')); - } catch (e) { - console.error(`Error loading form from ${formPath}: ${e.message}`); - process.exit(1); - } - - // Load _form.json if provided to get custom components - let customComponents = null; - if (formJsonPath) { - try { - const formJson = JSON.parse(fs.readFileSync(formJsonPath, 'utf-8')); - // Extract components from filters - if (formJson.filters && formJson.filters[0] && formJson.filters[0].components) { - customComponents = formJson.filters[0].components; - if (!jsonOnly) { - console.log(`Loaded ${customComponents.length} custom components from ${formJsonPath}`); - } - } - } catch (e) { - console.error(`Error loading _form.json from ${formJsonPath}: ${e.message}`); - process.exit(1); - } - } - - // Validate - const options = customComponents ? { customComponents } : {}; - const result = validate(form, options); - - // Output - if (jsonOnly) { - console.log(JSON.stringify(result.llmReport, null, 2)); - } else { - console.log('\n' + result.summary); - console.log('\n--- JSON Report (for LLM) ---'); - console.log(JSON.stringify(result.llmReport, null, 2)); - } - - process.exit(result.isValid ? 0 : 1); -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/form-validate b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/form-validate deleted file mode 100755 index 79701a35..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts/form-validate +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec node "$SCRIPT_DIR/eds_form_validator/validate.cjs" "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/SKILL.md deleted file mode 100644 index 0ad82efb..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/SKILL.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -name: scaffold-form -description: > - Scaffolds a new, empty AEM Adaptive Form JSON file pair (form.json + rule.json) from - a built-in template. Auto-converts kebab/snake-case names to Title Case, supports - optional submit button, and refuses to overwrite existing files. Use when starting a - brand-new form definition from scratch without touching AEM. - Triggers: scaffold form, new form, blank form, empty form, form template, form skeleton, - generate form json, scaffold-form, create form locally. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# Form Scaffolder - -You generate empty AEM Adaptive Form JSON files from a template using the `scaffold-form` CLI. - -## When to Use - -- Creating a brand-new form definition locally (without AEM) -- Generating a starter form.json + rule.json pair -- Starting from a clean template before adding fields - -**Do NOT use for:** Modifying existing forms (use **create-form** skill), or creating forms on AEM Author (use **sync-forms** skill). - -## Critical Rules - -1. **Use the CLI** — do not hand-create form.json files from scratch -2. **Will not overwrite** — the tool refuses to create files that already exist -3. **Naming convention** — form names should be kebab-case (e.g., `my-registration-form`) -4. **Always add fields after scaffolding** — the scaffolded form is empty; delegate to the **create-form** skill to add fields - -## Tool Commands - -| Action | Command | -|--------|---------| -| Scaffold a form | `scaffold-form <form_name>` | -| With custom title | `scaffold-form <form_name> --title "My Form Title"` | -| With submit button | `scaffold-form <form_name> --with-submit` | -| Custom output dir | `scaffold-form <form_name> --output-dir ./my-dir` | - -## Workflow - -1. **Scaffold** — `scaffold-form my-registration-form --with-submit` -2. **Verify** — check the generated `form/my-registration-form.form.json` and `.rule.json` -3. **Add fields** — delegate to the **create-form** skill to populate the form -4. **Add rules** — delegate to the **add-rules** skill for business logic - -## Output - -The tool generates two files: - -``` -<output-dir>/ -├── <form_name>.form.json # Empty form structure with metadata -└── <form_name>.rule.json # Empty rules file -``` - -The form.json includes: -- Proper AEM resource types and field types -- Auto-generated Title Case title from the form name -- Optional submit button (when `--with-submit` is used) - -## Examples - -### Basic form -```bash -scaffold-form customer-onboarding -``` -Creates `form/customer-onboarding.form.json` with title "Customer Onboarding". - -### Form with submit button in custom directory -```bash -scaffold-form loan-application --with-submit --output-dir ./forms -``` -Creates `forms/loan-application.form.json` with title "Loan Application" and a submit button. - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| File already exists | Choose a different name or delete the existing file first | -| Wrong title | Use `--title "Custom Title"` to override auto-generated title | -| No output | Check `--output-dir` path exists | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold-form b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold-form deleted file mode 100755 index f36381bf..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold-form +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m scaffold_form "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/__init__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/__init__.py deleted file mode 100644 index 412f3fe2..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Scaffold Form — creates empty AEM Adaptive Form JSON from template.""" - -__version__ = "0.1.0" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/__main__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/__main__.py deleted file mode 100644 index d16a1ae4..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Module entry point: python -m scaffold_form""" - -from .cli import main - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/cli.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/cli.py deleted file mode 100644 index 007d9657..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts/scaffold_form/cli.py +++ /dev/null @@ -1,143 +0,0 @@ -"""CLI for scaffold_form — creates empty AEM Adaptive Form JSON from template. - -Usage: - python -m scaffold_form my-registration-form - python -m scaffold_form my-form --title "My Custom Title" --output-dir out/ --with-submit -""" - -from __future__ import annotations - -import argparse -import json -import os -import sys -from pathlib import Path - - -def _name_to_title(form_name: str) -> str: - """Convert a kebab-case or snake_case form name to a title-case string. - - Examples: - my-registration-form -> My Registration Form - contact_us -> Contact Us - simpleform -> Simpleform - """ - return form_name.replace("-", " ").replace("_", " ").title() - - -def _build_form_json(title: str, *, with_submit: bool = False) -> dict: - """Return the JCR-format AEM Adaptive Form structure.""" - form: dict = { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "fd/franklin/components/form/v1/form", - "fieldType": "form", - "fd:version": "2.1", - "title": title, - } - - if with_submit: - form["submit"] = { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/actions/submit/v1/submit", - "fieldType": "form-submit-button", - "name": "submit", - "jcr:title": "Submit", - } - - return form - - -def _build_rule_json() -> dict: - """Return the default (empty) rule definition.""" - return {} - - -def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: - parser = argparse.ArgumentParser( - prog="scaffold_form", - description="Create an empty AEM Adaptive Form JSON from a template.", - ) - parser.add_argument( - "form_name", - help="Name of the form (used as the file-name stem, e.g. 'my-form').", - ) - parser.add_argument( - "--title", - default=None, - help="Human-readable form title. Defaults to the form name in Title Case.", - ) - parser.add_argument( - "--output-dir", - default="form", - dest="output_dir", - help="Directory where the generated files are written (default: form/).", - ) - parser.add_argument( - "--with-submit", - action="store_true", - default=False, - dest="with_submit", - help="Include a submit button in the generated form.", - ) - return parser.parse_args(argv) - - -def main(argv: list[str] | None = None) -> int: - """Entry point. Returns an integer exit code (0 = success).""" - args = _parse_args(argv) - - form_name: str = args.form_name - title: str = args.title if args.title else _name_to_title(form_name) - output_dir = Path(args.output_dir) - - form_path = output_dir / f"{form_name}.form.json" - rule_path = output_dir / f"{form_name}.rule.json" - - # ── Guard: refuse to overwrite existing form.json ──────────────── - if form_path.exists(): - print( - f"Error: {form_path} already exists. " - "Remove it first or choose a different form name / output directory.", - file=sys.stderr, - ) - return 1 - - # ── Ensure output directory exists ─────────────────────────────── - try: - output_dir.mkdir(parents=True, exist_ok=True) - except OSError as exc: - print( - f"Error: could not create output directory '{output_dir}': {exc}", - file=sys.stderr, - ) - return 1 - - # ── Build JSON payloads ────────────────────────────────────────── - form_json = _build_form_json(title, with_submit=args.with_submit) - rule_json = _build_rule_json() - - # ── Write files ────────────────────────────────────────────────── - try: - form_path.write_text(json.dumps(form_json, indent=2) + "\n", encoding="utf-8") - rule_path.write_text(json.dumps(rule_json, indent=2) + "\n", encoding="utf-8") - except OSError as exc: - print(f"Error: failed to write output files: {exc}", file=sys.stderr) - return 1 - - # ── Print confirmation + JSON summary to stdout ────────────────── - summary = { - "form_name": form_name, - "title": title, - "with_submit": args.with_submit, - "files_created": [ - str(form_path), - str(rule_path), - ], - } - - print(f"✔ Created {form_path}") - print(f"✔ Created {rule_path}") - print() - print(json.dumps(summary, indent=2)) - - return 0 diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/context/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/context/SKILL.md deleted file mode 100644 index 17f50f53..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/context/SKILL.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -name: context -description: Domain router for agent memory & session continuity skills -type: domain -triggers: - - update reports - - save progress - - handover - - session log - - agent memory - - save state - - session summary -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Context — Domain Router - -| | | -|---|---| -| **ID** | `context` | -| **Version** | 0.1 | -| **Description** | Routes agent memory & session continuity intents to the correct skill. | - -## Routing Table - -First match wins. - -| Intent | Examples | Skill | -|--------|----------|-------| -| Update project reports, save progress, handover | "update reports", "save progress", "write handover" | `manage-context` | -| Session summary, recall past work | "what did we do", "session summary", "session log" | `manage-context` | - -## Skills - -| # | Skill | Purpose | Triggers | -|---|-------|---------|----------| -| 1 | `manage-context` | Update project reports, save progress, session log | update reports, save progress, handover, session log, agent memory, save state, session summary | - -### Skill Locations - -| Skill | Path | -|-------|------| -| `manage-context` | `references/manage-context/SKILL.md` | - -## Guard Policies - -> After each plan completes, the orchestrator prompts: -> **"Would you like me to update the project reports?"** -> If confirmed, routes here. Never update silently. - -## File Locations - -| Asset | Path | -|-------|------| -| Project state snapshot | `.agent/handover.md` | -| Archived handovers | `.agent/history.md` | -| Session log | `.agent/sessions.md` | - -## Dependencies - -All plans may invoke the context domain at post-plan checkpoints for report updates. - -## Plan Integration - -Invoked at post-plan checkpoints to update project reports (handover, history, session log). After each plan completes its validate + deploy step, the orchestrator offers to run `manage-context` for report updates. - -## Extending This Domain - -1. Create a new skill directory under `references/<skill-name>/`. -2. Add a `SKILL.md` following the skill template structure. -3. Register the skill in the **Skills** table and **Skill Locations** sub-table above. -4. Add a routing entry in the **Routing Table** for the intents the new skill handles. -5. Update **triggers** in the YAML frontmatter if the new skill introduces new trigger phrases. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/context/references/manage-context/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/context/references/manage-context/SKILL.md deleted file mode 100644 index 66bce4f4..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/context/references/manage-context/SKILL.md +++ /dev/null @@ -1,235 +0,0 @@ ---- -name: manage-context -description: > - Manages agent memory files in the .agent/ workspace directory — handover.md, - history.md, and sessions.md. Maintains continuity across sessions by capturing - project state, archiving history, and logging session activity. Opt-in — - prompts the user before updating. - Triggers: update context, save progress, handover, session log, agent memory, - update reports, save state, what did we do, session summary. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Context Manager - -Manages the `.agent/` directory — the agent's memory across sessions. - ---- - -## When to Use - -- After executing or implementing a plan (prompt the user first) -- User explicitly asks to save progress, update handover, or log the session -- At the end of a session when the user confirms they're done -- User asks "what did we do?" or "summarize this session" - -**Do NOT** update `.agent/` files silently. Always ask the user first. - ---- - -## Files - -| File | Purpose | Update Mode | -|------|---------|-------------| -| `handover.md` | Latest project state snapshot — what's done, what's pending, how to resume | Overwrite | -| `history.md` | Append-only archive of previous handover snapshots with timestamps | Append | -| `sessions.md` | Chronological session log — date, agent, session ID, summary | Append | - -All files live in `.agent/` at the workspace root. - ---- - -## User Prompt - -After a plan is executed or a significant milestone is reached, ask: - -> **Would you like me to update the project reports?** -> This saves the current progress to `.agent/` so the next session can pick up where we left off. - -Only proceed if the user confirms. If declined, skip silently — do not ask again until the next plan completes. - ---- - -## Update Procedure - -When the user confirms, execute these steps in order: - -### Step 1 — Archive current handover - -Read `.agent/handover.md`. If it exists and is non-empty, append its content to `.agent/history.md` with a timestamp header: - -``` ---- -## Archived: YYYY-MM-DD HH:MM - -<previous handover.md content> -``` - -If `handover.md` does not exist or is empty, skip this step. - -### Step 2 — Write new handover - -Overwrite `.agent/handover.md` with a fresh snapshot using this template: - -``` -# Project Handover - -**Last updated:** YYYY-MM-DD HH:MM -**Workspace:** <workspace name> -**Active journey:** <journey name> | **Active plan:** <plan number> - ---- - -## Journey Status - -| Journey | Total Plans | Completed | Status | Progress | -|---------|-------------|-----------|--------|----------| -| <journey-1> | N | X | 🔵 Active / ✅ Done / ⏸️ Paused | X/N (XX%) | -| <journey-2> | N | X | ⏸️ Paused | X/N (XX%) | - ---- - -## Plan Execution Status — <active journey> - -| Plan | Title | Phase(s) | Status | Summary | -|------|-------|----------|--------|---------| -| 01 | <title> | Build | ✅ Done | <one-line summary of what was delivered> | -| 02 | <title> | Logic | ✅ Done | <one-line summary> | -| 03 | <title> | Logic | 🔵 Active | <what's in progress> | -| 04 | <title> | Integrate, Logic | ⬚ Pending | | -| ... | ... | ... | ... | | - -**Plan statuses:** ✅ Done — 🔵 Active — ⬚ Pending — ⏸️ Blocked — ❌ Failed - ---- - -## Current Plan Details - -**Plan:** <number> — <title> -**File:** `plans/<journey>/<plan-file>.md` -**Skills:** <skills this plan invokes> -**Depends on:** <plan numbers> - -### What's Done (this session) - -- <completed item 1> -- <completed item 2> - -### What's Remaining (this plan) - -- <next step 1> -- <next step 2> - -### Key Files Modified - -| File | Status | Notes | -|------|--------|-------| -| <path> | created/modified | <brief note> | - ---- - -## How to Resume - -<1-2 sentences: which plan, which step within that plan, which skill to invoke> -``` - -Keep it concise — aim for ≤ 60 lines. The Plan Execution Status table is the primary dashboard; Current Plan Details covers only the active plan. - -When **multiple journeys** exist, show the Plan Execution Status table only for the active journey. Completed journeys show only their row in the Journey Status table (details are in `history.md`). - -### Step 3 — Log session - -Append a row to `.agent/sessions.md`. If the file doesn't exist, create it with the header first: - -``` -# Session Log - -| Date | Agent | Session ID | Summary | -|------|-------|------------|---------| -``` - -Then append the row: - -``` -| YYYY-MM-DD | <agent name> | <session ID or —> | <one-line summary of what was accomplished> | -``` - -If the session ID is not available, use `—`. - -### Step 4 — Archive completed journey (if applicable) - -When **all plans** for a journey show status ✅ Done: - -1. **Build a journey completion record** from the Plan Execution Status table: - -``` ---- -## Journey Completed: <journey-name> — YYYY-MM-DD HH:MM - -### Summary - -| Metric | Value | -|--------|-------| -| Journey | <journey-name> | -| Plans executed | N | -| Start date | YYYY-MM-DD | -| Completion date | YYYY-MM-DD | -| Total screens | X | -| Total fields | X | -| Total rules | X | - -### Plan Execution Log - -| Plan | Title | Phase(s) | Summary | -|------|-------|----------|---------| -| 01 | <title> | Build | <summary> | -| 02 | <title> | Logic | <summary> | -| ... | ... | ... | ... | - -### Key Artifacts - -| Artifact | Path | -|----------|------| -| Form JSON | `repo/content/forms/af/<team>/<path>/<name>.form.json` | -| Rule store | `repo/content/forms/af/<team>/<path>/<name>.rule.json` | -| Form script | `code/blocks/form/scripts/form/<name>.js` | -| Screen docs | `journeys/<journey>/screens/*/Screen.md` | - -### Lessons / Notes - -- <any notable decisions, workarounds, or technical debt> -``` - -2. **Append** this record to `.agent/history.md` -3. **Update** `.agent/handover.md`: - - Move the journey's row in Journey Status to ✅ Done - - Remove that journey's Plan Execution Status table - - If another journey is queued, promote it to active - - If no journeys remain, set Active journey to `—` - ---- - -## Reading Context (Session Start) - -When starting a new session, if `.agent/handover.md` exists, read it to understand: -- What phase the project is in -- What was completed previously -- What's pending -- Key file locations - -Do NOT read `history.md` or `sessions.md` unless the user asks about past sessions. They exist for traceability, not for routine context loading. - ---- - -## Rules - -1. **Always ask before writing.** Never update `.agent/` files without user confirmation. -2. **Handover must be concise.** No more than 60 lines. The Plan Execution Status table is the primary dashboard — keep plan summaries to one line each. -3. **History is append-only.** Never modify or truncate `history.md`. -4. **Sessions is append-only.** Never modify or truncate `sessions.md`. -5. **No sensitive data.** Never write credentials, tokens, or secrets to `.agent/` files. -6. **Create if missing.** If any `.agent/` file doesn't exist, create it — don't error. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/SKILL.md deleted file mode 100644 index cba829b0..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/SKILL.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -name: infra -description: > - Domain router for infrastructure skills — workspace setup, form sync, - EDS code sync, and sandboxed git operations. -type: domain -triggers: - - setup - - sync - - pull - - push - - deploy - - git - - workspace - - credentials -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Infra — Domain Router - -**ID:** `infra` -**Version:** 0.1 -**Description:** Domain router for infrastructure skills — workspace setup, form sync, EDS code sync, and sandboxed git operations. - -This router does not implement — it delegates. It matches user intents to the correct skill within this domain. - ---- - -## Routing Table - -First match wins. - -| Intent | Examples | Skill | -|--------|----------|-------| -| Set up workspace, initialize project, configure credentials, system prereqs | "set up my workspace", "configure credentials" | `setup-workspace` | -| Pull / push / list / create forms on AEM, form sync | "sync my forms", "pull forms from AEM", "list forms" | `sync-forms` | -| Pull / push EDS code, create branch, open PR on GitHub, code sync | "push EDS code", "open a PR on GitHub", "sync code" | `sync-eds-code` | -| Sandboxed git commit / push / reset, restricted git operations | "commit my changes", "git push", "reset branch" | `git-sandbox` | - -> If the intent is ambiguous between two skills, present the options to the user and let them choose. - ---- - -## Skills - -All skills owned by this domain. - -| # | Skill | Purpose | Triggers | -|---|-------|---------|----------| -| 1 | `setup-workspace` | Initialize project, configure credentials | setup, workspace, credentials, initialize | -| 2 | `sync-forms` | Pull / push / list / create forms on AEM | sync, forms, pull, push, list, create | -| 3 | `sync-eds-code` | Pull / push EDS code, branch, open PR on GitHub | sync, code, eds, branch, pr, github | -| 4 | `git-sandbox` | Sandboxed git operations (commit, push, reset) | git, commit, push, reset, sandbox | - -### Skill Locations - -| Skill | Path | -|-------|------| -| `setup-workspace` | [`references/setup-workspace/SKILL.md`](references/setup-workspace/SKILL.md) | -| `sync-forms` | [`references/sync-forms/SKILL.md`](references/sync-forms/SKILL.md) | -| `sync-eds-code` | [`references/sync-eds-code/SKILL.md`](references/sync-eds-code/SKILL.md) | -| `git-sandbox` | [`references/git-sandbox/SKILL.md`](references/git-sandbox/SKILL.md) | - ---- - -## Guard Policies - -Guard policies are constraints that apply across all skills in this domain. They prevent unsafe or incorrect operations. - -> **delegation-only:** This router does not implement — it delegates. All execution is performed by the individual skills listed in the routing table. - ---- - -## Config Files - -| File | Managed By | Purpose | -|------|------------|---------| -| `metadata.json` | `sync-forms` | Tracks synced form/fragment paths (AEM ↔ local) | -| `sandbox.json` | `git-sandbox` | Restricts allowed commit paths and push branch names | - ---- - -## File Locations - -Canonical paths for assets managed by skills in this domain. - -| Asset | Path | -|-------|------| -| Forms | `repo/content/forms/af/<team>/<path>/<name>.form.json` | -| Rule stores | `repo/content/forms/af/<team>/<path>/<name>.rule.json` | -| EDS code | `code/blocks/form/` | - ---- - -## Dependencies - -Other domains or skills that this domain's skills may delegate to or depend on. - -| Dependency | Direction | Reason | -|------------|-----------|--------| -| All other domains | Other domains → `infra` | All other domains depend on infra for deployment (`sync-forms`, `sync-eds-code`, `git-sandbox`) | - ---- - -## Plan Integration - -How this domain participates in plan-driven execution. - -| When | Skill(s) Invoked | Role | -|------|-------------------|------| -| Before any plans — workspace setup | `setup-workspace` | Initializes project, configures credentials, verifies prerequisites | -| End of each plan's validate + deploy step | `sync-forms`, `sync-eds-code`, `git-sandbox` | Deploys form JSON, pushes EDS code, and commits changes after each plan completes | - ---- - -## Extending This Domain - -### Adding a New Skill - -1. Create the skill folder: `references/infra/references/<skill-name>/` -2. Add a `SKILL.md` inside the skill folder — this is the skill's entry point -3. Add the skill to the **Routing Table** above with its intent patterns -4. Add the skill to the **Skills** table and **Skill Locations** table above -5. Register the skill in the domain registry (`domains/SKILL.md`) — both the **Skills Catalog** and **Intent → Domain Routing** tables -6. If the skill manages new file types, add them to the **File Locations** table -7. If the skill manages config files, add them to the **Config Files** table -8. If needed, add guard policies that apply to the new skill \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/SKILL.md deleted file mode 100644 index 842daecd..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/SKILL.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -name: git-sandbox -description: > - Provides a restricted, sandboxed git workspace for AI agents. Clones a repository - using sparse checkout with configurable allowed paths, validates commits to ensure - only permitted files are included, validates push branch names, and supports hard - reset to clean state. Driven by a sandbox.json config file. - Triggers: git sandbox, sandbox, workspace, restricted git, safe git, allowed paths, - sparse checkout, isolated workspace, git-sandbox. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# Git Sandbox - -You manage a restricted git workspace that ensures AI agents can only interact with approved files and branches, using the `git-sandbox` CLI. - -## When to Use - -- Setting up an isolated git workspace for safe code operations -- Committing changes with path validation (only allowed files) -- Pushing to pre-approved branch patterns -- Resetting a workspace to a clean state - -## Critical Rules - -1. **Always use the `git-sandbox` CLI** — do not use raw `git` commands in the sandbox workspace -2. **Check `sandbox.json` first** — all behavior is driven by this config file -3. **Init before use** — always `git-sandbox init` before any other operation -4. **Check status before commit** — `git-sandbox status` shows which files are allowed vs denied -5. **Never force-push** — the sandbox validates branch names to prevent accidents - -## Tool Commands - -| Action | Command | -|--------|---------| -| Initialize workspace | `git-sandbox init` | -| Check file status | `git-sandbox status` | -| Commit changes | `git-sandbox commit -m "message"` | -| Push to branch | `git-sandbox push <branch>` | -| Soft reset | `git-sandbox reset` | -| Hard reset (re-clone) | `git-sandbox reset --hard` | -| Show sample config | `git-sandbox example-config` | - -## Workflow - -1. **Configure** — create `sandbox.json` with repo URL, allowed paths, and branch patterns -2. **Init** — `git-sandbox init` to clone with sparse checkout -3. **Work** — edit files within allowed paths -4. **Check** — `git-sandbox status` to verify all changes are in allowed paths -5. **Commit** — `git-sandbox commit -m "description"` (validates paths) -6. **Push** — `git-sandbox push feature-branch` (validates branch name) - -## Configuration - -Create `sandbox.json` in project root: - -```json -{ - "repo": "https://${GITHUB_TOKEN}@github.com/owner/repo.git", - "branch": "main", - "workspace": "./workspace", - "allowed_paths": [ - "blocks/form/**", - "scripts/**" - ], - "allowed_branches": [ - "feature/*", - "fix/*" - ] -} -``` - -| Field | Required | Description | -|-------|----------|-------------| -| `repo` | Yes | Git clone URL (supports `${VAR}` expansion from `.env`) | -| `branch` | Yes | Branch to clone from | -| `workspace` | No | Local workspace path (default: `./workspace`) | -| `allowed_paths` | No | Glob patterns for permitted files (default: `["**"]`) | -| `allowed_branches` | No | Glob patterns for permitted push branches (default: `["*"]`) | - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Init fails | Check repo URL and `GITHUB_TOKEN` in `.env` | -| Commit rejected | Run `status` — some changed files are outside `allowed_paths` | -| Push rejected | Branch name doesn't match `allowed_branches` patterns | -| Stale workspace | Run `git-sandbox reset --hard` to re-clone | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git-sandbox b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git-sandbox deleted file mode 100755 index a7a277a1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git-sandbox +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m git_sandbox.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/__init__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/__init__.py deleted file mode 100644 index 4edba2e3..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Git Sandbox - Restricted git workspace for AI agents.""" - -__version__ = "0.1.0" -__author__ = "Adobe" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/cli.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/cli.py deleted file mode 100644 index f2820e54..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/cli.py +++ /dev/null @@ -1,320 +0,0 @@ -"""CLI entry point for git-sandbox.""" - -import sys -from pathlib import Path - -import click - -from . import __version__ -from .config import Config -from .exceptions import ConfigurationError, GitSandboxError -from .workspace import Workspace - - -@click.group() -@click.version_option(version=__version__, prog_name="git-sandbox") -def cli(): - """Git Sandbox - Restricted git workspace for AI agents. - - \b - A simple tool that provides controlled git access: - - Validates file paths before commits - - Validates branch names before pushes - - Can reset workspace to clean state - - \b - Quick start: - 1. Create sandbox.json with your config - 2. Run: git-sandbox init - 3. Make changes in workspace/ - 4. Run: git-sandbox commit -m "message" - 5. Run: git-sandbox push <branch-name> - """ - pass - - -def _load_config(config_path: Path = None) -> Config: - """Load configuration with error handling.""" - try: - return Config.load(path=config_path) - except ConfigurationError as e: - click.secho(f"Configuration error: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option( - "--config", - "-c", - type=click.Path(exists=True, path_type=Path), - help="Path to config file (default: sandbox.json)", -) -def init(config: Path): - """Initialize workspace by cloning the repository. - - \b - This command: - - Clones the configured repository - - Checks out the specified branch - - Sets up sparse checkout for allowed paths - - \b - Example: - git-sandbox init - git-sandbox init --config ./my-config.json - """ - cfg = _load_config(config) - ws = Workspace(cfg) - - if ws.exists(): - click.secho(f"Workspace already exists: {ws.root}", fg="yellow") - click.echo("Use 'git-sandbox reset --hard' to re-initialize from current config.") - return - - click.echo(f"Initializing workspace from {cfg.repo}...") - click.echo(f"Branch: {cfg.branch}") - - try: - base_commit = ws.init() - click.secho(f"Workspace initialized at {ws.root}", fg="green") - click.echo(f"Base commit: {base_commit[:8]}") - click.echo() - click.echo("Allowed paths:") - for p in cfg.allowed_paths: - click.echo(f" {p}") - click.echo() - click.echo("Allowed branches:") - for p in cfg.allowed_branches: - click.echo(f" {p}") - except GitSandboxError as e: - click.secho(f"Error: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option( - "--config", - "-c", - type=click.Path(exists=True, path_type=Path), - help="Path to config file (default: sandbox.json)", -) -def status(config: Path): - """Show workspace status with path validation. - - \b - Displays: - - Changed files (allowed vs denied) - - Current branch and base commit - - Whether changes can be committed - - \b - Example: - git-sandbox status - """ - cfg = _load_config(config) - ws = Workspace(cfg) - - if not ws.exists(): - click.secho(f"Workspace not found: {ws.root}", fg="red", err=True) - click.echo("Run 'git-sandbox init' first.") - sys.exit(1) - - try: - st = ws.status() - - click.echo(f"Branch: {st.current_branch}") - click.echo(f"Base: {st.base_commit} ({st.ahead_by} commits ahead)") - click.echo() - - if not st.changed_files: - click.echo("No changes") - return - - click.echo("Changed files:") - for f in st.allowed_files: - click.secho(f" + {f}", fg="green") - for f in st.denied_files: - click.secho(f" - {f} (outside allowed paths)", fg="red") - - click.echo() - if st.can_commit: - click.secho("Ready to commit", fg="green") - else: - if st.denied_files: - click.secho("Cannot commit: files outside allowed paths", fg="red") - click.echo("Revert denied files or update allowed_paths in config.") - - except GitSandboxError as e: - click.secho(f"Error: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option("-m", "--message", required=True, help="Commit message") -@click.option( - "--config", - "-c", - type=click.Path(exists=True, path_type=Path), - help="Path to config file (default: sandbox.json)", -) -def commit(message: str, config: Path): - """Validate paths and commit changes. - - \b - This command: - - Checks all changed files against allowed_paths - - Commits only if all files are allowed - - Fails if any file is outside allowed paths - - \b - Example: - git-sandbox commit -m "Update wizard component" - """ - cfg = _load_config(config) - ws = Workspace(cfg) - - if not ws.exists(): - click.secho(f"Workspace not found: {ws.root}", fg="red", err=True) - click.echo("Run 'git-sandbox init' first.") - sys.exit(1) - - try: - result = ws.commit(message) - - if result.success: - click.secho(f"Committed {result.files_committed} file(s)", fg="green") - click.echo(f"Commit: {result.commit_hash[:8]}") - else: - click.secho(result.message, fg="red", err=True) - - # Show denied files if any - st = ws.status() - if st.denied_files: - click.echo() - click.echo("Files outside allowed paths:") - for f in st.denied_files: - click.echo(f" {f}") - click.echo() - click.echo("Allowed paths:") - for p in cfg.allowed_paths: - click.echo(f" {p}") - - sys.exit(1) - - except GitSandboxError as e: - click.secho(f"Error: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.argument("branch") -@click.option( - "--config", - "-c", - type=click.Path(exists=True, path_type=Path), - help="Path to config file (default: sandbox.json)", -) -def push(branch: str, config: Path): - """Validate branch name and push to remote. - - \b - This command: - - Validates branch name against allowed_branches - - Creates the branch if needed - - Pushes to origin - - \b - Example: - git-sandbox push session-123 - git-sandbox push claude-feature-x - """ - cfg = _load_config(config) - ws = Workspace(cfg) - - if not ws.exists(): - click.secho(f"Workspace not found: {ws.root}", fg="red", err=True) - click.echo("Run 'git-sandbox init' first.") - sys.exit(1) - - try: - result = ws.push(branch) - - if result.success: - click.secho(f"Pushed to {result.branch}", fg="green") - else: - click.secho(result.message, fg="red", err=True) - click.echo() - click.echo("Allowed branch patterns:") - for p in cfg.allowed_branches: - click.echo(f" {p}") - sys.exit(1) - - except GitSandboxError as e: - click.secho(f"Error: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option("--hard", is_flag=True, help="Remove workspace and re-initialize from config") -@click.option( - "--config", - "-c", - type=click.Path(exists=True, path_type=Path), - help="Path to config file (default: sandbox.json)", -) -def reset(hard: bool, config: Path): - """Reset workspace to clean state. - - \b - Without --hard: Resets to origin branch, keeps changes unstaged - With --hard: Removes workspace and re-initializes from current sandbox.json - - \b - Example: - git-sandbox reset # Soft reset to origin branch - git-sandbox reset --hard # Complete re-initialization - """ - cfg = _load_config(config) - ws = Workspace(cfg) - - if not ws.exists(): - click.secho(f"Workspace not found: {ws.root}", fg="red", err=True) - click.echo("Run 'git-sandbox init' first.") - sys.exit(1) - - try: - base = ws.reset(hard=hard) - - if hard: - click.secho(f"Workspace re-initialized at {base[:8]}", fg="green") - click.echo("All changes discarded. Clean state restored from sandbox.json") - else: - click.secho(f"Soft reset to {base[:8]}", fg="green") - click.echo("Changes preserved as unstaged.") - - except GitSandboxError as e: - click.secho(f"Error: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -def example_config(): - """Print an example sandbox.json configuration.""" - example = """{ - "repo": "https://${GITHUB_TOKEN}@github.com/owner/repo.git", - "branch": "main", - "workspace": "./workspace", - "allowed_paths": [ - "blocks/form/**", - "scripts/**" - ], - "allowed_branches": [ - "session-*", - "claude-*" - ] -}""" - click.echo(example) - - -if __name__ == "__main__": - cli() diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/config.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/config.py deleted file mode 100644 index 11741925..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/config.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Configuration loading for git-sandbox.""" - -import json -import os -import re -from dataclasses import dataclass, field -from pathlib import Path -from typing import List, Optional - -from dotenv import find_dotenv, load_dotenv - -from .exceptions import ConfigurationError - - -@dataclass -class Config: - """Configuration for git-sandbox.""" - - repo: str - branch: str - allowed_paths: List[str] - allowed_branches: List[str] - workspace: Path = field(default_factory=lambda: Path("./workspace")) - - @classmethod - def load(cls, path: Path = None, env_file: Path = None) -> "Config": - """ - Load configuration from JSON file. - - Environment variables can be referenced in the config using: - - ${VAR_NAME} or $VAR_NAME syntax - - Args: - path: Path to config file (default: sandbox.json) - env_file: Path to .env file (default: auto-discover) - - Returns: - Config instance - - Raises: - ConfigurationError: If config file not found or invalid - """ - # Load environment variables - if env_file: - load_dotenv(env_file) - else: - # Look for .env in the user's current working directory - cwd_env_path = Path.cwd() / ".env" - if cwd_env_path.exists(): - load_dotenv(cwd_env_path) - else: - # Fallback: let python-dotenv search upward from cwd - load_dotenv(dotenv_path=find_dotenv(usecwd=True)) - - # Find config file - config_path = path or Path("sandbox.json") - if not config_path.exists(): - raise ConfigurationError( - f"Configuration file not found: {config_path}\n" - "Create a sandbox.json file with your configuration." - ) - - # Load and parse JSON - try: - with open(config_path, "r", encoding="utf-8") as f: - data = json.load(f) - except json.JSONDecodeError as e: - raise ConfigurationError(f"Invalid JSON in {config_path}: {e}") - - # Expand environment variables in all string values - data = cls._expand_env_vars(data) - - # Validate required fields - required = ["repo", "branch"] - missing = [f for f in required if f not in data or not data[f]] - if missing: - raise ConfigurationError( - f"Missing required configuration fields: {', '.join(missing)}" - ) - - # Build config with defaults - return cls( - repo=data["repo"], - branch=data["branch"], - allowed_paths=data.get("allowed_paths", ["**"]), - allowed_branches=data.get("allowed_branches", ["*"]), - workspace=Path(data.get("workspace", "./workspace")), - ) - - @classmethod - def _expand_env_vars(cls, obj): - """ - Recursively expand environment variables in strings. - - Supports ${VAR_NAME} and $VAR_NAME syntax. - """ - if isinstance(obj, str): - return cls._expand_string(obj) - elif isinstance(obj, dict): - return {k: cls._expand_env_vars(v) for k, v in obj.items()} - elif isinstance(obj, list): - return [cls._expand_env_vars(item) for item in obj] - else: - return obj - - @classmethod - def _expand_string(cls, s: str) -> str: - """Expand environment variables in a string.""" - # Match ${VAR_NAME} or $VAR_NAME (not followed by {) - pattern = r"\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)" - - def replace(match): - var_name = match.group(1) or match.group(2) - value = os.getenv(var_name) - if value is None: - # Keep original if env var not set - return match.group(0) - return value - - return re.sub(pattern, replace, s) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/exceptions.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/exceptions.py deleted file mode 100644 index 2663d46d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/exceptions.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Custom exceptions for git-sandbox.""" - - -class GitSandboxError(Exception): - """Base exception for all git-sandbox errors.""" - pass - - -class ConfigurationError(GitSandboxError): - """Raised when configuration is missing or invalid.""" - pass - - -class ValidationError(GitSandboxError): - """Raised when path or branch validation fails.""" - pass - - -class WorkspaceError(GitSandboxError): - """Raised when workspace operations fail.""" - pass diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/validator.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/validator.py deleted file mode 100644 index 572f904b..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/validator.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Path and branch validation for git-sandbox.""" - -import fnmatch -from typing import List, Tuple - - -def validate_paths(files: List[str], allowed_patterns: List[str]) -> Tuple[List[str], List[str]]: - """ - Validate file paths against allowed patterns. - - Args: - files: List of file paths to validate - allowed_patterns: List of glob patterns (fnmatch style) - - Returns: - Tuple of (allowed_files, denied_files) - - Examples: - >>> validate_paths(["src/foo.js", "secret.env"], ["src/**"]) - (["src/foo.js"], ["secret.env"]) - """ - allowed = [] - denied = [] - - for file_path in files: - if _matches_any_pattern(file_path, allowed_patterns): - allowed.append(file_path) - else: - denied.append(file_path) - - return allowed, denied - - -def validate_branch(branch: str, allowed_patterns: List[str]) -> bool: - """ - Validate branch name against allowed patterns. - - Args: - branch: Branch name to validate - allowed_patterns: List of glob patterns (fnmatch style) - - Returns: - True if branch matches any allowed pattern - - Examples: - >>> validate_branch("session-123", ["session-*", "claude-*"]) - True - >>> validate_branch("main", ["session-*"]) - False - """ - return _matches_any_pattern(branch, allowed_patterns) - - -def _matches_any_pattern(value: str, patterns: List[str]) -> bool: - """ - Check if value matches any of the given patterns. - - Supports fnmatch glob patterns: - - * matches anything except / - - ** matches anything including / - - ? matches any single character - - [seq] matches any character in seq - - [!seq] matches any character not in seq - """ - for pattern in patterns: - # Handle ** for recursive matching - if "**" in pattern: - # Convert ** to match any path - regex_pattern = pattern.replace("**", "__DOUBLE_STAR__") - regex_pattern = fnmatch.translate(regex_pattern) - regex_pattern = regex_pattern.replace("__DOUBLE_STAR__", ".*") - - import re - if re.match(regex_pattern, value): - return True - else: - if fnmatch.fnmatch(value, pattern): - return True - - return False diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/workspace.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/workspace.py deleted file mode 100644 index 96eee94e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts/git_sandbox/workspace.py +++ /dev/null @@ -1,326 +0,0 @@ -"""Workspace operations for git-sandbox.""" - -import subprocess -from dataclasses import dataclass -from pathlib import Path -from typing import Dict, List, Optional, Tuple - -from .config import Config -from .exceptions import WorkspaceError -from .validator import validate_branch, validate_paths - - -@dataclass -class WorkspaceStatus: - """Status of the workspace.""" - - changed_files: List[str] - allowed_files: List[str] - denied_files: List[str] - can_commit: bool - current_branch: str - base_commit: str - ahead_by: int - - -@dataclass -class CommitResult: - """Result of a commit operation.""" - - success: bool - message: str - commit_hash: Optional[str] = None - files_committed: int = 0 - - -@dataclass -class PushResult: - """Result of a push operation.""" - - success: bool - message: str - branch: Optional[str] = None - - -class Workspace: - """Manages a sandboxed git workspace.""" - - def __init__(self, config: Config): - """ - Initialize workspace manager. - - Args: - config: Configuration object - """ - self.config = config - self.root = config.workspace.resolve() - - def _git(self, *args, check: bool = True) -> subprocess.CompletedProcess: - """ - Run a git command in the workspace. - - Args: - *args: Git command arguments - check: Raise exception on non-zero exit - - Returns: - CompletedProcess result - """ - result = subprocess.run( - ["git", *args], - cwd=self.root, - capture_output=True, - text=True, - ) - - if check and result.returncode != 0: - raise WorkspaceError(f"Git command failed: git {' '.join(args)}\n{result.stderr}") - - return result - - def exists(self) -> bool: - """Check if workspace exists and is a git repo.""" - return self.root.exists() and (self.root / ".git").exists() - - def init(self) -> str: - """ - Initialize workspace by cloning only the allowed paths (sparse checkout). - - Returns: - Base commit hash - - Raises: - WorkspaceError: If workspace already exists or clone fails - """ - if self.root.exists(): - raise WorkspaceError(f"Workspace already exists: {self.root}") - - # Create workspace directory - self.root.mkdir(parents=True, exist_ok=True) - - try: - # Initialize empty git repo - subprocess.run( - ["git", "init"], - cwd=self.root, - capture_output=True, - text=True, - check=True, - ) - - # Add remote - subprocess.run( - ["git", "remote", "add", "origin", self.config.repo], - cwd=self.root, - capture_output=True, - text=True, - check=True, - ) - - # Enable sparse checkout - subprocess.run( - ["git", "config", "core.sparseCheckout", "true"], - cwd=self.root, - capture_output=True, - text=True, - check=True, - ) - - # Write allowed paths to sparse-checkout file - sparse_checkout_dir = self.root / ".git" / "info" - sparse_checkout_dir.mkdir(parents=True, exist_ok=True) - sparse_checkout_file = sparse_checkout_dir / "sparse-checkout" - sparse_checkout_file.write_text("\n".join(self.config.allowed_paths) + "\n") - - # Fetch the branch - subprocess.run( - ["git", "fetch", "--depth=1", "origin", self.config.branch], - cwd=self.root, - capture_output=True, - text=True, - check=True, - ) - - # Checkout the branch - subprocess.run( - ["git", "checkout", self.config.branch], - cwd=self.root, - capture_output=True, - text=True, - check=True, - ) - - except subprocess.CalledProcessError as e: - # Cleanup on failure - import shutil - if self.root.exists(): - shutil.rmtree(self.root) - raise WorkspaceError(f"Failed to initialize workspace:\n{e.stderr}") - - return self._get_current_commit() - - def _get_current_commit(self) -> str: - """Get current commit hash.""" - result = self._git("rev-parse", "HEAD") - return result.stdout.strip() - - def _get_current_branch(self) -> str: - """Get current branch name.""" - result = self._git("rev-parse", "--abbrev-ref", "HEAD") - return result.stdout.strip() - - def _get_base_ref(self) -> str: - """Get the origin branch ref as the base.""" - return f"origin/{self.config.branch}" - - def _get_changed_files(self) -> List[str]: - """Get list of all changed files (staged and unstaged).""" - # Get unstaged changes - unstaged = self._git("diff", "--name-only", check=False) - # Get staged changes - staged = self._git("diff", "--name-only", "--cached", check=False) - # Get untracked files - untracked = self._git("ls-files", "--others", "--exclude-standard", check=False) - - files = set() - for output in [unstaged.stdout, staged.stdout, untracked.stdout]: - for line in output.strip().split("\n"): - if line: - files.add(line) - - return sorted(files) - - def _get_commits_ahead(self) -> int: - """Get number of commits ahead of origin branch.""" - base = self._get_base_ref() - result = self._git("rev-list", "--count", f"{base}..HEAD", check=False) - try: - return int(result.stdout.strip()) - except ValueError: - return 0 - - def status(self) -> WorkspaceStatus: - """ - Get workspace status with validation information. - - Returns: - WorkspaceStatus with change details - """ - if not self.exists(): - raise WorkspaceError(f"Workspace not found: {self.root}") - - changed = self._get_changed_files() - allowed, denied = validate_paths(changed, self.config.allowed_paths) - - return WorkspaceStatus( - changed_files=changed, - allowed_files=allowed, - denied_files=denied, - can_commit=len(denied) == 0 and len(changed) > 0, - current_branch=self._get_current_branch(), - base_commit=self._get_base_ref(), - ahead_by=self._get_commits_ahead(), - ) - - def commit(self, message: str) -> CommitResult: - """ - Validate paths and commit changes. - - Args: - message: Commit message - - Returns: - CommitResult with operation details - """ - if not self.exists(): - raise WorkspaceError(f"Workspace not found: {self.root}") - - changed = self._get_changed_files() - - if not changed: - return CommitResult( - success=False, - message="Nothing to commit", - ) - - # Validate paths - allowed, denied = validate_paths(changed, self.config.allowed_paths) - - if denied: - return CommitResult( - success=False, - message=f"Cannot commit: {len(denied)} file(s) outside allowed paths", - ) - - # Stage all changes - self._git("add", "-A") - - # Commit - self._git("commit", "-m", message) - commit_hash = self._get_current_commit() - - return CommitResult( - success=True, - message="Changes committed successfully", - commit_hash=commit_hash, - files_committed=len(allowed), - ) - - def push(self, branch: str) -> PushResult: - """ - Validate branch name and push changes. - - Args: - branch: Branch name to push to - - Returns: - PushResult with operation details - """ - if not self.exists(): - raise WorkspaceError(f"Workspace not found: {self.root}") - - # Validate branch name - if not validate_branch(branch, self.config.allowed_branches): - patterns = ", ".join(self.config.allowed_branches) - return PushResult( - success=False, - message=f"Branch '{branch}' not allowed. Must match: {patterns}", - ) - - # Create/checkout branch - current = self._get_current_branch() - if current != branch: - self._git("checkout", "-B", branch) - - # Push - self._git("push", "-u", "origin", branch) - - return PushResult( - success=True, - message=f"Pushed to {branch}", - branch=branch, - ) - - def reset(self, hard: bool = False) -> str: - """ - Reset workspace by removing and re-initializing from current config. - - Args: - hard: If True, removes workspace and re-initializes. If False, just resets to origin branch. - - Returns: - Base commit hash after reset - """ - if not self.exists(): - raise WorkspaceError(f"Workspace not found: {self.root}") - - if hard: - # Remove workspace and re-initialize - import shutil - shutil.rmtree(self.root) - return self.init() - else: - # Soft reset: just reset to origin branch - base = self._get_base_ref() - self._git("reset", base) - return base diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/setup-workspace/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/setup-workspace/SKILL.md deleted file mode 100644 index b1accffb..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/setup-workspace/SKILL.md +++ /dev/null @@ -1,334 +0,0 @@ ---- -name: setup-workspace -description: > - Initializes the AEM Forms workspace directory structure, configures AEM and GitHub credentials, - verifies system requirements, and performs first-run setup. Creates .env with non-sensitive - values collected conversationally and directs users to paste tokens (AEM bearer, GitHub PAT) - directly into the .env file to avoid terminal escaping issues. - Triggers: setup, workspace, initialize, init, configure, credentials, .env, get started, - new project, first time, set up, create workspace, project setup, environment setup, - system requirements, install plugin. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.2" -allowed-tools: Read, Write, Edit, Bash ---- - -# Workspace Setup - -You help users set up and configure a new AEM Forms workspace through a guided, conversational flow — directory creation, credential collection, system checks, and first sync. - -> **Token handling:** Bearer tokens and PATs contain characters (`+`, `/`, `=`, etc.) that get mangled when pasted into terminal prompts. **Always** write placeholder lines in `.env` and ask the user to paste tokens directly into the file — never collect tokens through the conversation. - -## When to Use - -- User just installed the plugin and needs to set up a workspace -- User needs to configure AEM or GitHub credentials -- User asks "how do I get started?" or "what do I need to set up?" -- User wants to create a new project from scratch -- User needs to verify system requirements (Node.js, Python, git) -- User is troubleshooting credential or connectivity issues - -**Do NOT use for:** Building forms, adding rules, syncing code, or any task that assumes the workspace is already set up — use the appropriate skill instead. - -## Critical Rules - -1. **Ask for the workspace name first** — the very first thing you do is ask the user what they want to name their workspace -2. **Write `FORMS_WORKSPACE` to `.env` immediately after creating the directory** — this is the first line of `.env` and is how every CLI tool finds the workspace -3. **Collect non-sensitive values conversationally** — ask for URLs, paths, and repo names one at a time in the conversation -4. **Never collect tokens through the conversation** — for `AEM_TOKEN` and `GITHUB_TOKEN`, write a clearly marked placeholder line in `.env` and tell the user to open the file and paste the value directly. Terminal escaping corrupts tokens. -5. **Never hardcode credentials** — always write to `.env`; never commit `.env` to version control -6. **Verify system requirements** — confirm Node.js 18+ and Python 3.10+ are available -7. **Test credentials after collecting them** — use `eds-code-sync test` to verify AEM and GitHub connectivity -8. **Accept "skip"** — if the user doesn't have a value yet, write a placeholder comment and move on - -## Interactive Setup Flow - -Execute these steps in order. This is a conversation — wait for the user's response after each prompt. - -### Step 1: Ask for workspace name - -> "What would you like to name your workspace?" - -Accept any reasonable name (e.g. `personal-loan-form`, `my-project`, `acme-onboarding`). This becomes the directory name. - -### Step 2: Create workspace in cwd and write FORMS_WORKSPACE to .env - -Create the workspace directory **inside the current working directory** — the directory the user already has open in their editor / terminal. Do NOT ask the user where to put it; it always goes in cwd. - -``` -mkdir -p <name>/{repo,refs/apis,code/blocks/form/{scripts,api-clients,components},journeys,plans,.agent} -``` - -Then immediately write the absolute path into `<name>/.env` as the first entry: - -``` -# ── Workspace ──────────────────────────────────────────── -FORMS_WORKSPACE=<cwd>/<name> -``` - -Confirm to the user: -> "Created workspace at `<cwd>/<name>`. Now let's configure your credentials." - -**IMPORTANT:** `FORMS_WORKSPACE` must be the first entry in `.env`. Every CLI tool reads this value from `.env` to resolve the workspace directory. All subsequent credentials are appended below it in the same file. - -### Step 3: Collect credentials one by one - -Ask for each value individually. After the user provides a value, confirm it and move to the next. Follow this exact order: - -#### Required credentials - -Collect these in two passes: **conversational values** first, then **token placeholders**. - -**Pass 1 — Ask in conversation (safe to paste in terminal):** - -| # | Variable | What to ask | Help text | -|---|----------|-------------|-----------| -| 1 | `AEM_HOST` | "What is your AEM Author URL?" | Pattern: `https://author-pXXXX-eYYYY.adobeaemcloud.com`. Find it in Cloud Manager → Program → Environment → Author URL. | -| 2 | `GITHUB_URL` | "What is the full GitHub URL for your EDS repo?" | e.g. `https://github.com/owner/repo` | -| 3 | `GITHUB_REPO` | "What is the repo in `owner/repo` format?" | e.g. `adobe/my-eds-repo`. You can usually derive this from the URL they just gave. If obvious, auto-fill and confirm. | -| 4 | `AEM_WRITE_PATHS` | "Which AEM content paths should be writable? (comma-separated)" | e.g. `/content/forms/af/my-team` | - -**Pass 2 — Write placeholders, user pastes directly into `.env`:** - -| # | Variable | Placeholder written to `.env` | Instructions to give user | -|---|----------|-------------------------------|---------------------------| -| 5 | `AEM_TOKEN` | `AEM_TOKEN=<paste-your-bearer-token-here>` | "Open `.env` in your editor and replace `<paste-your-bearer-token-here>` with your AEM bearer token. Get it from Developer Console → Integrations → Local Token → Get Local Development Token. Tokens expire after 24h." | -| 6 | `GITHUB_TOKEN` | `GITHUB_TOKEN=<paste-your-github-pat-here>` | "In the same `.env` file, replace `<paste-your-github-pat-here>` with your GitHub personal access token (classic PAT with `repo` scope, starts with `ghp_`). Generate one at github.com/settings/tokens." | - -> **Why not paste tokens in the chat?** Bearer tokens and GitHub PATs contain special characters (`+`, `/`, `=`) that are silently corrupted by terminal escaping when pasted into a conversation prompt. Pasting directly into the `.env` file bypasses the terminal entirely and preserves the token exactly as-is. - -After writing the placeholders, tell the user: -> "I've written your `.env` file with placeholder lines for `AEM_TOKEN` and `GITHUB_TOKEN`. Please open `<workspace>/.env` in your editor and paste the actual values on those lines. Let me know when you're done and I'll test the connection." - -#### Optional credentials - -Offer these but don't require them. Provide a default: - -| Variable | Default | What to ask | -|----------|---------|-------------| -| `GITHUB_BRANCH` | `main` | "Which branch should I sync from? (default: main)" | -| `FORM_SYNC_ENV` | `prod` | "Which environment profile? local / stage / prod (default: prod)" | - -#### Handling "skip" or "I'll do it later" - -If the user says skip for any variable (including non-token values), write it as a commented placeholder: - -``` -# AEM_HOST=<your-aem-author-url> -``` - -And note to the user which values are still pending. Token placeholders are always written as uncommented lines with `<paste-...>` markers — the user replaces the marker with the real value. - -#### Handling alternative auth - -If the user says they use basic auth instead of a bearer token: -- Skip `AEM_TOKEN` -- Ask for `AEM_USERNAME` and `AEM_PASSWORD` instead - -### Step 4: Write `.env` - -Append all collected credentials to `<workspace>/.env` (below the `FORMS_WORKSPACE` line written in Step 2). For conversational values, write the actual collected value. For tokens, write the placeholder marker: - -``` -# ── Workspace ──────────────────────────────────────────── -FORMS_WORKSPACE=<absolute-path-to-workspace> - -# ── AEM Cloud Service ──────────────────────────────────── -AEM_HOST=<collected-value> -AEM_TOKEN=<paste-your-bearer-token-here> - -# ── GitHub EDS Repo ────────────────────────────────────── -GITHUB_URL=<collected-value> -GITHUB_REPO=<collected-value> -GITHUB_TOKEN=<paste-your-github-pat-here> -GITHUB_BRANCH=<collected-value> - -# ── Form Sync ──────────────────────────────────────────── -AEM_WRITE_PATHS=<collected-value> -FORM_SYNC_ENV=<collected-value> -``` - -After writing the file, tell the user to open it and paste their tokens: -> "I've saved your `.env` file. Two values need your attention — open `<workspace>/.env` in your editor and replace the placeholder markers for `AEM_TOKEN` and `GITHUB_TOKEN` with your actual tokens. Let me know when you're done." - -**Never echo secrets back** to the user. Do not read or print token values from `.env` after the user has pasted them. - -Wait for the user to confirm they've pasted the tokens before proceeding to Step 5. - -### Step 5: Verify system requirements - -Check that required tools are available: - -``` -node --version # must be v18+ -python3 --version # must be 3.10+ -git --version -``` - -If any are missing, tell the user exactly what to install and from where. - -### Step 6: Test connectivity - -Run from the workspace: - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync" test -``` - -This verifies both AEM and GitHub access. If it fails: -- Identify which credential is wrong from the error message -- If it's a **token** issue (401/403): tell the user to open `.env` and re-paste the token directly. Do NOT ask them to paste it in the conversation — terminal escaping will corrupt it. -- If it's a **non-token** issue (wrong URL, repo name, etc.): ask for the corrected value conversationally, update `.env` -- Re-test - -### Step 7: Sync EDS code - -Once connectivity is confirmed, pull the latest EDS form code from the GitHub repo into the workspace's `code/` directory: - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync" sync -``` - -This clones the repository configured in `GITHUB_REPO` and maps the relevant EDS form files (blocks, components, custom functions, API clients) into the local `code/` folder using the default file mapping. - -> **Important:** The `code/` directory is **not** part of the workspace's own git repository — it is synced from the EDS GitHub repo independently. Do not commit it with the workspace. Add `code/` to the workspace's `.gitignore` if the workspace is version-controlled. - -If the sync fails: -- Verify `GITHUB_REPO` and `GITHUB_TOKEN` are correct in `.env` -- Re-run `eds-code-sync test` to diagnose -- Check the file mapping with `eds-code-sync show-mapping` - -Confirm to the user: -> "Synced latest EDS code into `code/`. This folder mirrors your GitHub repo and will stay in sync via `eds-code-sync`." - -### Step 8: Confirm and hand off - -> "Your workspace is ready at `<path>`. What would you like to build?" - -## System Requirements - -| Requirement | Minimum | Why | -|-------------|---------|-----| -| Node.js | 18+ | Runs the form validator, rule transformer, and rule save tools | -| Python | 3.10+ | Runs form sync, API manager, and rule validation | -| `git` | on PATH | Used by `eds-code-sync` and `git-sandbox` for repo operations | - -> **Note:** The plugin bundles its own Python virtual environment and dependencies — you don't need to install any Python packages yourself. The first time the agent calls a Python-based tool, a venv is created automatically inside the plugin directory. - -## Workspace Directory Structure - -``` -<workspace-name>/ -├── .env # Credentials (AEM + GitHub) — never commit -├── metadata.json # Tracks synced forms (auto-managed by form-sync) -├── sandbox.json # Git sandbox config (repo URL, branch, allowed paths) -├── .agent/ # Agent memory — handover, history, session log -│ ├── handover.md -│ ├── history.md -│ └── sessions.md -├── repo/ -│ └── content/forms/af/ # Mirrors AEM content path — pulled forms land here -│ └── <team>/<app>/ -│ └── <form>/ -│ ├── <form>.form.json -│ └── <form>.rule.json -├── refs/ -│ ├── metadata.json # Fragment registry -│ ├── apis/ # OpenAPI 3.0 YAML specs and generated clients -│ └── <fragment>.form.json # Fragment content (read-only references) -├── code/ -│ └── blocks/form/ # EDS project code (synced from GitHub via git-sandbox) -│ ├── scripts/ # Custom functions (form-level, fragment, shared libs) -│ ├── api-clients/ # Deployed API client JS files -│ └── components/ # Custom component definitions -├── journeys/ -│ └── <journey>.md # Requirement docs & user stories (input) -└── plans/ - └── <journey>/ # Execution plans generated from journeys - ├── 01-form-structure.md - ├── 02-business-rules.md - └── ... -``` - -### What each directory is for - -| Directory | Purpose | -|-----------|---------| -| `repo/` | Mirrors AEM Author content structure; forms are pulled here under their AEM content path | -| `refs/` | Read-only references — fragments, API specs, and generated API clients (staging area) | -| `code/` | Mirrors your EDS GitHub repo; contains blocks, custom functions, API clients, and components | -| `journeys/` | Input requirement documents and user stories that describe what the form should do | -| `plans/` | Sequentially ordered execution plans generated by analyzing journeys | -| `.agent/` | Agent memory — handover state, history, and session log for continuity across sessions | - -## Workspace Resolution - -All CLI tools shipped with the plugin auto-resolve the workspace directory by reading `FORMS_WORKSPACE` from `.env`. This value is written during Step 2 of this setup flow. If the value is not found, tools fall back to the current working directory. - -**Resolution order (first match wins):** - -1. **`FORMS_WORKSPACE` already in environment** — e.g. exported by the caller -2. **`FORMS_WORKSPACE` read from `.env` in cwd** — written during this setup flow -3. **Fall back to cwd** — backwards-compatible default - -> **Key point:** `FORMS_WORKSPACE` must be the first entry in `.env`. This is how every tool — form-sync, api-manager, rule-save, scaffold-form, etc. — knows where to find the workspace and all its files. - -## Environment Variable Reference - -| Variable | Required | Description | -|----------|----------|-------------| -| `FORMS_WORKSPACE` | Yes (auto) | Absolute path to workspace root — first line of `.env`, written during setup, read by all tools | -| `AEM_HOST` | Yes | AEM Cloud Service Author URL | -| `AEM_TOKEN` | Yes* | Bearer token from AEM Developer Console | -| `AEM_USERNAME` | Yes* | Basic auth username (alternative to token) | -| `AEM_PASSWORD` | Yes* | Basic auth password (alternative to token) | -| `GITHUB_URL` | Yes | Full GitHub URL for the EDS repo | -| `AEM_WRITE_PATHS` | Yes | Comma-separated AEM paths allowed for push | -| `GITHUB_REPO` | Yes | Repository in `owner/repo` format | -| `GITHUB_TOKEN` | Yes | Classic personal access token with `repo` scope (starts with `ghp_`) | -| `GITHUB_BRANCH` | No | Branch to sync from (default: `main`) | -| `FORM_SYNC_ENV` | No | Environment profile — `local`, `stage`, or `prod` (default: `prod`) | -| `UE_SERVICE_URL` | No | Universal Editor Service URL | -| `UE_BEARER_TOKEN` | No | Universal Editor token (if static) | -| `FORM_SYNC_REPO_DIR` | No | Local directory for editable form files (default: `./repo`) | -| `FORM_SYNC_REFS_DIR` | No | Local directory for reference files (default: `./refs`) | -| `DEBUG` | No | Set to `true` to enable rule bridge debug output | - -*Either `AEM_TOKEN` or `AEM_USERNAME` + `AEM_PASSWORD` must be provided. - -## CLI Tools Reference - -| Tool | Location | Purpose | -|------|----------|---------| -| `form-sync` | `skills/sync-forms/scripts/` | Sync forms between AEM Author and local workspace | -| `eds-code-sync` | `skills/sync-eds-code/scripts/` | Sync EDS code between GitHub and local via git | -| `api-manager` | `scripts/` (shared) | Manage API definitions, generate typed JS clients | -| `form-validate` | `skills/create-form/scripts/` | Validate form.json against EDS field schemas | -| `cct` | `skills/create-component/scripts/` | Scaffold custom form components | -| `git-sandbox` | `skills/git-sandbox/scripts/` | Sandboxed git operations for AI agents | -| `scaffold-form` | `skills/scaffold-form/scripts/` | Scaffold empty form JSON from template | -| `rule-transform` | `scripts/` (shared) | Transform form JSON for rule editing | -| `rule-validate` | `scripts/` (shared) | Validate rule JSON against grammar | -| `rule-save` | `scripts/` (shared) | Save rules back to rule store | -| `rule-grammar` | `scripts/` (shared) | Print rule grammar reference | -| `parse-functions` | `scripts/` (shared) | Parse custom function JSDoc annotations | - -## Troubleshooting - -| Problem | Cause | Solution | -|---------|-------|----------| -| `node: command not found` | Node.js not installed | Install Node.js 18+ from [nodejs.org](https://nodejs.org) | -| `python3: command not found` | Python not installed | Install Python 3.10+ from [python.org](https://python.org) | -| `AEM_HOST not set` | Missing `.env` or missing variable | Re-run setup or manually add `AEM_HOST` to `.env` | -| Tool reads wrong `.env` | `FORMS_WORKSPACE` missing from `.env` | Add `FORMS_WORKSPACE=/absolute/path/to/workspace` as the first line of your workspace's `.env` | -| Tool writes files in wrong directory | `FORMS_WORKSPACE` missing from `.env` | Add `FORMS_WORKSPACE=/absolute/path/to/workspace` as the first line of your workspace's `.env` | -| `401 Unauthorized` from AEM | Token expired or invalid | Regenerate bearer token from AEM Developer Console | -| `403 Forbidden` on push | Path not in allowlist | Add the AEM path to `AEM_WRITE_PATHS` in `.env` | -| `eds-code-sync test` fails for GitHub | Bad token or wrong repo | Verify `GITHUB_TOKEN` has `repo` scope and `GITHUB_REPO` is correct | -| Python venv errors | Corrupted venv | Delete the venv directory inside the plugin and retry (it auto-recreates) | -| `sandbox.json` not found | Missing config | Create `sandbox.json` in workspace root — run `git-sandbox example-config` for a starter | -| Forms not appearing after pull | Wrong DAM path | Use `form-sync list <dam-path>` to discover correct paths first | -| `.env` committed to git | Security risk | Add `.env` to `.gitignore` immediately; rotate all exposed credentials | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/SKILL.md deleted file mode 100644 index 5d65b035..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/SKILL.md +++ /dev/null @@ -1,172 +0,0 @@ ---- -name: sync-eds-code -description: > - Syncs Edge Delivery Services (EDS) Forms front-end code between a GitHub repository - and a local workspace. Clones the repo, applies configurable file-mapping to extract - form-related source files into a local code/ directory, and can push changes back by - creating branches, committing, and optionally opening PRs. - Triggers: eds code sync, eds sync, sync code, push code, github sync, edge delivery code, - eds-code-sync, form components, form code, blocks/form. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# EDS Code Sync - -You synchronize Edge Delivery Services form code between a GitHub repository and the local workspace using the `eds-code-sync` CLI. - -## When to Use - -- Syncing EDS form code from a GitHub repo to local `code/` directory -- Pushing local code changes back to GitHub on a new branch -- Validating local code changes before pushing -- Opening a pull request for code changes -- Checking GitHub token validity and repo access -- Inspecting active file mapping rules - -## Critical Rules - -1. **Always use the `eds-code-sync` CLI** — do not manually clone or push to the repo -2. **Check GitHub credentials first** — `GITHUB_REPO` and `GITHUB_TOKEN` must be set in `.env` -3. **Sync before editing** — always `sync` first to get the latest code from the repo -4. **Push to branches** — never push directly to main; always use `push --branch <name>` -5. **Validate before pushing** — after editing files in `code/`, always run `eds-code-sync validate` to catch lint errors and dependency issues before pushing. The local `code/` directory does not contain `package.json` or lint configs — the validate command handles this by cloning the repo, applying your changes, and running `npm ci` + `npm run lint` automatically -6. **Preview with `--pr`** — use `push --branch <name> --pr` to auto-open a pull request -7. **Re-sync after PR merge** — after the user merges a PR, run `eds-code-sync sync` before starting any new work so the local `code/` directory reflects the latest main branch - -## Tool Commands - -| Action | Command | -|--------|---------| -| Sync repo to local | `eds-code-sync sync` | -| Validate local changes | `eds-code-sync validate` | -| Push to branch | `eds-code-sync push --branch <name>` | -| Push + open PR | `eds-code-sync push --branch <name> --pr` | -| Test GitHub access | `eds-code-sync test` | -| Show file mapping | `eds-code-sync show-mapping` | -| Delete remote branch | `eds-code-sync delete-branch --branch <name>` | -| Generate .env template | `eds-code-sync init` | - -## Workflow - -1. **Configure** — set `GITHUB_REPO` and `GITHUB_TOKEN` in `.env` -2. **Sync** — `eds-code-sync sync` to clone and map files to `./code` -3. **Edit** — modify files in `code/` directory -4. **Validate** — `eds-code-sync validate` to verify changes pass `npm ci` and `npm run lint` -5. **Push** — `eds-code-sync push --branch feature-name --pr` to push and open PR - -## Deploy & Resync Lifecycle - -When a plan or phase modifies EDS code (files in the `code/` directory), follow this lifecycle at plan completion: - -### 1. Validate the changes - -Before pushing, validate the EDS code using the CLI: - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync" validate --verbose -``` - -This clones the EDS repository, applies your local `code/` changes on top, runs `npm ci` and `npm run lint`, and reports any errors. - -If validation fails, fix the issues in the `code/` directory and re-run `validate` until it passes. - -> **Why validate?** The local `code/` directory only contains a mapped subset of the EDS repository — it has no `package.json`, no lint config, and no `node_modules`. You cannot run `npm install` or `npm run lint` directly in `code/`. The `validate` command handles this by working against the full cloned repo. This catches syntax errors, dependency issues, and style violations before they reach the PR. - -> **Note:** The `push` command also runs lint automatically, but validating first lets you catch and fix errors before committing. - -### 2. Push changes and open a PR - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync" push --branch <plan-name-or-feature> --pr -``` - -Use a descriptive branch name derived from the plan or feature (e.g., `plan-03-business-rules`, `add-prefill-logic`). - -### 3. Ask the user to review and merge - -> "I've pushed the code changes and opened a PR. Please review and merge it when ready. Let me know once it's merged so we can continue." - -Wait for the user to confirm the merge. Do not proceed to the next plan until the PR is merged. - -### 4. Re-sync before the next plan - -Once the user confirms the merge, re-sync the local `code/` directory: - -``` -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/eds-code-sync" sync -``` - -This pulls the merged main branch so the workspace reflects the latest state — including any review changes the user or reviewers may have made during the PR. - -> **Why re-sync?** The user or other reviewers may modify code during PR review. Re-syncing ensures the agent works with the actual merged code, not a stale local copy. - -## Lock-file Handling - -The `push` and `validate` commands use `npm ci` (not `npm install`) to install dependencies inside the temporary clone. `npm ci` installs exactly what is recorded in `package-lock.json` without modifying it, so the committed lock file is never altered by the tool. - -> **Tip:** If you still see CI lock-file errors, make sure the `package-lock.json` checked into the repo was generated with the same Node.js major version used by CI (check `.node-version` or the CI workflow file). - -## AEM PSI Check & PR Body - -AEM EDS repositories typically include an `aem-psi-check` CI gate that validates the pull-request description. It requires a **preview URL** in the PR body matching this pattern: - -``` -URL for testing: - -- https://<branch>--<repo>--<owner>.aem.page/ -``` - -**Automatic inclusion:** When you use `push --pr`, the tool now auto-generates the correct preview URL from the branch name, repository, and owner (all derived from `GITHUB_REPO` in `.env`) and includes it in the PR body. No manual editing is needed. - -If the check still fails, verify that: -- The branch name doesn't contain characters that break the URL (use lowercase alphanumeric and hyphens) -- The repository has AEM EDS preview enabled - -## Environment - -Create `.env` in project root: - -``` -GITHUB_REPO=owner/repo-name -GITHUB_TOKEN=ghp_xxxxxxxxxxxx -GITHUB_BRANCH=main -``` - -| Variable | Required | Description | -|----------|----------|-------------| -| `GITHUB_REPO` | Yes | GitHub repository (e.g., `owner/repo`) | -| `GITHUB_TOKEN` | Yes | GitHub PAT with `repo` scope | -| `GITHUB_BRANCH` | No | Branch to sync from (default: `main`) | - -## File Mapping - -The `sync` command maps EDS repo files to the local `code/` directory: - -| Repo Path | Local Path | -|-----------|------------| -| `blocks/form/form.js` | `code/forms.js` | -| `blocks/form/components/` | `code/components/` | -| `blocks/form/mappings.js` | `code/mappings.js` | -| `blocks/form/api-clients/` | `code/api-clients/` | - -Custom mappings can be provided via `--mapping` flag. - -> **Important:** Only the mapped files above are synced. The local `code/` directory does not contain `package.json`, lint configs, or other repo root files. Use `eds-code-sync validate` to run npm-based validations. - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Auth failure | Run `eds-code-sync test` to verify token and repo access | -| Stale code | Run `eds-code-sync sync` to pull latest | -| Lint errors before push | Run `eds-code-sync validate --verbose` to see detailed lint output, fix issues in `code/`, then re-validate | -| Branch already exists | Delete it first with `eds-code-sync delete-branch --branch <name>` | -| Wrong files synced | Check mapping with `eds-code-sync show-mapping` | -| CI fails with lock-file error | The tool uses `npm ci` which never modifies `package-lock.json`. If it still fails, ensure the lock file in the repo was generated with the same Node.js version as CI | -| aem-psi-check fails on PR | The `push --pr` command auto-includes the AEM preview URL. If you created the PR manually, add `URL for testing:\n\n- https://<branch>--<repo>--<owner>.aem.page/` to the PR body | -| Can't run npm in code/ | This is expected — `code/` has no `package.json`. Use `eds-code-sync validate` instead | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds-code-sync b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds-code-sync deleted file mode 100755 index 116620d6..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds-code-sync +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m eds_code_sync.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/__init__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/__init__.py deleted file mode 100644 index 895ebc81..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""EDS Code Sync - GitHub to local workspace sync tool.""" - -__version__ = "0.1.0" -__author__ = "Adobe" - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/cli.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/cli.py deleted file mode 100644 index d51dbcec..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/cli.py +++ /dev/null @@ -1,680 +0,0 @@ -"""CLI entry point for EDS Code Sync.""" - -import sys -from pathlib import Path - -import click - -from . import __version__ -from .config import Config -from .exceptions import EDSCodeSyncError -from .mapper import FileMapper -from .sync import sync_code - - -@click.group() -@click.version_option(version=__version__, prog_name="eds-code-sync") -def cli(): - """EDS Code Sync - Pull EDS Forms code from GitHub to local workspace. - - \b - Examples: - eds-code-sync sync - eds-code-sync sync --target ./my-code --verbose - """ - pass - - -@cli.command() -@click.option( - "--target", - "-t", - default=None, - help="Target directory for synced code (default: ./code)", -) -@click.option( - "--mapping", - "-m", - default=None, - type=click.Path(exists=True, path_type=Path), - help="Custom mapping configuration JSON file", -) -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def sync(target: str, mapping: Path, verbose: bool): - """Sync EDS Forms code from GitHub to local directory. - - \b - This command clones the GitHub repository and copies files - based on mapping rules to your local code/ directory. - - \b - Examples: - eds-code-sync sync - eds-code-sync sync --target ./sandbox/code - eds-code-sync sync --mapping ./my-mapping.json --verbose - """ - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env(target_dir=target) - - if verbose: - click.echo(f" Repository: {config.github_repo}") - click.echo(f" Branch: {config.github_branch}") - click.echo(f" Target: {config.target_dir}") - - # Load mapper - if mapping: - click.echo(f"Loading custom mapping from {mapping}") - mapper = FileMapper.from_file(mapping) - else: - mapper = FileMapper() - - # Show active mapping rules if verbose - if verbose: - click.echo() - click.secho("Active Mapping Rules:", fg="cyan", bold=True) - for repo_pattern, local_pattern in mapper.mapping.items(): - click.echo(f" {repo_pattern} → {local_pattern}") - click.echo() - - # Create progress callback - def on_progress(message: str) -> None: - if verbose: - click.echo(f" {message}") - - # Perform sync - click.echo("Syncing code from GitHub...") - synced, skipped = sync_code(config, mapper, on_progress if verbose else None) - - # Success output - click.echo(f"✓ Synced {synced} files to {config.target_dir}") - if skipped > 0: - click.echo(f"⚠️ Skipped {skipped} files due to errors") - - click.secho("SUCCESS: Code sync completed", fg="green") - - except EDSCodeSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", - fg="red", - err=True, - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -def test(): - """Test GitHub token and repository access. - - \b - This command verifies: - - Your GitHub token is valid - - You have access to the repository - - The repository exists and is accessible - - \b - Example: - eds-code-sync test - """ - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - - click.echo(f"Testing token: {config.github_token[:10]}...") - click.echo(f"Testing access to: {config.github_repo}") - click.echo() - - # Import here to avoid loading if not needed - from github import GithubException - - from .github_client import GitHubClient - - client = GitHubClient(config) - - # Test token by getting authenticated user - click.echo("Checking token validity...") - try: - user = client.github.get_user() - click.secho(f"✅ Token is valid!", fg="green") - click.echo(f" Authenticated as: {user.login}") - if user.name: - click.echo(f" Name: {user.name}") - click.echo() - except GithubException as e: - if e.status == 401: - click.secho(f"❌ Authentication failed!", fg="red", bold=True) - click.echo(f" Your token is invalid, expired, or revoked.") - click.echo() - click.echo("To fix this:") - click.echo(" 1. Go to: https://github.com/settings/tokens") - click.echo(" 2. Generate a new token (classic)") - click.echo(" 3. Select 'repo' scope") - click.echo(" 4. Update your .env file with the new token") - sys.exit(1) - else: - raise - - # Test repository access - click.echo(f"Testing repository access to {config.github_repo}...") - try: - repo = client.get_repo() - click.secho(f"✅ Repository access granted!", fg="green") - click.echo(f" Repo: {repo.full_name}") - if repo.description: - click.echo(f" Description: {repo.description}") - click.echo(f" Private: {repo.private}") - click.echo(f" Default branch: {repo.default_branch}") - click.echo() - except GithubException as e: - if e.status == 404: - click.secho(f"❌ Repository not found!", fg="red", bold=True) - click.echo( - f" Either the repository doesn't exist or you don't have access." - ) - click.echo() - click.echo("Possible issues:") - click.echo(f" • Repository name might be wrong: {config.github_repo}") - click.echo( - f" • Repository might be private and your token lacks access" - ) - click.echo( - f" • Token might not have 'repo' scope for private repositories" - ) - sys.exit(1) - elif e.status == 403: - click.secho(f"❌ Access forbidden!", fg="red", bold=True) - click.echo( - f" Your token doesn't have permission to access this repository." - ) - click.echo() - click.echo("To fix this:") - click.echo(" 1. Go to: https://github.com/settings/tokens") - click.echo( - " 2. Make sure your token has 'repo' scope (for private repos)" - ) - click.echo(" 3. Or use 'public_repo' scope (for public repos only)") - sys.exit(1) - else: - raise - - # Check rate limit - try: - rate_limit = client.github.get_rate_limit() - # Try different ways to access rate limit depending on PyGithub version - if hasattr(rate_limit, "core"): - remaining = rate_limit.core.remaining - limit = rate_limit.core.limit - elif hasattr(rate_limit, "rate"): - remaining = rate_limit.rate.remaining - limit = rate_limit.rate.limit - else: - remaining = "?" - limit = "?" - click.echo(f"Rate limit: {remaining}/{limit} requests remaining") - except Exception: - # Rate limit check is not critical, skip if it fails - click.echo("Rate limit: Unable to check (not critical)") - - click.echo() - click.secho( - "🎉 Everything looks good! You're ready to sync.", fg="green", bold=True - ) - - except EDSCodeSyncError as e: - click.secho(f"❌ ERROR: {e}", fg="red", err=True) - click.echo() - click.echo("Troubleshooting tips:") - click.echo(" 1. Check your token at: https://github.com/settings/tokens") - click.echo(" 2. Make sure the token has 'repo' scope") - click.echo(" 3. Verify the repository name is correct (owner/repo)") - sys.exit(1) - except Exception as e: - click.secho(f"❌ UNEXPECTED ERROR: {e}", fg="red", err=True) - click.echo() - click.echo("This might be a network issue or API problem.") - click.echo("Try again in a moment.") - sys.exit(1) - - -@cli.command() -@click.option( - "--mapping", - "-m", - default=None, - type=click.Path(exists=True, path_type=Path), - help="Show custom mapping from JSON file", -) -def show_mapping(mapping: Path): - """Show the active file mapping rules. - - \b - This displays which repository files will be synced - and where they will be saved locally. - - \b - Examples: - eds-code-sync show-mapping - eds-code-sync show-mapping --mapping ./custom.json - """ - try: - # Load mapper - if mapping: - click.echo(f"Loading custom mapping from {mapping}") - click.echo() - mapper = FileMapper.from_file(mapping) - mapping_source = f"Custom mapping from {mapping}" - else: - mapper = FileMapper() - mapping_source = "Default mapping (built-in)" - - click.secho(mapping_source, fg="cyan", bold=True) - click.echo() - - click.echo("File Mapping Rules:") - click.echo("─" * 60) - - for repo_pattern, local_pattern in mapper.mapping.items(): - click.echo(f" {repo_pattern}") - click.secho(f" → {local_pattern}", fg="green") - - click.echo("─" * 60) - click.echo() - - # Explain patterns - click.echo("Pattern Types:") - click.echo(" • Exact match: Syncs only the specified file") - click.echo(" • Directory (ends with /): Syncs matching files from directory") - click.echo() - - click.echo("Example Matches:") - click.echo(" scripts/form.js") - click.echo(f" → ./code/form.js") - click.echo(" blocks/text-input/text-input.js") - click.echo(f" → ./code/components/text-input.js") - click.echo() - - click.echo("To see actual files that will sync, run:") - click.secho(" eds-code-sync sync --dry-run", fg="yellow") - - except Exception as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option( - "--source", - "-s", - default="./code", - type=click.Path(exists=True, path_type=Path), - help="Source directory containing files to push (default: ./code)", -) -@click.option( - "--branch", - "-b", - required=True, - help="Name for the new branch (required)", -) -@click.option( - "--message", - "-m", - default=None, - help="Commit message (default: auto-generated)", -) -@click.option( - "--pr", - is_flag=True, - help="Create a pull request after pushing", -) -@click.option( - "--mapping", - default=None, - type=click.Path(exists=True, path_type=Path), - help="Custom mapping configuration JSON file", -) -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def push( - source: Path, branch: str, message: str, pr: bool, mapping: Path, verbose: bool -): - """Push local code changes to a new GitHub branch. - - \b - This command: - - Creates a new branch from main - - Pushes your local files to the new branch - - Optionally creates a pull request - - \b - Examples: - eds-code-sync push --branch feature/my-updates - eds-code-sync push -b fix/form-bug --pr - eds-code-sync push -b updates -m "Update components" --verbose - """ - try: - from .push import push_code - - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - - if verbose: - click.echo(f" Repository: {config.github_repo}") - click.echo(f" Base branch: {config.github_branch}") - click.echo(f" New branch: {branch}") - click.echo(f" Source directory: {source}") - - # Load mapper - if mapping: - click.echo(f"Loading custom mapping from {mapping}") - mapper = FileMapper.from_file(mapping) - else: - mapper = FileMapper() - - # Create progress callback - def on_progress(msg: str) -> None: - if verbose: - click.echo(f" {msg}") - - # Perform push - click.echo(f"Pushing code to new branch '{branch}'...") - branch_name, pushed, pr_url = push_code( - config=config, - source_dir=source, - branch_name=branch, - mapper=mapper, - commit_message=message, - create_pr=pr, - on_progress=on_progress if verbose else None, - ) - - # Success output - if pushed == 0: - click.echo(f"⚠ No changes to commit - branch '{branch_name}' is up to date") - click.secho("SUCCESS: Code is already up to date", fg="green") - else: - click.echo(f"✓ Pushed {pushed} files to branch '{branch_name}'") - - if pr_url: - click.echo(f"✓ Pull request created: {pr_url}") - else: - repo_url = f"https://github.com/{config.github_repo}" - click.echo(f"View branch: {repo_url}/tree/{branch_name}") - - click.secho("SUCCESS: Code pushed successfully", fg="green") - - except EDSCodeSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", - fg="red", - err=True, - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option( - "--source", - "-s", - default=None, - type=click.Path(exists=True, path_type=Path), - help="Source directory with local code (default: ./code)", -) -@click.option( - "--mapping", - "-m", - default=None, - type=click.Path(exists=True, path_type=Path), - help="Custom mapping configuration JSON file", -) -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def validate(source: Path, mapping: Path, verbose: bool): - """Validate local code changes against the EDS repository. - - \b - This command: - - Clones the GitHub repository - - Applies your local code changes - - Runs npm ci and npm run lint - - Reports any validation errors - - \b - Use this before pushing to catch lint errors early. - - \b - Examples: - eds-code-sync validate - eds-code-sync validate --verbose - eds-code-sync validate --source ./my-code - """ - try: - from .validate import validate_code - - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - - # Resolve source directory - if source: - config.target_dir = source - source_dir = config.target_dir - - if not source_dir.exists(): - click.secho( - f"ERROR: Source directory not found: {source_dir}", - fg="red", - err=True, - ) - sys.exit(1) - - if verbose: - click.echo(f" Repository: {config.github_repo}") - click.echo(f" Base branch: {config.github_branch}") - click.echo(f" Source directory: {source_dir}") - - # Load mapper - if mapping: - click.echo(f"Loading custom mapping from {mapping}") - mapper = FileMapper.from_file(mapping) - else: - mapper = FileMapper() - - # Create progress callback - def on_progress(msg: str) -> None: - if verbose: - click.echo(f" {msg}") - - # Perform validation - click.echo("Validating code...") - passed, message = validate_code( - config=config, - source_dir=source_dir, - mapper=mapper, - on_progress=on_progress if verbose else None, - ) - - if passed: - click.echo(f"✓ {message}") - click.secho("SUCCESS: Validation passed", fg="green") - else: - click.echo(f"✗ {message}") - click.secho("FAILED: Validation did not pass", fg="red", err=True) - sys.exit(1) - - except EDSCodeSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", - fg="red", - err=True, - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.option( - "--branch", - "-b", - required=True, - help="Name of the branch to delete (required)", -) -@click.option( - "--force", - "-f", - is_flag=True, - help="Force delete without confirmation", -) -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def delete_branch(branch: str, force: bool, verbose: bool): - """Delete a branch from the GitHub repository. - - \b - This command: - - Deletes the specified branch from GitHub - - Cannot delete the default/main branch (safety check) - - \b - Examples: - eds-code-sync delete-branch --branch session-abc123 - eds-code-sync delete-branch -b feature/old-branch --force - """ - try: - from github import GithubException - - from .github_client import GitHubClient - - # Load configuration - if verbose: - click.echo("Loading configuration...") - config = Config.from_env() - - if verbose: - click.echo(f" Repository: {config.github_repo}") - click.echo(f" Branch to delete: {branch}") - - # Initialize GitHub client - client = GitHubClient(config) - repo = client.get_repo() - - # Safety check: Don't allow deleting default branch - if branch == repo.default_branch or branch in ["main", "master"]: - click.secho( - f"❌ Cannot delete default/main branch: {branch}", fg="red", bold=True - ) - click.echo( - "This is a safety check to prevent accidental deletion of main branches." - ) - sys.exit(1) - - # Check if branch exists - try: - ref = repo.get_git_ref(f"heads/{branch}") - if verbose: - click.echo(f"✓ Found branch: {branch}") - except GithubException as e: - if e.status == 404: - click.secho(f"❌ Branch not found: {branch}", fg="red") - click.echo("The branch does not exist in the repository.") - sys.exit(1) - else: - raise - - # Confirm deletion unless --force - if not force: - click.echo() - click.echo(f"You are about to delete branch: {branch}") - click.echo(f"Repository: {config.github_repo}") - if not click.confirm("Are you sure you want to delete this branch?"): - click.echo("Operation cancelled.") - sys.exit(0) - - # Delete the branch - if verbose: - click.echo(f"Deleting branch '{branch}'...") - - try: - ref.delete() - click.secho(f"✓ Branch '{branch}' deleted successfully", fg="green") - - if verbose: - click.echo( - f"Branch URL was: https://github.com/{config.github_repo}/tree/{branch}" - ) - - except GithubException as e: - if e.status == 422: - click.secho( - f"❌ Cannot delete branch: {e.data.get('message', 'Unknown error')}", - fg="red", - ) - click.echo("The branch might be protected or the default branch.") - else: - raise - - except EDSCodeSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", - fg="red", - err=True, - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -def init(): - """Create a .env.example file in the current directory.""" - env_example = """# GitHub Repository Configuration -GITHUB_REPO=gahuja1991/aem-boilerplate-forms -GITHUB_TOKEN=ghp_your_token_here -GITHUB_BRANCH=main - -# Optional: Custom mapping configuration -# MAPPING_CONFIG=./custom-mapping.json -""" - - env_file = Path(".env.example") - if env_file.exists(): - click.echo(".env.example already exists") - return - - with open(env_file, "w") as f: - f.write(env_example) - - click.secho("✓ Created .env.example", fg="green") - click.echo("Copy it to .env and update with your credentials") - - -if __name__ == "__main__": - cli() diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/config.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/config.py deleted file mode 100644 index a0044709..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/config.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Configuration management for EDS Code Sync.""" - -import os -from dataclasses import dataclass -from pathlib import Path - -from dotenv import find_dotenv, load_dotenv - -from .exceptions import ConfigurationError - - -@dataclass -class Config: - """Configuration container for EDS Code Sync.""" - - github_repo: str - github_token: str - github_branch: str - target_dir: Path - - @classmethod - def from_env(cls, env_file: Path = None, target_dir: str = None) -> "Config": - """ - Load configuration from environment variables. - - Args: - env_file: Optional path to .env file. - target_dir: Target directory for synced code (defaults to ./code). - - Returns: - Config instance with loaded values. - - Raises: - ConfigurationError: If required environment variables are missing. - """ - # Load .env file if it exists - if env_file: - load_dotenv(env_file) - else: - # Look for .env in the user's current working directory - cwd_env_path = Path.cwd() / ".env" - if cwd_env_path.exists(): - load_dotenv(cwd_env_path) - else: - # Fallback: let python-dotenv search upward from cwd - load_dotenv(dotenv_path=find_dotenv(usecwd=True)) - - # Required environment variables - required_vars = { - "GITHUB_REPO": "GitHub repository (e.g., owner/repo)", - "GITHUB_TOKEN": "GitHub personal access token", - } - - # Check for missing variables - missing = [] - for var, description in required_vars.items(): - if not os.getenv(var): - missing.append(f" - {var}: {description}") - - if missing: - raise ConfigurationError( - "Missing required environment variables:\n" - + "\n".join(missing) - + "\n\nPlease set these in your .env file or environment." - ) - - # Optional branch (defaults to main) - branch = os.getenv("GITHUB_BRANCH", "main") - - # Target directory (defaults to ./code) - target = Path(target_dir) if target_dir else Path.cwd() / "code" - - return cls( - github_repo=os.getenv("GITHUB_REPO"), - github_token=os.getenv("GITHUB_TOKEN"), - github_branch=branch, - target_dir=target, - ) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/exceptions.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/exceptions.py deleted file mode 100644 index 6b57d986..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/exceptions.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Custom exceptions for EDS Code Sync.""" - - -class EDSCodeSyncError(Exception): - """Base exception for all eds-code-sync errors.""" - pass - - -class ConfigurationError(EDSCodeSyncError): - """Raised when required configuration is missing or invalid.""" - pass - - -class GitHubError(EDSCodeSyncError): - """Raised when GitHub API operations fail.""" - pass - - -class MappingError(EDSCodeSyncError): - """Raised when file mapping fails.""" - pass - - -class FileWriteError(EDSCodeSyncError): - """Raised when writing local files fails.""" - pass - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/git_ops.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/git_ops.py deleted file mode 100644 index 4f44bafd..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/git_ops.py +++ /dev/null @@ -1,217 +0,0 @@ -"""Git operations for EDS Code Sync.""" - -import shutil -import subprocess -from pathlib import Path -from typing import Callable, Optional - -from .config import Config -from .exceptions import GitHubError - - -class GitOperations: - """Handle git operations (clone, commit, push).""" - - def __init__(self, config: Config): - """ - Initialize git operations. - - Args: - config: Configuration with repo details. - """ - self.config = config - self.repo_url = self._build_repo_url() - - def _build_repo_url(self) -> str: - """Build the git repository URL with authentication.""" - # Format: https://TOKEN@github.com/owner/repo.git - return f"https://{self.config.github_token}@github.com/{self.config.github_repo}.git" - - def _run_git_command( - self, command: list, cwd: Optional[Path] = None, check: bool = True - ) -> subprocess.CompletedProcess: - """ - Run a git command. - - Args: - command: Command and arguments as list. - cwd: Working directory for the command. - check: Whether to raise exception on error. - - Returns: - CompletedProcess result. - - Raises: - GitHubError: If command fails and check=True. - """ - try: - result = subprocess.run( - command, cwd=cwd, capture_output=True, text=True, check=check - ) - return result - except subprocess.CalledProcessError as e: - raise GitHubError( - f"Git command failed: {' '.join(command)}\nError: {e.stderr}" - ) - - def clone_repo( - self, - target_dir: Path, - branch: Optional[str] = None, - on_progress: Optional[Callable[[str], None]] = None, - ) -> Path: - """ - Clone the repository to target directory. - - Args: - target_dir: Directory to clone into. - branch: Optional specific branch to clone. - on_progress: Progress callback. - - Returns: - Path to cloned repository. - - Raises: - GitHubError: If clone fails. - """ - if on_progress: - on_progress(f"Cloning {self.config.github_repo}...") - - # Remove target if it exists - if target_dir.exists(): - shutil.rmtree(target_dir) - - # Build clone command - cmd = ["git", "clone"] - if branch: - cmd.extend(["-b", branch]) - cmd.extend(["--depth", "1"]) # Shallow clone for speed - cmd.extend([self.repo_url, str(target_dir)]) - - self._run_git_command(cmd) - - if on_progress: - on_progress(f"✓ Repository cloned") - - return target_dir - - def create_branch( - self, repo_dir: Path, branch_name: str, base_branch: Optional[str] = None - ) -> None: - """ - Create a new branch in the repository. - - Args: - repo_dir: Repository directory. - branch_name: Name for new branch. - base_branch: Base branch to create from (default: current). - - Raises: - GitHubError: If branch creation fails. - """ - if base_branch: - self._run_git_command(["git", "checkout", base_branch], cwd=repo_dir) - - self._run_git_command(["git", "checkout", "-b", branch_name], cwd=repo_dir) - - def commit_changes( - self, - repo_dir: Path, - commit_message: str, - on_progress: Optional[Callable[[str], None]] = None, - ) -> bool: - """ - Stage and commit all changes. - - Args: - repo_dir: Repository directory. - commit_message: Commit message. - on_progress: Progress callback. - - Returns: - True if changes were committed, False if no changes. - - Raises: - GitHubError: If commit fails. - """ - # Stage all changes - self._run_git_command(["git", "add", "-A"], cwd=repo_dir) - - # Check if there are changes to commit - result = self._run_git_command( - ["git", "diff", "--cached", "--quiet"], cwd=repo_dir, check=False - ) - - if result.returncode == 0: - # No changes - return False - - # Commit changes - if on_progress: - on_progress("Creating commit...") - - self._run_git_command(["git", "commit", "-m", commit_message], cwd=repo_dir) - - if on_progress: - on_progress("✓ Changes committed") - - return True - - def push_branch( - self, - repo_dir: Path, - branch_name: str, - on_progress: Optional[Callable[[str], None]] = None, - ) -> None: - """ - Push branch to remote. - - Args: - repo_dir: Repository directory. - branch_name: Branch to push. - on_progress: Progress callback. - - Raises: - GitHubError: If push fails. - """ - if on_progress: - on_progress(f"Pushing branch {branch_name}...") - - self._run_git_command( - ["git", "push", "-u", "origin", branch_name], cwd=repo_dir - ) - - if on_progress: - on_progress(f"✓ Branch pushed") - - def get_repo_files(self, repo_dir: Path, base_path: str = "") -> list: - """ - Get list of files in repository. - - Args: - repo_dir: Repository directory. - base_path: Base path to list files from. - - Returns: - List of file paths relative to repo root. - """ - search_dir = repo_dir / base_path if base_path else repo_dir - files = [] - - for item in search_dir.rglob("*"): - if item.is_file() and ".git" not in item.parts: - # Get path relative to repo root - rel_path = item.relative_to(repo_dir) - files.append(str(rel_path)) - - return files - - def cleanup(self, repo_dir: Path) -> None: - """ - Clean up cloned repository. - - Args: - repo_dir: Repository directory to remove. - """ - if repo_dir.exists(): - shutil.rmtree(repo_dir) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/github_client.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/github_client.py deleted file mode 100644 index 3369a567..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/github_client.py +++ /dev/null @@ -1,120 +0,0 @@ -"""GitHub API client for EDS Code Sync (simplified - PR creation only).""" - -from typing import Optional -from github import Github, GithubException -from .config import Config -from .exceptions import GitHubError - - -class GitHubClient: - """Simplified client for GitHub API (PR creation only).""" - - def __init__(self, config: Config): - """ - Initialize the GitHub client. - - Args: - config: Configuration object with GitHub credentials. - """ - self.config = config - self.github = Github(config.github_token) - self._repo = None - - def get_repo(self): - """ - Get the GitHub repository object. - - Returns: - Repository object. - - Raises: - GitHubError: If repository cannot be accessed. - """ - if self._repo is None: - try: - self._repo = self.github.get_repo(self.config.github_repo) - except GithubException as e: - raise GitHubError( - f"Failed to access repository {self.config.github_repo}: {e}" - ) - return self._repo - - def create_pull_request( - self, - head_branch: str, - base_branch: str, - title: str, - body: str = "" - ) -> str: - """ - Create a pull request. - - Args: - head_branch: Source branch (your changes). - base_branch: Target branch (usually main). - title: PR title. - body: PR description. - - Returns: - URL of the created PR. - - Raises: - GitHubError: If PR creation fails. - """ - repo = self.get_repo() - - try: - pr = repo.create_pull( - title=title, - body=body, - head=head_branch, - base=base_branch - ) - return pr.html_url - except GithubException as e: - raise GitHubError(f"Failed to create PR: {e}") - - def delete_branch(self, branch_name: str) -> None: - """ - Delete a branch from the repository. - - Args: - branch_name: Name of the branch to delete. - - Raises: - GitHubError: If branch deletion fails. - """ - repo = self.get_repo() - - try: - # Get the reference - ref = repo.get_git_ref(f"heads/{branch_name}") - # Delete it - ref.delete() - except GithubException as e: - if e.status == 404: - raise GitHubError(f"Branch not found: {branch_name}") - elif e.status == 422: - raise GitHubError(f"Cannot delete branch (might be protected): {branch_name}") - else: - raise GitHubError(f"Failed to delete branch: {e}") - - def branch_exists(self, branch_name: str) -> bool: - """ - Check if a branch exists in the repository. - - Args: - branch_name: Name of the branch to check. - - Returns: - True if branch exists, False otherwise. - """ - repo = self.get_repo() - - try: - repo.get_git_ref(f"heads/{branch_name}") - return True - except GithubException as e: - if e.status == 404: - return False - raise GitHubError(f"Failed to check branch existence: {e}") diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/mapper.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/mapper.py deleted file mode 100644 index 9c738d56..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/mapper.py +++ /dev/null @@ -1,99 +0,0 @@ -"""File mapping logic for EDS Code Sync.""" - -from pathlib import Path -from typing import Dict, List, Tuple -import json - - -class FileMapper: - """Maps GitHub repository files to local directory structure.""" - - # Default mapping configuration - DEFAULT_MAPPING = { - "blocks/form/form.js": "forms.js", - "blocks/form/form.css": "forms.css", - "blocks/form/components/": "components/", - "blocks/form/mappings.js": "mappings.js", - "blocks/form/_form.json": "authoring/_form.json", - "models/_component-definition.json": "authoring/_component-definition.json", - "component-definition.json": "authoring/component-definition.json", - "component-filters.json": "authoring/component-filters.json", - "component-models.json": "authoring/component-models.json", - "blocks/form/functions.js" : "functions.js", - "blocks/form/models/form-components/" : "authoring/models/form-components/", - } - - def __init__(self, custom_mapping: Dict[str, str] = None): - """ - Initialize the file mapper. - - Args: - custom_mapping: Optional custom mapping configuration. - """ - self.mapping = custom_mapping or self.DEFAULT_MAPPING - - @classmethod - def from_file(cls, mapping_file: Path) -> "FileMapper": - """ - Load mapping from a JSON file. - - Args: - mapping_file: Path to mapping configuration JSON file. - - Returns: - FileMapper instance. - """ - with open(mapping_file, "r", encoding="utf-8") as f: - mapping = json.load(f) - return cls(custom_mapping=mapping) - - def map_path(self, repo_path: str) -> Tuple[bool, str]: - """ - Map a repository path to a local path. - - Args: - repo_path: Path in the repository. - - Returns: - Tuple of (should_sync, local_path). - should_sync is False if file should be ignored. - - Examples: - "blocks/form/form.js" -> (True, "forms.js") - "blocks/form/components/text-input.js" -> (True, "components/text-input.js") - "README.md" -> (False, "") - """ - for repo_pattern, local_pattern in self.mapping.items(): - # Exact file match - if repo_pattern == repo_path: - return True, local_pattern - - # Directory mapping (pattern ends with /) - if repo_pattern.endswith("/") and repo_path.startswith(repo_pattern): - # Extract the relative path after the pattern - relative = repo_path[len(repo_pattern):] - - # General directory mapping: preserve relative structure - # blocks/form/components/text-input.js -> components/text-input.js - local_path = f"{local_pattern}{relative}" - return True, local_path - - return False, "" - - def get_sync_plan(self, repo_files: List[str]) -> Dict[str, str]: - """ - Create a sync plan for a list of repository files. - - Args: - repo_files: List of file paths from repository. - - Returns: - Dictionary mapping repo_path -> local_path for files to sync. - """ - sync_plan = {} - for repo_path in repo_files: - should_sync, local_path = self.map_path(repo_path) - if should_sync: - sync_plan[repo_path] = local_path - return sync_plan - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/push.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/push.py deleted file mode 100644 index 38419ab1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/push.py +++ /dev/null @@ -1,290 +0,0 @@ -"""Push operation for EDS Code Sync (git-based).""" - -import shutil -import subprocess -import tempfile -from datetime import datetime -from pathlib import Path -from typing import Callable, List, Optional, Tuple - -from .config import Config -from .exceptions import GitHubError -from .git_ops import GitOperations -from .github_client import GitHubClient -from .mapper import FileMapper - - -def _run_npm_command( - command: list, cwd: Path, on_progress: Optional[Callable[[str], None]] = None -) -> None: - """ - Run an npm command in the specified directory. - - Args: - command: Command and arguments as list (e.g., ["npm", "install"]). - cwd: Working directory for the command. - on_progress: Optional progress callback. - - Raises: - GitHubError: If command fails. - """ - try: - if on_progress: - on_progress(f"Running: {' '.join(command)}") - - result = subprocess.run( - command, cwd=cwd, capture_output=True, text=True, check=True - ) - - if on_progress and result.stdout: - on_progress(result.stdout.strip()) - - except subprocess.CalledProcessError as e: - error_msg = f"Command failed: {' '.join(command)}\n" - if e.stderr: - error_msg += f"Error: {e.stderr}" - raise GitHubError(error_msg) - - -def push_code( - config: Config, - source_dir: Path, - branch_name: str, - mapper: FileMapper = None, - commit_message: Optional[str] = None, - create_pr: bool = False, - on_progress: Optional[Callable[[str], None]] = None, -) -> Tuple[str, int, Optional[str]]: - """ - Push local code changes to a new GitHub branch using git. - - Args: - config: Configuration object. - source_dir: Local directory containing files to push. - branch_name: Name for the new branch. - mapper: Optional file mapper for reverse mapping. - commit_message: Optional custom commit message. - create_pr: Whether to create a pull request. - on_progress: Optional progress callback. - - Returns: - Tuple of (branch_name, files_pushed, pr_url). - - Raises: - GitHubError: If push operation fails. - """ - - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Initialize - git_ops = GitOperations(config) - mapper = mapper or FileMapper() - - # Create temp directory for clone - temp_dir = Path(tempfile.mkdtemp(prefix="eds-push-")) - - try: - # Clone repository - log(f"Cloning {config.github_repo} (branch: {config.github_branch})") - repo_dir = git_ops.clone_repo( - target_dir=temp_dir / "repo", branch=config.github_branch, on_progress=log - ) - - # Install dependencies (npm ci never modifies package-lock.json) - log("Installing npm dependencies...") - _run_npm_command(["npm", "ci"], repo_dir, on_progress=log) - log("✓ Dependencies installed") - - # Create new branch - log(f"Creating branch '{branch_name}'...") - git_ops.create_branch(repo_dir, branch_name) - log(f"✓ Branch created") - - # Get local files to push - log(f"Scanning local directory: {source_dir}") - local_files = _scan_local_files(source_dir) - log(f"Found {len(local_files)} local files") - - # Create reverse mapping (local -> repo) - push_plan = _create_push_plan(local_files, source_dir, mapper) - log(f"Planning to push {len(push_plan)} files") - - if not push_plan: - raise GitHubError("No files to push. Check that files match mapping rules.") - - # Copy files to repository - pushed = 0 - for local_path, repo_path in push_plan.items(): - log(f"Copying {local_path.name} -> {repo_path}") - - # Destination in repo - dest_file = repo_dir / repo_path - dest_file.parent.mkdir(parents=True, exist_ok=True) - - # Copy file - shutil.copy2(local_path, dest_file) - pushed += 1 - - # Lint validation - log("Running npm lint...") - _run_npm_command(["npm", "run", "lint"], repo_dir, on_progress=log) - log("✓ Lint passed") - - # Build JSON files - log("Running npm build:json...") - _run_npm_command(["npm", "run", "build:json"], repo_dir, on_progress=log) - log("✓ JSON build complete") - - # Default commit message - if not commit_message: - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - commit_message = f"Update EDS Forms code - {timestamp}" - - # Commit changes - log("Committing changes...") - has_changes = git_ops.commit_changes( - repo_dir=repo_dir, commit_message=commit_message, on_progress=log - ) - - if not has_changes: - log("⚠ No changes to commit - branch is up to date") - log("Pushing branch to ensure it exists on GitHub...") - # Still push the branch even without changes to ensure it exists remotely - git_ops.push_branch( - repo_dir=repo_dir, branch_name=branch_name, on_progress=log - ) - log(f"✓ Branch '{branch_name}' created on GitHub") - return branch_name, 0, None - - # Push branch - git_ops.push_branch(repo_dir=repo_dir, branch_name=branch_name, on_progress=log) - - log(f"✓ Pushed {pushed} files to branch '{branch_name}'") - - # Create PR if requested - pr_url = None - if create_pr: - log("Creating pull request...") - client = GitHubClient(config) - - pr_title = f"EDS Forms Update - {branch_name}" - - # Build the AEM EDS preview URL. - # config.github_repo is "owner/repo"; the URL pattern is - # https://<branch>--<repo>--<owner>.aem.page/ - _owner, _repo = config.github_repo.split("/", 1) - safe_branch = branch_name.replace("/", "--") - preview_url = f"https://{safe_branch}--{_repo}--{_owner}.aem.page/" - - pr_body = f"""Automated push from local development. - -Files updated: {pushed} -Branch: {branch_name} -Base: {config.github_branch} - -URL for testing: - -- {preview_url} -""" - pr_url = client.create_pull_request( - head_branch=branch_name, - base_branch=config.github_branch, - title=pr_title, - body=pr_body, - ) - log(f"✓ Pull request created: {pr_url}") - - return branch_name, pushed, pr_url - - finally: - # Clean up temp directory - log("Cleaning up...") - git_ops.cleanup(temp_dir) - - -def _scan_local_files(source_dir: Path) -> List[Path]: - """Recursively scan local directory for files.""" - files = [] - for item in source_dir.rglob("*"): - if item.is_file() and not _should_ignore(item): - files.append(item) - return files - - -def _should_ignore(file_path: Path) -> bool: - """Check if file should be ignored.""" - ignore_patterns = { - ".DS_Store", - ".git", - "__pycache__", - "node_modules", - ".env", - ".env.local", - "*.pyc", - "*.log", - } - - name = file_path.name - for pattern in ignore_patterns: - if pattern.startswith("*.") and name.endswith(pattern[1:]): - return True - if pattern == name: - return True - if pattern in str(file_path): - return True - - return False - - -def _create_push_plan( - local_files: List[Path], source_dir: Path, mapper: FileMapper -) -> dict: - """ - Create push plan by reverse mapping local files to repo paths. - - Args: - local_files: List of local file paths. - source_dir: Base source directory. - mapper: File mapper with mapping rules. - - Returns: - Dict mapping local_path -> repo_path. - """ - push_plan = {} - - for local_file in local_files: - # Get relative path from source_dir - relative = local_file.relative_to(source_dir) - local_path_str = str(relative) - - # Reverse map: local -> repo - repo_path = _reverse_map(local_path_str, mapper) - if repo_path: - push_plan[local_file] = repo_path - - return push_plan - - -def _reverse_map(local_path: str, mapper: FileMapper) -> Optional[str]: - """ - Reverse map: convert local path to repository path. - - Examples: - "forms.js" -> "blocks/form/form.js" - "components/text-input.js" -> "blocks/form/components/text-input.js" - """ - # Check exact matches first - for repo_pattern, local_pattern in mapper.mapping.items(): - if local_pattern == local_path: - return repo_pattern - - # Check directory mappings - for repo_pattern, local_pattern in mapper.mapping.items(): - if local_pattern.endswith("/") and local_path.startswith(local_pattern): - # Remove local prefix, add repo prefix - relative = local_path[len(local_pattern) :] - return f"{repo_pattern}{relative}" - - return None diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/sync.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/sync.py deleted file mode 100644 index ef28b469..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/sync.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Sync operation for EDS Code Sync (git-based).""" - -import shutil -import tempfile -from pathlib import Path -from typing import Optional, Callable, Tuple -from .config import Config -from .git_ops import GitOperations -from .mapper import FileMapper -from .exceptions import GitHubError - - -def sync_code( - config: Config, - mapper: FileMapper = None, - on_progress: Optional[Callable[[str], None]] = None, -) -> Tuple[int, int]: - """ - Sync code from GitHub repository to local directory using git clone. - - Args: - config: Configuration object. - mapper: Optional custom file mapper. - on_progress: Optional progress callback. - - Returns: - Tuple of (files_synced, files_skipped). - - Raises: - GitHubError: If sync operation fails. - """ - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Initialize - git_ops = GitOperations(config) - mapper = mapper or FileMapper() - - # Create temp directory for clone - temp_dir = Path(tempfile.mkdtemp(prefix="eds-sync-")) - - try: - # Clone repository - log(f"Cloning {config.github_repo} (branch: {config.github_branch})") - repo_dir = git_ops.clone_repo( - target_dir=temp_dir / "repo", - branch=config.github_branch, - on_progress=log - ) - - # Get all files from repository - log("Scanning repository files...") - all_files = git_ops.get_repo_files(repo_dir) - log(f"Found {len(all_files)} files in repository") - - # Create sync plan - sync_plan = mapper.get_sync_plan(all_files) - log(f"Planning to sync {len(sync_plan)} files") - - # Ensure target directory exists - config.target_dir.mkdir(parents=True, exist_ok=True) - - # Sync files - synced = 0 - skipped = 0 - - for repo_path, local_path in sync_plan.items(): - try: - log(f"Syncing {repo_path} -> {local_path}") - - # Source file in cloned repo - source_file = repo_dir / repo_path - - if not source_file.exists(): - log(f" ⚠️ File not found: {repo_path}") - skipped += 1 - continue - - # Destination file - dest_file = config.target_dir / local_path - dest_file.parent.mkdir(parents=True, exist_ok=True) - - # Copy file - shutil.copy2(source_file, dest_file) - synced += 1 - - except Exception as e: - log(f" ⚠️ Failed to sync {repo_path}: {e}") - skipped += 1 - - return synced, skipped - - finally: - # Clean up temp directory - log("Cleaning up...") - git_ops.cleanup(temp_dir) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/validate.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/validate.py deleted file mode 100644 index d3a749b0..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts/eds_code_sync/validate.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Validate operation for EDS Code Sync.""" - -import shutil -import tempfile -from pathlib import Path -from typing import Callable, Optional, Tuple - -from .config import Config -from .exceptions import GitHubError -from .git_ops import GitOperations -from .mapper import FileMapper -from .push import _run_npm_command - - -def validate_code( - config: Config, - source_dir: Path, - mapper: FileMapper = None, - on_progress: Optional[Callable[[str], None]] = None, -) -> Tuple[bool, str]: - """ - Validate local code changes against the EDS repository. - - Clones the repo, applies local changes, runs npm ci and npm run lint - to verify that changes are valid before pushing. - - Args: - config: Configuration object. - source_dir: Local directory containing files to validate. - mapper: Optional file mapper for reverse mapping. - on_progress: Optional progress callback. - - Returns: - Tuple of (passed, message). - - Raises: - GitHubError: If validation operation fails. - """ - - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Initialize - git_ops = GitOperations(config) - mapper = mapper or FileMapper() - - # Create temp directory for clone - temp_dir = Path(tempfile.mkdtemp(prefix="eds-validate-")) - - try: - # Clone repository - log(f"Cloning {config.github_repo} (branch: {config.github_branch})") - repo_dir = git_ops.clone_repo( - target_dir=temp_dir / "repo", branch=config.github_branch, on_progress=log - ) - - # Install dependencies (npm ci never modifies package-lock.json) - log("Installing npm dependencies...") - _run_npm_command(["npm", "ci"], repo_dir, on_progress=log) - log("✓ Dependencies installed") - - # Apply local files to the cloned repo - log(f"Applying local changes from: {source_dir}") - from .push import _create_push_plan, _scan_local_files - - local_files = _scan_local_files(source_dir) - push_plan = _create_push_plan(local_files, source_dir, mapper) - log(f"Applying {len(push_plan)} files") - - if not push_plan: - return True, "No files to validate. Check that files match mapping rules." - - for local_path, repo_path in push_plan.items(): - dest_file = repo_dir / repo_path - dest_file.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(local_path, dest_file) - - # Run lint - log("Running npm run lint...") - try: - _run_npm_command(["npm", "run", "lint"], repo_dir, on_progress=log) - log("✓ Lint passed") - except GitHubError as e: - return False, f"Lint failed:\n{e}" - - return True, "All validations passed" - - finally: - # Clean up temp directory - log("Cleaning up...") - git_ops.cleanup(temp_dir) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/SKILL.md deleted file mode 100644 index e8634387..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/SKILL.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -name: sync-forms -description: > - Bidirectional sync for AEM Adaptive Forms between AEM Author and local workspace. - Pulls form JSON definitions from AEM, pushes local edits back via Universal Editor API, - and manages a metadata registry tracking local-to-remote mappings. Supports forms and - fragments, content path allowlisting, and multiple environments (local SDK, stage, prod). - Triggers: form sync, pull form, push form, sync form, create form on AEM, create fragment, - list forms, form-sync, adaptive form sync. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# Form Sync - -You synchronize AEM Adaptive Form definitions between an AEM Author instance and the local workspace using the `form-sync` CLI. - -## When to Use - -- Pulling a form or fragment from AEM Author to local files -- Pushing local form edits back to AEM -- Listing available forms in an AEM DAM folder -- Creating a new empty form or fragment on AEM -- Resetting a local form to a clean state - -## Critical Rules - -1. **Always use the `form-sync` CLI** — do not manually create or edit form sync metadata -2. **Check AEM credentials first** — `AEM_HOST` and `AEM_TOKEN` (or `AEM_USERNAME` + `AEM_PASSWORD`) must be set in `.env` -3. **Respect allowlisted paths** — `AEM_WRITE_PATHS` controls which AEM paths can be written to -4. **Pull before editing** — always pull the latest version before making changes -5. **Rules are separated** — `pull` splits rules/events into a companion `.rule.json` file with UUID references - -## Tool Commands - -| Action | Command | -|--------|---------| -| Pull form from AEM | `form-sync pull <form_path>` | -| Push form to AEM | `form-sync push <form_path>` | -| List forms in folder | `form-sync list <dam_path>` | -| List and pull all | `form-sync list <dam_path> --pull` | -| Clear local form | `form-sync clear <form_path>` | -| Create new form | `form-sync create <folder_path> <form_name>` | -| Create fragment | `form-sync create-fragment <folder_path> <name>` | - -## Workflow - -1. **Configure** — set `AEM_HOST`, `AEM_TOKEN`, `GITHUB_URL`, `AEM_WRITE_PATHS` in `.env` -2. **Pull** — `form-sync pull <path>` to fetch form JSON to `repo/` or `refs/` -3. **Edit** — modify the local `.form.json` and `.rule.json` files -4. **Push** — `form-sync push <path>` to send changes back to AEM - -## Environment - -Create `.env` in project root: - -``` -AEM_HOST=https://author.aem.example.com -AEM_TOKEN=your-bearer-token -GITHUB_URL=https://github.com/owner/repo -AEM_WRITE_PATHS=/content/dam/formsanddocuments/my-project -FORM_SYNC_ENV=prod -``` - -| Variable | Required | Description | -|----------|----------|-------------| -| `AEM_HOST` | Yes | AEM Author instance URL | -| `AEM_TOKEN` | Yes* | Bearer token for AEM auth | -| `AEM_USERNAME` | Yes* | Basic auth username (alternative to token) | -| `AEM_PASSWORD` | Yes* | Basic auth password (alternative to token) | -| `GITHUB_URL` | Yes | GitHub repository URL | -| `AEM_WRITE_PATHS` | Yes | Comma-separated allowlist of writable AEM paths | -| `FORM_SYNC_ENV` | No | Environment: `local`, `stage`, or `prod` (default: `prod`) | - -*Either `AEM_TOKEN` or `AEM_USERNAME`+`AEM_PASSWORD` must be provided. - -## File Structure - -``` -<workspace>/ -├── repo/ -│ └── content/forms/af/ # Mirrors AEM content path — forms pulled here -│ └── <team>/<path>/ -│ ├── <form-name>.form.json -│ └── <form-name>.rule.json -├── refs/ -│ ├── metadata.json # Fragment registry -│ ├── <fragment>.form.json # Fragment content -│ └── <fragment>.rule.json # Fragment rules -└── .env # AEM credentials -``` - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Auth failure | Check `AEM_HOST` and `AEM_TOKEN` in `.env` | -| Write denied | Ensure path is in `AEM_WRITE_PATHS` allowlist | -| Stale local form | Run `form-sync pull` to get latest from AEM | -| Push creates duplicate | Check `metadata.json` for correct path mapping | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form-sync b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form-sync deleted file mode 100755 index 84a08e34..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form-sync +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m form_sync.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/__init__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/__init__.py deleted file mode 100644 index 18524b92..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""AEM Form Sync CLI - Pull and push forms to Adobe Experience Manager.""" - -__version__ = "0.1.0" -__author__ = "Adobe" - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/auth.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/auth.py deleted file mode 100644 index 17ff0b96..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/auth.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Authentication management for AEM Form Sync.""" - -from dataclasses import dataclass -from typing import Optional - -from .client import AEMClient -from .config import Config -from .exceptions import TokenError - - -@dataclass -class CloudToken: - """Container for cloud token data.""" - - access_token: str - client_id: str - org_id: str - - -class AuthManager: - """Manages authentication for AEM APIs.""" - - def __init__(self, config: Config, client: AEMClient): - """ - Initialize the auth manager. - - Args: - config: Configuration object with credentials. - client: AEM HTTP client. - """ - self.config = config - self.client = client - self._cloud_token: Optional[CloudToken] = None - - def get_cloud_token(self) -> CloudToken: - """ - Get cloud token for Universal Editor API. - - Resolution order: - 1. If UE_BEARER_TOKEN is set, use it with client_id from env profile. - 2. Otherwise fetch from AEM's genai/token endpoint (stage/prod only). - - Returns: - CloudToken with access_token, client_id, and org_id. - - Raises: - TokenError: If token retrieval fails. - """ - if self._cloud_token is not None: - return self._cloud_token - - # Static bearer token from config (UE_BEARER_TOKEN env var) - if self.config.cloud_token_source == "static" or self.config.ue_bearer_token: - if not self.config.ue_bearer_token: - raise TokenError( - "Static cloud token source requires UE_BEARER_TOKEN.\n" - "Set UE_BEARER_TOKEN in your .env file." - ) - self._cloud_token = CloudToken( - access_token=self.config.ue_bearer_token, - client_id=self.config.client_id, - org_id="", - ) - return self._cloud_token - - # Fetch from AEM genai/token endpoint (stage/prod) - try: - headers = {"X-Adobe-Accept-Unsupported-API": "1"} - response = self.client.get("/adobe/forms/genai/token", headers=headers) - data = response.json() - - # Use client_id from response, but allow config override - fetched_client_id = data.get("clientId", "") - effective_client_id = self.config.client_id or fetched_client_id - - self._cloud_token = CloudToken( - access_token=data.get("accessToken", ""), - client_id=effective_client_id, - org_id=data.get("orgId", ""), - ) - - if not self._cloud_token.access_token: - raise TokenError("Received empty access token from AEM.") - - return self._cloud_token - - except Exception as e: - if isinstance(e, TokenError): - raise - raise TokenError(f"Failed to retrieve cloud token: {e}") - - def clear_token_cache(self) -> None: - """Clear the cached cloud token.""" - self._cloud_token = None diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/cli.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/cli.py deleted file mode 100644 index 5f9bdbe6..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/cli.py +++ /dev/null @@ -1,889 +0,0 @@ -"""CLI entry point for AEM Form Sync.""" - -import sys -from typing import Callable, Optional - -import click - -from . import __version__ -from .config import Config -from .exceptions import FormSyncError - -# Global verbose flag -_verbose = False - - -def log_verbose(message: str) -> None: - """Print message only if verbose mode is enabled.""" - if _verbose: - click.secho(f" [DEBUG] {message}", fg="cyan") - - -@click.group() -@click.version_option(version=__version__, prog_name="form-sync") -def cli(): - """AEM Form Sync - Pull and push forms to Adobe Experience Manager. - - \b - Examples: - form-sync pull /content/forms/af/myform - form-sync push /content/forms/af/myform - """ - pass - - -@cli.command() -@click.argument("form_path") -@click.option( - "--verbose", "-v", is_flag=True, help="Enable verbose output for debugging" -) -@click.option("--no-rules", is_flag=True, help="Skip rules extraction") -@click.option( - "--output", - "-o", - default=None, - help="Output directory (mutually exclusive with --no-edit)", -) -@click.option( - "--no-edit", is_flag=True, help="Sync to refs directory (read-only reference)" -) -def pull(form_path: str, verbose: bool, no_rules: bool, output: str, no_edit: bool): - """Pull a form from AEM to local filesystem. - - \b - FORM_PATH: Full AEM path to the form (e.g., /content/forms/af/myform) - - \b - By default, forms are synced to repo/ directory (editable). - Use --no-edit to sync to refs/ directory (read-only reference). - - \b - Examples: - form-sync pull /content/forms/af/acroform - form-sync pull /content/forms/af/acroform --no-edit - form-sync pull /content/forms/af/acroform --verbose - form-sync pull /content/forms/af/acroform --no-rules - form-sync pull /content/forms/af/acroform --output ./forms - """ - global _verbose - _verbose = verbose - - from pathlib import Path - - from .pull import pull_form - - # Validate mutual exclusion - if output and no_edit: - raise click.UsageError( - "Cannot use --output with --no-edit. Use one or the other." - ) - - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - log_verbose(f"AEM Host: {config.aem_host}") - - # Pull the form - click.echo(f"Fetching form from AEM: {form_path}") - log_verbose( - f"API URL: {config.aem_host}{form_path}/jcr:content/root/section/form.-1.json" - ) - if no_rules: - log_verbose("Skipping rules extraction") - if no_edit: - log_verbose("Syncing to refs directory (read-only)") - if output: - log_verbose(f"Output directory: {output}") - - output_dir = Path(output) if output else None - output_path, form_key = pull_form( - form_path, - config, - extract_rules=not no_rules, - output_dir=output_dir, - no_edit=no_edit, - ) - - # Success output - click.echo(f"✓ Saved to {output_path}") - click.echo(f"✓ Updated metadata.json (key: {form_key})") - click.secho("SUCCESS: Form pulled successfully", fg="green") - - except FormSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", fg="red", err=True - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command("list") -@click.argument("dam_path") -@click.option( - "--verbose", "-v", is_flag=True, help="Enable verbose output for debugging" -) -@click.option("--json", "as_json", is_flag=True, help="Output as JSON") -@click.option("--pull", "do_pull", is_flag=True, help="Pull all listed forms") -@click.option("--no-rules", is_flag=True, help="Skip rules extraction when pulling") -@click.option( - "--output", - "-o", - default=None, - help="Output directory for pulled forms (mutually exclusive with --no-edit)", -) -@click.option( - "--no-edit", - is_flag=True, - help="Sync pulled forms to refs directory (read-only reference)", -) -def list_forms( - dam_path: str, - verbose: bool, - as_json: bool, - do_pull: bool, - no_rules: bool, - output: str, - no_edit: bool, -): - """List forms in an AEM DAM folder. - - \b - DAM_PATH: AEM DAM path to list (e.g., /content/dam/formsanddocuments/myfolder) - - \b - Examples: - form-sync list /content/dam/formsanddocuments/form-coder/fragments - form-sync list /content/dam/formsanddocuments/form-coder/fragments --json - form-sync list /content/dam/formsanddocuments/form-coder/fragments --pull - form-sync list /content/dam/formsanddocuments/form-coder/fragments --pull --no-edit - form-sync list /content/dam/formsanddocuments/form-coder/fragments --pull --no-rules - form-sync list /content/dam/formsanddocuments/form-coder/fragments --pull --output ./forms - """ - global _verbose - _verbose = verbose - - import json - from pathlib import Path - - from .client import AEMClient - from .pull import pull_form - - # Validate mutual exclusion - if output and no_edit: - raise click.UsageError( - "Cannot use --output with --no-edit. Use one or the other." - ) - - def dam_to_content_path(dam_path: str) -> str: - """Convert DAM path to form content path.""" - if dam_path.startswith("/content/dam/formsanddocuments"): - return dam_path.replace( - "/content/dam/formsanddocuments", "/content/forms/af" - ) - return dam_path - - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - log_verbose(f"AEM Host: {config.aem_host}") - if no_edit: - log_verbose("Syncing to refs directory (read-only)") - if output: - log_verbose(f"Output directory: {output}") - - # Create client and fetch listing - client = AEMClient(config) - click.echo(f"Fetching forms from: {dam_path}") - log_verbose(f"API URL: {config.aem_host}{dam_path}.-1.json") - - response = client.get(f"{dam_path}.-1.json") - data = response.json() - - # Parse forms from response - forms = [] - for key, value in data.items(): - if key.startswith(("jcr:", "sling:", "rep:")): - continue - if isinstance(value, dict): - form_info = { - "name": key, - "damPath": f"{dam_path}/{key}", - "contentPath": dam_to_content_path(f"{dam_path}/{key}"), - } - # Extract title if available - if "jcr:content" in value and isinstance(value["jcr:content"], dict): - jcr_content = value["jcr:content"] - if "jcr:title" in jcr_content: - form_info["title"] = jcr_content["jcr:title"] - elif "jcr:title" in value: - form_info["title"] = value["jcr:title"] - forms.append(form_info) - - # Output results - if as_json: - click.echo(json.dumps(forms, indent=2)) - else: - click.echo(f"\nFound {len(forms)} form(s):\n") - for i, form in enumerate(forms, 1): - title = form.get("title", form["name"]) - click.echo(f" {i}. {title}") - click.echo(f" Content: {form['contentPath']}") - log_verbose(f"DAM: {form['damPath']}") - click.echo() - - # Pull forms if requested - if do_pull and forms: - output_dir = Path(output) if output else None - if output_dir: - click.echo(f"Pulling forms to: {output_dir}") - elif no_edit: - click.echo("Pulling forms to refs/ (read-only)...") - else: - click.echo("Pulling forms to repo/...") - success_count = 0 - for form in forms: - try: - output_path, form_key = pull_form( - form["contentPath"], - config, - extract_rules=not no_rules, - output_dir=output_dir, - no_edit=no_edit, - ) - click.echo(f" ✓ Pulled: {form['name']} → {output_path}") - success_count += 1 - except FormSyncError as e: - click.secho(f" ✗ Failed: {form['name']} - {e}", fg="red") - - click.echo(f"\nPulled {success_count}/{len(forms)} forms successfully.") - - click.secho("SUCCESS: List complete", fg="green") - - except FormSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", fg="red", err=True - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.argument("form_path") -@click.option( - "--source", - "-s", - default=None, - help="Source JSON file (default: {form_name}.form.json in current directory)", -) -@click.option( - "--suffix", - "-x", - default="-v1", - help="Suffix to append to form name when creating new form (default: -v1)", -) -@click.option( - "--new", - "force_new", - is_flag=True, - help="Force creation of new form even if one already exists", -) -@click.option( - "--preview", - is_flag=True, - help="Push to preview path defined by FORM_SYNC_PREVIEW_PATH env variable", -) -@click.option( - "--verbose", "-v", is_flag=True, help="Enable verbose output for debugging" -) -def push( - form_path: str, - source: str, - suffix: str, - force_new: bool, - preview: bool, - verbose: bool, -): - """Push a local form to AEM. - - \b - FORM_PATH: Full AEM path for the form (e.g., /content/forms/af/myform) - - \b - Examples: - form-sync push /content/forms/af/acroform - form-sync push /content/forms/af/acroform --source ./acroform.form.json - form-sync push /content/forms/af/acroform --suffix -v2 - form-sync push /content/forms/af/acroform --new - form-sync push /content/forms/af/acroform --preview - form-sync push /content/forms/af/acroform --verbose - - \b - Note: First push creates a new form with suffix. Subsequent pushes - update the existing form. Use --new to create a new form instead. - Use --preview to push to a separate preview path (requires FORM_SYNC_PREVIEW_PATH env). - """ - global _verbose - _verbose = verbose - - from .push import push_form - - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - log_verbose(f"AEM Host: {config.aem_host}") - - # Handle preview flag - preview_path = None - if preview: - if not config.preview_path: - click.secho( - "WARNING: --preview flag used but FORM_SYNC_PREVIEW_PATH environment variable is not set.\n" - "Please set FORM_SYNC_PREVIEW_PATH in your .env file to use preview mode.", - fg="yellow", - err=True, - ) - sys.exit(1) - preview_path = config.preview_path - # Normalize to DAM path format (accepts both forms and DAM paths) - if preview_path.startswith("/content/forms/af/"): - preview_path = preview_path.replace( - "/content/forms/af/", "/content/dam/formsanddocuments/" - ) - log_verbose(f"Converted forms path to DAM path: {preview_path}") - log_verbose(f"Preview path: {preview_path}") - - # Push the form - click.echo(f"Pushing form to AEM: {form_path}") - if source: - click.echo(f" Source file: {source}") - if force_new: - click.echo(f" Creating new form with suffix: {suffix}") - if preview_path: - click.echo(f" Preview mode: pushing to {preview_path}") - - # Create progress callback for verbose mode - def on_progress(message: str) -> None: - if verbose: - click.echo(f" {message}") - - target_path, is_new_form = push_form( - form_path, - config, - source, - suffix, - force_new, - on_progress if verbose else None, - preview_path=preview_path, - ) - - # Success output - if is_new_form: - click.echo(f"✓ Created new form: {target_path}") - else: - click.echo(f"✓ Updated existing form: {target_path}") - click.echo(f"✓ Updated metadata.json") - click.secho( - f"SUCCESS: Form pushed to {target_path}", - fg="green", - ) - - except FormSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", fg="red", err=True - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.argument("form_path") -@click.option( - "--verbose", "-v", is_flag=True, help="Enable verbose output for debugging" -) -def clear(form_path: str, verbose: bool): - """Clear a local form to empty state. - - \b - FORM_PATH: Full AEM path to the form (e.g., /content/forms/af/forms-team/demo) - - \b - This resets the form.json to a minimal empty form structure and - clears the rule.json file. Useful for starting fresh with a form. - - \b - Examples: - form-sync clear /content/forms/af/forms-team/demo - form-sync clear /content/forms/af/my-project/my-form --verbose - """ - global _verbose - _verbose = verbose - - import json - from pathlib import Path - - from .metadata import MetadataManager - - # Minimal form structure - EMPTY_FORM = { - "jcr:primaryType": "nt:unstructured", - "fieldType": "form", - "sling:resourceType": "fd/franklin/components/form/v1/form", - "fd:version": "2.1", - "dorType": "none", - "thankYouOption": "message", - } - - try: - # Load metadata and find form by path - click.echo("Loading metadata...") - metadata_manager = MetadataManager() - - # Search for form by original_path or current_path - form_key = None - form_metadata = None - for key in metadata_manager._data: - data = metadata_manager._data[key] - if isinstance(data, dict) and "originalPath" in data: - if ( - data.get("originalPath") == form_path - or data.get("currentPath") == form_path - ): - form_key = key - form_metadata = metadata_manager.get_form(key) - break - - if not form_metadata: - click.secho( - f"ERROR: Form with path '{form_path}' not found in metadata.json", - fg="red", - err=True, - ) - sys.exit(1) - - log_verbose(f"Form key: {form_key}") - log_verbose(f"Form location: {form_metadata.location}") - log_verbose(f"Local file: {form_metadata.local_file}") - if form_metadata.local_rule_file: - log_verbose(f"Rule file: {form_metadata.local_rule_file}") - - # Determine base directory - if form_metadata.location == "refs": - base_dir = Path("./refs") - else: - base_dir = Path("./repo") - - # Clear form.json (local_file already contains the relative path) - form_file = base_dir / form_metadata.local_file - if form_file.exists(): - click.echo(f"Clearing form: {form_file}") - with open(form_file, "w", encoding="utf-8") as f: - json.dump(EMPTY_FORM, f, indent=2) - click.echo(f"✓ Cleared {form_metadata.local_file}") - else: - click.secho(f"WARNING: Form file not found: {form_file}", fg="yellow") - - # Clear rule.json (local_rule_file already contains the relative path) - if form_metadata.local_rule_file: - rule_file = base_dir / form_metadata.local_rule_file - if rule_file.exists(): - click.echo(f"Clearing rules: {rule_file}") - with open(rule_file, "w", encoding="utf-8") as f: - json.dump({}, f, indent=2) - click.echo(f"✓ Cleared {form_metadata.local_rule_file}") - else: - log_verbose(f"Rule file not found: {rule_file}") - - click.secho(f"SUCCESS: Form '{form_path}' cleared", fg="green") - - except FormSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", fg="red", err=True - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command() -@click.argument("folder_path") -@click.argument("form_name") -@click.option( - "--verbose", "-v", is_flag=True, help="Enable verbose output for debugging" -) -def create(folder_path: str, form_name: str, verbose: bool): - """Create a new empty form on AEM. - - \b - FOLDER_PATH: AEM folder path where form will be created - (e.g., /content/forms/af/myproject) - FORM_NAME: Name for the new form (e.g., my-new-form) - - \b - Examples: - form-sync create /content/forms/af/forms-team my-form - form-sync create /content/forms/af/forms-team/subfolder contact-form - - \b - Note: The folder must be in your AEM_WRITE_PATHS. - If a form with the same name exists, a suffix (-1, -2, etc.) will be added. - """ - global _verbose - _verbose = verbose - - import time - - from .client import AEMClient - from .metadata import MetadataManager - from .pull import pull_form - from .push import ( - create_empty_form, - get_form_path_from_url, - update_edge_delivery_config, - ) - - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - log_verbose(f"AEM Host: {config.aem_host}") - - # Create client - client = AEMClient(config) - - # Validate folder path format - if not folder_path.startswith("/content/forms/af/"): - click.secho( - f"ERROR: Folder path must start with /content/forms/af/\n" - f"Got: {folder_path}", - fg="red", - err=True, - ) - sys.exit(1) - - # Check allowlist - click.echo(f"Checking allowlist for: {folder_path}") - client.check_path_allowed(folder_path) - log_verbose("Path is in allowlist") - - # Convert forms path to DAM path for listing - dam_path = folder_path.replace( - "/content/forms/af/", "/content/dam/formsanddocuments/" - ) - log_verbose(f"DAM path: {dam_path}") - - # List existing forms in the folder - click.echo(f"Checking existing forms in: {folder_path}") - try: - response = client.get(f"{dam_path}.-1.json") - data = response.json() - existing_forms = set() - for key, value in data.items(): - if not key.startswith(("jcr:", "sling:", "rep:")) and isinstance( - value, dict - ): - existing_forms.add(key) - log_verbose(f"Found {len(existing_forms)} existing form(s)") - except FormSyncError: - # Folder might not exist or be empty - existing_forms = set() - log_verbose("No existing forms found or folder is empty") - - # Check if form name exists and add suffix if needed - final_form_name = form_name - suffix_counter = 1 - while final_form_name in existing_forms: - final_form_name = f"{form_name}-{suffix_counter}" - suffix_counter += 1 - log_verbose(f"Name conflict, trying: {final_form_name}") - - if final_form_name != form_name: - click.echo(f"Form '{form_name}' already exists, using: {final_form_name}") - - # Create the form - click.echo(f"Creating form: {final_form_name}") - form_url = create_empty_form( - client=client, - config=config, - form_title=final_form_name, - folder_path=dam_path, - ) - - target_path = get_form_path_from_url(form_url) - - # Verify created form path is in allowlist - client.check_path_allowed(target_path) - click.echo(f"✓ Created new form: {target_path}") - - # Wait for form to be ready - click.echo("Waiting for form to be ready...") - time.sleep(3) - - # Pull the form to create local files and metadata - click.echo(f"Pulling form to create local files...") - output_path, form_key = pull_form( - target_path, config, extract_rules=True, override_form_key=final_form_name - ) - - # Set currentPath to the target_path so push updates this form instead of creating a new version - metadata_manager = MetadataManager() - metadata_manager.set_current_path(form_key, target_path) - - # Update Edge Delivery configuration with branch - def on_progress(message: str) -> None: - if verbose: - click.echo(f" {message}") - - click.echo("Updating Edge Delivery configuration...") - eds_result = update_edge_delivery_config( - client, config, target_path, on_progress if verbose else None - ) - if eds_result["success"]: - click.echo("✓ Edge Delivery configuration updated") - else: - click.secho( - f"⚠ Edge Delivery config update failed: {eds_result['message']}", - fg="yellow", - err=True, - ) - if eds_result.get("remediation"): - click.secho( - f" Remediation: {eds_result['remediation']}", fg="yellow", err=True - ) - click.secho( - " The form was created successfully, but its EDS cloud config needs to be fixed manually.", - fg="yellow", - err=True, - ) - - # Success output - click.echo(f"✓ Saved to {output_path}") - click.echo(f"✓ Updated metadata.json (key: {form_key})") - click.secho(f"SUCCESS: Form created and pulled to {output_path}", fg="green") - - except FormSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", fg="red", err=True - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -@cli.command("create-fragment") -@click.argument("folder_path") -@click.argument("fragment_name") -@click.option( - "--verbose", "-v", is_flag=True, help="Enable verbose output for debugging" -) -def create_fragment(folder_path: str, fragment_name: str, verbose: bool): - """Create a new empty fragment on AEM. - - \b - FOLDER_PATH: AEM folder path where fragment will be created - (e.g., /content/forms/af/myproject/fragments) - FRAGMENT_NAME: Name for the new fragment (e.g., my-new-fragment) - - \b - Examples: - form-sync create-fragment /content/forms/af/forms-team/fragments my-fragment - form-sync create-fragment /content/forms/af/forms-team/subfolder contact-panel - - \b - Note: The folder must be in your AEM_WRITE_PATHS. - If a fragment with the same name exists, a suffix (-1, -2, etc.) will be added. - """ - global _verbose - _verbose = verbose - - import time - - from .client import AEMClient - from .metadata import MetadataManager - from .pull import pull_form - from .push import create_empty_fragment, update_edge_delivery_config - - try: - # Load configuration - click.echo("Loading configuration...") - config = Config.from_env() - log_verbose(f"AEM Host: {config.aem_host}") - - # Create client - client = AEMClient(config) - - # Validate folder path format - if not folder_path.startswith("/content/forms/af/"): - click.secho( - f"ERROR: Folder path must start with /content/forms/af/\n" - f"Got: {folder_path}", - fg="red", - err=True, - ) - sys.exit(1) - - # Check allowlist - click.echo(f"Checking allowlist for: {folder_path}") - client.check_path_allowed(folder_path) - log_verbose("Path is in allowlist") - - # Convert forms path to DAM path for listing - dam_path = folder_path.replace( - "/content/forms/af/", "/content/dam/formsanddocuments/" - ) - log_verbose(f"DAM path: {dam_path}") - - # List existing fragments in the folder - click.echo(f"Checking existing fragments in: {folder_path}") - try: - response = client.get(f"{dam_path}.-1.json") - data = response.json() - existing_items = set() - # Handle both dict and list responses from AEM - if isinstance(data, dict): - for key, value in data.items(): - if not key.startswith(("jcr:", "sling:", "rep:")) and isinstance( - value, dict - ): - existing_items.add(key) - elif isinstance(data, list): - # List response - extract names from items - for item in data: - if isinstance(item, dict) and "name" in item: - existing_items.add(item["name"]) - log_verbose(f"Found {len(existing_items)} existing item(s)") - except FormSyncError: - # Folder might not exist or be empty - existing_items = set() - log_verbose("No existing items found or folder is empty") - - # Check if fragment name exists and add suffix if needed - final_fragment_name = fragment_name - suffix_counter = 1 - while final_fragment_name in existing_items: - final_fragment_name = f"{fragment_name}-{suffix_counter}" - suffix_counter += 1 - log_verbose(f"Name conflict, trying: {final_fragment_name}") - - if final_fragment_name != fragment_name: - click.echo( - f"Fragment '{fragment_name}' already exists, using: {final_fragment_name}" - ) - - # Create the fragment - click.echo(f"Creating fragment: {final_fragment_name}") - target_path = create_empty_fragment( - client=client, - config=config, - fragment_title=final_fragment_name, - fragment_name=final_fragment_name, - folder_path=dam_path, - ) - - # Verify created fragment path is in allowlist - client.check_path_allowed(target_path) - click.echo(f"✓ Created new fragment: {target_path}") - - # Wait for fragment to be ready - click.echo("Waiting for fragment to be ready...") - time.sleep(3) - - # Pull the fragment to create local files and metadata - click.echo(f"Pulling fragment to create local files...") - output_path, fragment_key = pull_form( - target_path, - config, - extract_rules=True, - override_form_key=final_fragment_name, - ) - - # Set currentPath to the target_path so push updates this fragment instead of creating a new version - metadata_manager = MetadataManager() - metadata_manager.set_current_path(fragment_key, target_path) - - # Update Edge Delivery configuration with branch - def on_progress(message: str) -> None: - if verbose: - click.echo(f" {message}") - - click.echo("Updating Edge Delivery configuration...") - eds_result = update_edge_delivery_config( - client, config, target_path, on_progress if verbose else None - ) - if eds_result["success"]: - click.echo("✓ Edge Delivery configuration updated") - else: - click.secho( - f"⚠ Edge Delivery config update failed: {eds_result['message']}", - fg="yellow", - err=True, - ) - if eds_result.get("remediation"): - click.secho( - f" Remediation: {eds_result['remediation']}", fg="yellow", err=True - ) - click.secho( - " The fragment was created successfully, but its EDS cloud config needs to be fixed manually.", - fg="yellow", - err=True, - ) - - # Success output - click.echo(f"✓ Saved to {output_path}") - click.echo(f"✓ Updated metadata.json (key: {fragment_key}, fragment: true)") - click.secho( - f"SUCCESS: Fragment created and pulled to {output_path}", fg="green" - ) - - except FormSyncError as e: - click.secho(f"ERROR: {e}", fg="red", err=True) - sys.exit(1) - except Exception as e: - if verbose: - import traceback - - click.secho( - f"UNEXPECTED ERROR: {e}\n{traceback.format_exc()}", fg="red", err=True - ) - else: - click.secho(f"UNEXPECTED ERROR: {e}", fg="red", err=True) - sys.exit(1) - - -if __name__ == "__main__": - cli() diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/client.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/client.py deleted file mode 100644 index a4d3e8a6..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/client.py +++ /dev/null @@ -1,148 +0,0 @@ -"""HTTP client wrapper for AEM APIs.""" - -from typing import Any - -import requests - -from .config import Config -from .exceptions import ( - AuthenticationError, - FormNotFoundError, - FormSyncError, - PathNotAllowedError, -) - - -class AEMClient: - """HTTP client for making requests to AEM.""" - - def __init__(self, config: Config): - """ - Initialize the AEM client. - - Args: - config: Configuration object with AEM credentials. - """ - self.config = config - self.session = requests.Session() - self.session.headers.update( - { - "Authorization": config.basic_auth_header, - "X-Adobe-Accept-Unsupported-API": "1", - } - ) - - def get(self, path: str, **kwargs) -> requests.Response: - """ - Make a GET request to AEM. - - Args: - path: URL path (will be appended to AEM host). - **kwargs: Additional arguments passed to requests.get(). - - Returns: - Response object. - - Raises: - AuthenticationError: If authentication fails (401/403). - FormNotFoundError: If resource not found (404). - FormSyncError: For other HTTP errors. - """ - url = f"{self.config.aem_host}{path}" - response = self.session.get(url, **kwargs) - self._handle_response_errors(response, path) - return response - - def post(self, path: str, json: dict = None, **kwargs) -> requests.Response: - """ - Make a POST request to AEM. - - Args: - path: URL path (will be appended to AEM host). - json: JSON payload to send. - **kwargs: Additional arguments passed to requests.post(). - - Returns: - Response object. - - Raises: - AuthenticationError: If authentication fails (401/403). - FormSyncError: For other HTTP errors. - """ - url = f"{self.config.aem_host}{path}" - response = self.session.post(url, json=json, **kwargs) - self._handle_response_errors(response, path) - return response - - def check_path_allowed(self, form_path: str) -> None: - """ - Check if a form path is in the push allowlist. - - Args: - form_path: The AEM form path to check. - - Raises: - PathNotAllowedError: If path is not allowed. - """ - if not self.config.push_allowlist: - raise PathNotAllowedError( - f"Push not allowed: AEM_WRITE_PATHS is empty.\n" - f"Please configure allowed paths in your .env file." - ) - if not self.config.is_path_allowed(form_path): - raise PathNotAllowedError( - f"Path '{form_path}' is not in the push allowlist.\n" - f"Allowed paths: {', '.join(self.config.push_allowlist)}" - ) - - def post_external( - self, url: str, json: dict = None, headers: dict = None, **kwargs - ) -> requests.Response: - """ - Make a POST request to an external URL (e.g., Universal Editor). - - Args: - url: Full URL to post to. - json: JSON payload to send. - headers: Custom headers (replaces session headers). - **kwargs: Additional arguments passed to requests.post(). - - Returns: - Response object. - - Raises: - FormSyncError: For HTTP errors. - """ - response = requests.post(url, json=json, headers=headers, **kwargs) - self._handle_response_errors(response, url) - return response - - def _handle_response_errors(self, response: requests.Response, path: str) -> None: - """ - Handle HTTP response errors. - - Args: - response: The HTTP response to check. - path: The path/URL that was requested (for error messages). - - Raises: - AuthenticationError: If authentication fails (401/403). - FormNotFoundError: If resource not found (404). - FormSyncError: For other HTTP errors. - """ - if response.status_code == 401: - raise AuthenticationError( - "Authentication failed. Your token may be expired or invalid.\n" - "Run forms-orchestrator/scripts/setup.sh to refresh credentials." - ) - elif response.status_code == 403: - raise AuthenticationError( - "Access forbidden. Your token may be expired or you lack permissions.\n" - "Run forms-orchestrator/scripts/setup.sh to refresh credentials." - ) - elif response.status_code == 404: - raise FormNotFoundError(f"Resource not found: {path}") - elif not response.ok: - raise FormSyncError( - f"HTTP {response.status_code} error for {path}: {response.text[:200]}" - ) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/components.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/components.py deleted file mode 100644 index 73996c7b..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/components.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Component extraction and transformation for AEM Form Sync.""" - -from typing import Any - - -# Keys to remove when transforming component for push -KEYS_TO_REMOVE = { - "jcr:lastModifiedBy", - "jcr:primaryType", - "jcr:createdBy", - "jcr:lastModified", - "jcr:created", - "sling:resourceType", # Used for resourceType, then removed from template -} - - -def extract_root_components(form_data: dict) -> list[tuple[str, dict]]: - """ - Extract root-level components from form JSON. - - A component is any key-value pair where the value is a dict. - - Args: - form_data: The form JSON data. - - Returns: - List of (component_key, component_data) tuples. - """ - return [(key, value) for key, value in form_data.items() if isinstance(value, dict)] - - -def get_component_resource_type(component_data: dict) -> str: - """ - Get the sling:resourceType from a component. - - Args: - component_data: The component data dict. - - Returns: - The resource type string, or empty string if not found. - """ - return component_data.get("sling:resourceType", "") - - -def get_component_field_type(component_data: dict) -> str: - """ - Get the fieldType from a component. - - Args: - component_data: The component data dict. - - Returns: - The field type string, or empty string if not found. - """ - return component_data.get("fieldType", "") - - -def get_component_name(component_data: dict) -> str: - """ - Get the name from a component. - - Args: - component_data: The component data dict. - - Returns: - The name string, or empty string if not found. - """ - return component_data.get("name", "") - - -def transform_component_for_push(component_key: str, component_data: dict) -> dict: - """ - Transform a pulled component into Universal Editor content format. - - The transformation: - - sling:resourceType becomes resourceType in xwalk.page - - Keys in KEYS_TO_REMOVE are excluded from template - - Everything else goes into template - - The component_key becomes the name - - Args: - component_key: The key of the component in the form JSON. - component_data: The component data dict. - - Returns: - Transformed content dict for Universal Editor /add API. - """ - # Extract resourceType - resource_type = component_data.get("sling:resourceType", "") - - # Build template (everything except removed keys) - template = {k: v for k, v in component_data.items() if k not in KEYS_TO_REMOVE} - - return { - "name": component_key, - "xwalk": { - "page": { - "resourceType": resource_type, - "template": template - } - } - } - - -def build_add_component_payload( - aem_host: str, - form_path: str, - component_key: str, - component_data: dict, -) -> dict: - """ - Build the full payload for Universal Editor /add API. - - Args: - aem_host: AEM host URL. - form_path: Path to the form (without .html). - component_key: The key of the component. - component_data: The component data dict. - - Returns: - Full payload dict for the /add API. - """ - content = transform_component_for_push(component_key, component_data) - - return { - "connections": [ - { - "name": "aemconnection", - "protocol": "xwalk", - "uri": aem_host - } - ], - "target": { - "container": { - "resource": f"urn:aemconnection:{form_path}/jcr:content/root/section/form", - "type": "container", - "prop": "" - } - }, - "content": content - } - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/config.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/config.py deleted file mode 100644 index 5caad4c8..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/config.py +++ /dev/null @@ -1,348 +0,0 @@ -"""Configuration management for AEM Form Sync.""" - -import base64 -import os -from dataclasses import dataclass, field -from enum import Enum -from pathlib import Path -from typing import List, Optional - -from dotenv import find_dotenv, load_dotenv - -from .exceptions import ConfigurationError - - -class Environment(Enum): - """Supported deployment environments.""" - - LOCAL = "local" - STAGE = "stage" - PROD = "prod" - - -# Environment profile defaults. -# Explicit .env values ALWAYS override these defaults. -ENV_PROFILES = { - Environment.LOCAL: { - "ue_service_url": "https://universal-editor-service-stage.adobe.io", - "client_id": "exc_app", - "cloud_token_source": "static", # requires UE_BEARER_TOKEN in .env - "create_form_strategy": "sling_import", # genai endpoint not available - "auth_mechanism": "basic", # expects AEM_USERNAME + AEM_PASSWORD - }, - Environment.STAGE: { - "ue_service_url": "https://universal-editor-service-stage.adobe.io", - "client_id": "", # fetched from AEM genai/token endpoint - "cloud_token_source": "aem_genai", - "create_form_strategy": "genai", - "auth_mechanism": "token", # expects AEM_TOKEN - }, - Environment.PROD: { - "ue_service_url": "https://universal-editor-service.adobe.io", - "client_id": "", # fetched from AEM genai/token endpoint - "cloud_token_source": "aem_genai", - "create_form_strategy": "genai", - "auth_mechanism": "token", # expects AEM_TOKEN - }, -} - - -@dataclass -class Config: - """Configuration container for AEM Form Sync.""" - - aem_host: str - github_url: str - env: Environment = Environment.STAGE - push_allowlist: List[str] = field(default_factory=list) - username: str = None - password: str = None - auth_token: str = None - repo_dir: Path = field(default_factory=lambda: Path("./repo")) - refs_dir: Path = field(default_factory=lambda: Path("./refs")) - preview_path: Optional[str] = None - github_branch: Optional[str] = None - ue_service_url: str = "https://universal-editor-service-stage.adobe.io" - ue_bearer_token: Optional[str] = None - client_id: str = "" - cloud_token_source: str = "aem_genai" - create_form_strategy: str = "genai" - - @property - def basic_auth_encoded(self) -> str: - """Return base64 encoded credentials for Basic Auth.""" - if not self.username or not self.password: - return None - credentials = f"{self.username}:{self.password}" - return base64.b64encode(credentials.encode()).decode() - - @property - def basic_auth_header(self) -> str: - """Return the Authorization header value. - - Uses AEM_TOKEN if provided, otherwise falls back to Basic Auth. - """ - if self.auth_token: - return f"Bearer {self.auth_token}" - return f"Basic {self.basic_auth_encoded}" - - @property - def github_owner(self) -> Optional[str]: - """Extract owner from github_url (e.g., 'my-org' from 'https://github.com/my-org/my-repo').""" - if not self.github_url: - return None - parts = self.github_url.rstrip("/").split("/") - if len(parts) >= 2: - return parts[-2] - return None - - @property - def github_repo(self) -> Optional[str]: - """Extract repo from github_url (e.g., 'my-repo' from 'https://github.com/my-org/my-repo').""" - if not self.github_url: - return None - parts = self.github_url.rstrip("/").split("/") - if len(parts) >= 1: - return parts[-1] - return None - - def is_path_allowed(self, path: str) -> bool: - """Check if a path is allowed for push operations. - - Args: - path: The AEM path to check. - - Returns: - True if the path starts with any of the allowed paths. - """ - if not self.push_allowlist: - return False - # Normalize path to prevent traversal attacks (e.g., /allowed/../not-allowed) - import posixpath - - normalized_path = posixpath.normpath(path) - return any( - normalized_path.startswith(allowed) for allowed in self.push_allowlist - ) - - def get_form_dir(self, form_path: str, no_edit: bool = False) -> Path: - """ - Build the local directory path for a form based on its AEM path. - - Args: - form_path: AEM form path (e.g., /content/forms/af/project/form) - no_edit: If True, use refs_dir; otherwise use repo_dir - - Returns: - Full local directory path (e.g., repo/content/forms/af/project/) - """ - base_dir = self.refs_dir if no_edit else self.repo_dir - # Strip leading slash from form_path and get parent directory - relative_path = form_path.lstrip("/") - parent_path = "/".join(relative_path.split("/")[:-1]) # Remove form name - return base_dir / parent_path - - @property - def is_local(self) -> bool: - """True when running against a local AEM SDK.""" - return self.env == Environment.LOCAL - - @property - def is_stage(self) -> bool: - """True when running against AEM Cloud stage.""" - return self.env == Environment.STAGE - - @property - def is_prod(self) -> bool: - """True when running against AEM Cloud prod.""" - return self.env == Environment.PROD - - @classmethod - def _parse_env(cls, raw: str) -> Environment: - """Parse FORM_SYNC_ENV string into Environment enum. - - Args: - raw: One of 'local', 'stage', 'prod' (case-insensitive). - - Returns: - Environment enum member. - - Raises: - ConfigurationError: If the value is not recognised. - """ - try: - return Environment(raw.strip().lower()) - except ValueError: - valid = ", ".join(e.value for e in Environment) - raise ConfigurationError( - f"Invalid FORM_SYNC_ENV value: '{raw}'.\nValid values: {valid}" - ) - - @classmethod - def from_env(cls, env_file: Path = None) -> "Config": - """ - Load configuration from environment variables. - - Environment profiles (FORM_SYNC_ENV) supply defaults. - Explicit .env values always override profile defaults. - - Args: - env_file: Optional path to .env file. If not provided, - looks for .env in current directory. - - Returns: - Config instance with loaded values. - - Raises: - ConfigurationError: If required environment variables are missing. - """ - # Load .env file if it exists - if env_file: - load_dotenv(env_file) - else: - # Look for .env in the user's current working directory - cwd_env_path = Path.cwd() / ".env" - if cwd_env_path.exists(): - load_dotenv(cwd_env_path) - else: - # Fallback: let python-dotenv search upward from cwd - load_dotenv(dotenv_path=find_dotenv(usecwd=True)) - - # ── Resolve environment profile ────────────────────────── - env = cls._parse_env(os.getenv("FORM_SYNC_ENV", "prod")) - profile = ENV_PROFILES[env] - - # Always required environment variables - required_vars = { - "AEM_HOST": "AEM Author URL (Cloud or local tunnel)", - "GITHUB_URL": "GitHub URL for form template", - "AEM_WRITE_PATHS": "Comma-separated list of allowed push paths", - } - - # Check for missing required variables - missing = [] - for var, description in required_vars.items(): - if not os.getenv(var): - missing.append(f" - {var}: {description}") - - if missing: - raise ConfigurationError( - "Missing required environment variables:\n" - + "\n".join(missing) - + "\n\nPlease set these in your .env file or environment." - ) - - # ── Authentication ────────────────────────────────────── - auth_token = os.getenv("AEM_TOKEN") - username = os.getenv("AEM_USERNAME") - password = os.getenv("AEM_PASSWORD") - - has_token = bool(auth_token) - has_credentials = bool(username and password) - - if profile["auth_mechanism"] == "basic": - # Local mode: Basic Auth required - if not has_credentials: - raise ConfigurationError( - f"FORM_SYNC_ENV={env.value} requires Basic Auth.\n" - "Please provide AEM_USERNAME and AEM_PASSWORD in your .env file." - ) - elif profile["auth_mechanism"] == "token": - # Stage/Prod mode: prefer token, allow credentials as fallback - if not has_token and not has_credentials: - raise ConfigurationError( - f"FORM_SYNC_ENV={env.value} requires authentication.\n" - "Please provide one of the following:\n" - " - AEM_TOKEN: Bearer token for AEM authentication\n" - " OR\n" - " - AEM_USERNAME and AEM_PASSWORD: Basic auth credentials\n" - "\nSet these in your .env file or environment." - ) - else: - # Fallback: any auth - if not has_token and not has_credentials: - raise ConfigurationError( - "Missing authentication credentials.\n" - "Please provide one of the following:\n" - " - AEM_TOKEN: Bearer token for AEM authentication\n" - " OR\n" - " - AEM_USERNAME and AEM_PASSWORD: Basic auth credentials\n" - "\nSet these in your .env file or environment." - ) - - # Local mode with static cloud token source requires UE_BEARER_TOKEN - ue_bearer_token = os.getenv("UE_BEARER_TOKEN") - if profile["cloud_token_source"] == "static" and not ue_bearer_token: - raise ConfigurationError( - f"FORM_SYNC_ENV={env.value} requires UE_BEARER_TOKEN.\n" - "The local AEM SDK does not have the genai/token endpoint.\n" - "Please set UE_BEARER_TOKEN in your .env file." - ) - - # Strip trailing slash from host if present - aem_host = os.getenv("AEM_HOST").rstrip("/") - - # Parse push allowlist - allowlist_str = os.getenv("AEM_WRITE_PATHS", "") - push_allowlist = [p.strip() for p in allowlist_str.split(",") if p.strip()] - - # Parse optional directory paths - repo_dir = Path(os.getenv("FORM_SYNC_REPO_DIR", "./repo")) - refs_dir = Path(os.getenv("FORM_SYNC_REFS_DIR", "./refs")) - - # Parse optional preview path - preview_path = os.getenv("FORM_SYNC_PREVIEW_PATH") - - # Parse optional GitHub branch for Edge Delivery config - github_branch = os.getenv("GITHUB_BRANCH") - - # ── UE configuration (explicit .env overrides profile defaults) ── - ue_service_url = os.getenv("UE_SERVICE_URL", profile["ue_service_url"]).rstrip( - "/" - ) - - # client_id: explicit .env override, then profile default - client_id = os.getenv("FORM_SYNC_CLIENT_ID", profile["client_id"]) - - return cls( - aem_host=aem_host, - github_url=os.getenv("GITHUB_URL"), - env=env, - push_allowlist=push_allowlist, - username=username, - password=password, - auth_token=auth_token, - repo_dir=repo_dir, - refs_dir=refs_dir, - preview_path=preview_path, - github_branch=github_branch, - ue_service_url=ue_service_url, - ue_bearer_token=ue_bearer_token, - client_id=client_id, - cloud_token_source=profile["cloud_token_source"], - create_form_strategy=profile["create_form_strategy"], - ) - - -# Metadata file name -METADATA_FILE = "metadata.json" - - -def get_working_dir() -> Path: - """ - Get the current working directory where forms will be saved. - - Returns: - Path to current working directory. - """ - return Path.cwd() - - -def get_metadata_path() -> Path: - """ - Get the path to the metadata.json file. - - Returns: - Path to metadata.json in current working directory. - """ - return get_working_dir() / METADATA_FILE diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/exceptions.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/exceptions.py deleted file mode 100644 index e1cf531e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/exceptions.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Custom exceptions for AEM Form Sync.""" - - -class FormSyncError(Exception): - """Base exception for all form-sync errors.""" - - pass - - -class ConfigurationError(FormSyncError): - """Raised when required configuration is missing or invalid.""" - - pass - - -class AuthenticationError(FormSyncError): - """Raised when authentication with AEM fails.""" - - pass - - -class FormNotFoundError(FormSyncError): - """Raised when a form cannot be found at the specified path.""" - - pass - - -class FormCreationError(FormSyncError): - """Raised when form creation on AEM fails.""" - - pass - - -class ComponentAddError(FormSyncError): - """Raised when adding a component to a form fails.""" - - def __init__(self, message: str, component_name: str = None, form_path: str = None): - super().__init__(message) - self.component_name = component_name - self.form_path = form_path - - -class TokenError(FormSyncError): - """Raised when cloud token retrieval fails.""" - - pass - - -class VersionFileError(FormSyncError): - """Raised when there's an issue with the version file.""" - - pass - - -class PathNotAllowedError(FormSyncError): - """Raised when a path is not in the push allowlist.""" - - pass - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/metadata.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/metadata.py deleted file mode 100644 index 187a550e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/metadata.py +++ /dev/null @@ -1,235 +0,0 @@ -"""Metadata file management for AEM Form Sync.""" - -import json -from datetime import datetime, timezone -from pathlib import Path -from typing import Optional - -from .config import METADATA_FILE, get_metadata_path, get_working_dir -from .exceptions import VersionFileError - - -class FormMetadata: - """Represents metadata for a single form or fragment.""" - - def __init__( - self, - folder_path: str, - original_path: str, - local_file: str, - current_path: str = None, - local_rule_file: str = None, - location: str = "repo", - fragment: bool = False, - ): - self.folder_path = folder_path - self.original_path = original_path - self.local_file = local_file - self.current_path = current_path - self.local_rule_file = local_rule_file - self.location = location # "repo" or "refs" - self.fragment = fragment # True if this is a fragment - - def to_dict(self) -> dict: - """Convert to dictionary for JSON serialization.""" - result = { - "folderPath": self.folder_path, - "originalPath": self.original_path, - "localFile": self.local_file, - "location": self.location, - } - if self.current_path: - result["currentPath"] = self.current_path - if self.local_rule_file: - result["localRuleFile"] = self.local_rule_file - # Only include fragment key if it's a fragment (backward compatibility) - if self.fragment: - result["fragment"] = True - return result - - @classmethod - def from_dict(cls, data: dict) -> "FormMetadata": - """Create from dictionary.""" - return cls( - folder_path=data.get("folderPath", ""), - original_path=data.get("originalPath", ""), - local_file=data.get("localFile", ""), - current_path=data.get("currentPath"), - local_rule_file=data.get("localRuleFile"), - location=data.get("location", "repo"), - fragment=data.get("fragment", False), - ) - - -class MetadataManager: - """Manages the centralized metadata.json file.""" - - def __init__(self, metadata_dir: Optional[Path] = None): - """ - Initialize the metadata manager. - - Args: - metadata_dir: Optional directory where metadata.json should be stored. - If None, uses current working directory. - """ - if metadata_dir: - self.metadata_path = metadata_dir / METADATA_FILE - else: - self.metadata_path = get_metadata_path() - self._data: dict = {} - self._load() - - def _load(self) -> None: - """Load metadata from file, creating empty dict if doesn't exist.""" - if self.metadata_path.exists(): - try: - with open(self.metadata_path, "r", encoding="utf-8") as f: - self._data = json.load(f) - except json.JSONDecodeError as e: - raise VersionFileError(f"Invalid metadata.json format: {e}") - else: - self._data = {} - - def _save(self) -> None: - """Save metadata to file.""" - with open(self.metadata_path, "w", encoding="utf-8") as f: - json.dump(self._data, f, indent=2) - - def get_form(self, form_key: str) -> Optional[FormMetadata]: - """ - Get metadata for a form by its key. - - Args: - form_key: The form key (used as key in metadata.json). - - Returns: - FormMetadata if found, None otherwise. - """ - if form_key in self._data: - data = self._data[form_key] - # Only return FormMetadata if the value is a dict with form metadata structure - if isinstance(data, dict) and "originalPath" in data: - return FormMetadata.from_dict(data) - return None - - def set_form(self, form_key: str, metadata: FormMetadata) -> None: - """ - Set metadata for a form. - - Args: - form_key: The form key. - metadata: FormMetadata instance. - """ - self._data[form_key] = metadata.to_dict() - self._save() - - def set_current_path(self, form_key: str, current_path: str) -> None: - """ - Set the current path for a form after push. - - Args: - form_key: The form key. - current_path: The AEM path where the form is pushed. - """ - form = self.get_form(form_key) - if form is None: - raise VersionFileError(f"Form '{form_key}' not found in metadata.") - - form.current_path = current_path - self.set_form(form_key, form) - - -def extract_form_name(form_path: str) -> str: - """ - Extract form name from AEM path. - - Args: - form_path: Full AEM path (e.g., /content/forms/af/acroform) - - Returns: - Form name (last segment of path). - """ - return form_path.rstrip("/").split("/")[-1] - - -def extract_folder_name(form_path: str) -> str: - """ - Extract folder name from AEM path. - - Args: - form_path: Full AEM path (e.g., /content/forms/af/myFolder/acroform) - - Returns: - Folder name (second-to-last segment, or 'af' if at root). - """ - parts = form_path.rstrip("/").split("/") - if len(parts) >= 2: - return parts[-2] - return "af" - - -def extract_folder_path(form_path: str) -> str: - """ - Extract the DAM folder path from a form path. - - Converts /content/forms/af/... to /content/dam/formsanddocuments/... - - Args: - form_path: Full AEM form path. - - Returns: - Corresponding DAM folder path. - """ - # Remove form name to get parent path - parts = form_path.rstrip("/").split("/") - parent_parts = parts[:-1] # Remove last segment (form name) - - # Convert /content/forms/af/... to /content/dam/formsanddocuments/... - if len(parent_parts) >= 4 and parent_parts[:4] == ["", "content", "forms", "af"]: - remaining = parent_parts[4:] # Parts after /content/forms/af - if remaining: - return "/content/dam/formsanddocuments/" + "/".join(remaining) - return "/content/dam/formsanddocuments" - - # Fallback: just return the parent path as-is - return "/".join(parent_parts) - - -def determine_local_filename(form_path: str) -> str: - """ - Determine the local filename for a form, handling collisions. - - Args: - form_path: Full AEM form path. - - Returns: - Local filename (e.g., 'acroform.form.json' or 'myFolder_acroform.form.json'). - """ - form_name = extract_form_name(form_path) - simple_filename = f"{form_name}.form.json" - - # Check if simple filename already exists - working_dir = get_working_dir() - if not (working_dir / simple_filename).exists(): - return simple_filename - - # Use folder prefix - folder_name = extract_folder_name(form_path) - return f"{folder_name}_{form_name}.form.json" - - -def get_form_key_from_filename(filename: str) -> str: - """ - Extract form key from local filename. - - Args: - filename: Local filename (e.g., 'acroform.form.json'). - - Returns: - Form key (e.g., 'acroform'). - """ - # Remove .form.json extension - if filename.endswith(".form.json"): - return filename[:-10] - return filename - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/pull.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/pull.py deleted file mode 100644 index 6de6419b..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/pull.py +++ /dev/null @@ -1,341 +0,0 @@ -"""Pull operation for AEM Form Sync.""" - -import json -import uuid -from pathlib import Path -from typing import Optional - -from .client import AEMClient -from .config import Config, get_working_dir -from .metadata import ( - FormMetadata, - MetadataManager, - determine_local_filename, - extract_folder_path, - extract_form_name, - get_form_key_from_filename, -) - - -def parse_fd_json_strings(data: dict) -> dict: - """ - Parse JSON strings in values where keys start with 'fd:'. - - Args: - data: Dictionary potentially containing JSON strings in fd: keys. - - Returns: - New dictionary with JSON strings parsed into objects. - """ - result = {} - for key, value in data.items(): - if key.startswith("fd:"): - # Parse JSON strings in arrays or single values - if isinstance(value, list): - parsed_list = [] - for item in value: - if isinstance(item, str): - try: - parsed_list.append(json.loads(item)) - except json.JSONDecodeError: - # Keep as string if not valid JSON - parsed_list.append(item) - else: - parsed_list.append(item) - result[key] = parsed_list - elif isinstance(value, str): - try: - result[key] = json.loads(value) - except json.JSONDecodeError: - # Keep as string if not valid JSON - result[key] = value - else: - result[key] = value - else: - result[key] = value - return result - - -def extract_rules_from_component( - component: dict, - rules_store: dict, - component_path: str = "" -) -> None: - """ - Recursively traverse component and extract fd:rules and fd:events. - - Modifies the component in-place, replacing fd:rules and fd:events - with {"ref": uuid} references. - - Args: - component: The component dictionary to process. - rules_store: Dictionary to store extracted rules, keyed by UUID. - component_path: The path to the current component (for debugging). - """ - if not isinstance(component, dict): - return - - # Check if this component has fd:rules - if "fd:rules" in component: - rule_uuid = str(uuid.uuid4()) - - # Extract and parse fd:rules (parse JSON strings in fd: keys) - fd_rules = component["fd:rules"] - if isinstance(fd_rules, dict): - fd_rules = parse_fd_json_strings(fd_rules) - - # Extract both fd:rules and fd:events (if present) - extracted = { - "componentPath": component_path, - "componentName": component.get("name", ""), - "fd:rules": fd_rules - } - - if "fd:events" in component: - fd_events = component["fd:events"] - if isinstance(fd_events, dict): - fd_events = parse_fd_json_strings(fd_events) - extracted["fd:events"] = fd_events - # Replace fd:events with ref - component["fd:events"] = {"ref": rule_uuid} - - # Store in rules_store - rules_store[rule_uuid] = extracted - - # Replace fd:rules with ref - component["fd:rules"] = {"ref": rule_uuid} - - # Recursively process nested components - for key, value in component.items(): - if isinstance(value, dict): - # Build component path for nested components - nested_path = f"{component_path}/{key}" if component_path else key - extract_rules_from_component(value, rules_store, nested_path) - - -def extract_all_rules(form_data: dict) -> dict: - """ - Extract all rules from the form data. - - Args: - form_data: The full form JSON data. - - Returns: - Dictionary of extracted rules keyed by UUID. - """ - rules_store = {} - extract_rules_from_component(form_data, rules_store) - return rules_store - - -def save_rules_file( - rules_store: dict, - form_key: str, - working_dir: Path -) -> Path: - """ - Save extracted rules to a separate JSON file. - - Always creates the file, even if no rules were extracted (empty JSON object). - - Args: - rules_store: Dictionary of extracted rules keyed by UUID. - form_key: The form key (used for filename). - working_dir: Directory to save the rules file. - - Returns: - Path to the saved rules file. - """ - rules_filename = f"{form_key}.rule.json" - rules_path = working_dir / rules_filename - - with open(rules_path, "w", encoding="utf-8") as f: - json.dump(rules_store, f, indent=2) - - return rules_path - - -def is_fragment(form_data: dict) -> bool: - """ - Check if the form data represents a fragment. - - Fragments have 'fd:type' set to 'fragment' at the top level. - - Args: - form_data: The form JSON data from AEM. - - Returns: - True if this is a fragment, False otherwise. - """ - return form_data.get("fd:type") == "fragment" - - -def pull_form( - form_path: str, - config: Config, - extract_rules: bool = True, - output_dir: Path = None, - override_form_key: str = None, - no_edit: bool = False, -) -> tuple[Path, str]: - """ - Pull a form or fragment from AEM and save it locally. - - Args: - form_path: Full AEM path to the form/fragment (e.g., /content/forms/af/acroform). - config: Configuration object with AEM credentials. - extract_rules: If True (default), extract rules and create formabstract file. - If False, skip rules extraction and formabstract creation. - output_dir: Optional custom output directory. If not provided, uses content - path structure under repo/ or refs/ directory. - override_form_key: Optional form key to use instead of auto-generated one. - no_edit: If True, sync to refs directory (read-only reference). - If False (default), sync to repo directory (editable). - - Returns: - Tuple of (path to saved file, form key). - - Raises: - FormNotFoundError: If form/fragment doesn't exist on AEM. - AuthenticationError: If authentication fails. - """ - # Initialize client - client = AEMClient(config) - - # Determine working directory based on no_edit flag and output_dir - if output_dir: - # Custom output directory takes precedence - working_dir = Path(output_dir) - else: - # Use content path structure under repo/ or refs/ - working_dir = config.get_form_dir(form_path, no_edit=no_edit) - - # Create directory if it doesn't exist - working_dir.mkdir(parents=True, exist_ok=True) - - # Determine base directory for relative path calculation - base_dir = config.refs_dir if no_edit else config.repo_dir - - # Check if form already exists in metadata BY ORIGINAL PATH - # Use global metadata (from cwd, not output_dir) - metadata_manager = MetadataManager() - - # Search metadata for this form by originalPath or currentPath - existing_metadata = None - form_key = None - for key, data in metadata_manager._data.items(): - # Skip non-form entries (must be a dict with form metadata fields) - if not isinstance(data, dict) or "originalPath" not in data: - continue - - form_meta = FormMetadata.from_dict(data) - if form_meta.original_path == form_path or form_meta.current_path == form_path: - existing_metadata = form_meta - form_key = key - break - - # Determine which path to fetch from and what filename to use - # use_base_dir flag indicates local_filename is a full relative path from base_dir - use_base_dir = False - if existing_metadata: - # Form exists in metadata - use existing settings - # local_file in metadata is relative to base_dir (repo/ or refs/) - local_filename = existing_metadata.local_file - use_base_dir = True - if existing_metadata.current_path: - fetch_path = existing_metadata.current_path - print(f"Found existing form in metadata, fetching from: {fetch_path}") - else: - fetch_path = form_path - print(f"Found existing form in metadata, fetching from: {fetch_path}") - else: - # New form - determine filename and use original path - fetch_path = form_path - if override_form_key: - # Use the provided form key - form_key = override_form_key - local_filename = f"{form_key}.form.json" - else: - local_filename = determine_local_filename(form_path) - form_key = get_form_key_from_filename(local_filename) - - # Fetch form content (form node inside the page structure) - fetch_url = f"{fetch_path}/jcr:content/root/section/form.-1.json" - response = client.get(fetch_url) - form_data = response.json() - rules_filename = None - - # Determine output path based on whether we're using existing metadata - if use_base_dir: - # local_filename is a full relative path from base_dir - output_path = base_dir / local_filename - rules_dir = output_path.parent - else: - # local_filename is just the filename, combine with working_dir - output_path = working_dir / local_filename - rules_dir = working_dir - - if extract_rules: - # Extract rules from form data (modifies form_data in place) - rules_store = extract_all_rules(form_data) - - # Save form JSON (now with fd:rules/fd:events replaced by refs) - with open(output_path, "w", encoding="utf-8") as f: - json.dump(form_data, f, indent=2) - - # Save rules file (always created, even if empty) - rules_path = save_rules_file(rules_store, form_key, rules_dir) - rules_filename = f"{form_key}.rule.json" - print(f"Extracted {len(rules_store)} rule(s) to {rules_path}") - else: - # Save form JSON as-is (no rules extraction) - with open(output_path, "w", encoding="utf-8") as f: - json.dump(form_data, f, indent=2) - - # Update metadata - folder_path = extract_folder_path(form_path) - - # Determine location for metadata - location = "refs" if no_edit else "repo" - - # Detect if this is a fragment - is_fragment_flag = is_fragment(form_data) - if is_fragment_flag: - print(f"Detected as fragment (fd:type=fragment)") - - # Calculate relative paths from base directory - if output_dir: - # Custom output: store just the filename - relative_local_file = local_filename - relative_rule_file = rules_filename - else: - # Standard repo/refs: store path relative to base_dir - try: - relative_local_file = str(output_path.relative_to(base_dir)) - if rules_filename: - rules_path_full = working_dir / rules_filename - relative_rule_file = str(rules_path_full.relative_to(base_dir)) - else: - relative_rule_file = None - except ValueError: - # Fallback if paths don't share base - relative_local_file = local_filename - relative_rule_file = rules_filename - - form_metadata = FormMetadata( - folder_path=folder_path, - original_path=form_path, - local_file=relative_local_file, - local_rule_file=relative_rule_file, - location=location, - fragment=is_fragment_flag, - ) - - # Preserve current_path from existing entry if it exists - if existing_metadata and existing_metadata.current_path: - form_metadata.current_path = existing_metadata.current_path - - metadata_manager.set_form(form_key, form_metadata) - - return output_path, form_key - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/push.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/push.py deleted file mode 100644 index c73c1401..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts/form_sync/push.py +++ /dev/null @@ -1,1194 +0,0 @@ -"""Push operation for AEM Form Sync.""" - -import json -import time -from pathlib import Path -from typing import Optional - -import requests - -from .auth import AuthManager, CloudToken -from .client import AEMClient -from .components import build_add_component_payload, extract_root_components -from .config import Config, Environment, get_working_dir -from .exceptions import ( - ComponentAddError, - FormCreationError, - FormSyncError, - PathNotAllowedError, - VersionFileError, -) -from .metadata import ( - FormMetadata, - MetadataManager, - extract_form_name, - get_form_key_from_filename, -) - - -def stringify_fd_json_objects(data: dict) -> dict: - """ - Stringify JSON objects back to strings for keys starting with 'fd:'. - - This is the reverse of parse_fd_json_strings in pull.py. - - Args: - data: Dictionary with parsed JSON objects in fd: keys. - - Returns: - New dictionary with objects stringified back to JSON strings. - """ - result = {} - for key, value in data.items(): - if key.startswith("fd:"): - # Stringify objects back to JSON strings - if isinstance(value, list): - stringified_list = [] - for item in value: - if isinstance(item, dict): - stringified_list.append(json.dumps(item)) - else: - stringified_list.append(item) - result[key] = stringified_list - elif isinstance(value, dict): - result[key] = json.dumps(value) - else: - result[key] = value - else: - result[key] = value - return result - - -def restore_rules_to_component(component: dict, rules_store: dict) -> None: - """ - Recursively traverse component and restore fd:rules and fd:events from refs. - - Modifies the component in-place, replacing {"ref": uuid} with actual content. - Also stringifies the fd: prefixed keys back to JSON strings. - - Args: - component: The component dictionary to process. - rules_store: Dictionary of extracted rules keyed by UUID. - """ - if not isinstance(component, dict): - return - - # Check if fd:rules has a ref to restore - if "fd:rules" in component: - rules_data = component["fd:rules"] - if isinstance(rules_data, dict) and "ref" in rules_data: - rule_uuid = rules_data["ref"] - if rule_uuid in rules_store: - # Restore original fd:rules and stringify fd: keys - original_rules = rules_store[rule_uuid].get("fd:rules", {}) - if isinstance(original_rules, dict): - original_rules = stringify_fd_json_objects(original_rules) - component["fd:rules"] = original_rules - - # Check if fd:events has a ref to restore - if "fd:events" in component: - events_data = component["fd:events"] - if isinstance(events_data, dict) and "ref" in events_data: - rule_uuid = events_data["ref"] - if rule_uuid in rules_store: - # Restore original fd:events and stringify fd: keys - original_events = rules_store[rule_uuid].get("fd:events", {}) - if isinstance(original_events, dict): - original_events = stringify_fd_json_objects(original_events) - component["fd:events"] = original_events - - # Recursively process nested components - for key, value in component.items(): - if isinstance(value, dict): - restore_rules_to_component(value, rules_store) - - -def load_and_restore_rules( - form_data: dict, form_metadata: FormMetadata, base_dir: Path -) -> None: - """ - Load rules file and restore rules into form data. - - Args: - form_data: The form JSON data (modified in-place). - form_metadata: The form metadata containing local_rule_file path. - base_dir: Base directory (repo or refs) for resolving relative paths. - """ - # Use the localRuleFile from metadata if available - if not form_metadata.local_rule_file: - return # No rules file specified in metadata - - rules_path = Path(form_metadata.local_rule_file) - if not rules_path.is_absolute(): - rules_path = base_dir / rules_path - - if not rules_path.exists(): - return # No rules file, nothing to restore - - with open(rules_path, "r", encoding="utf-8") as f: - rules_store = json.load(f) - - restore_rules_to_component(form_data, rules_store) - - -def get_csrf_token(client: AEMClient) -> str: - """ - Get CSRF token from AEM for form submissions. - - Args: - client: AEM HTTP client. - - Returns: - CSRF token string. - - Raises: - FormSyncError: If token retrieval fails. - """ - try: - response = client.get("/libs/granite/csrf/token.json") - data = response.json() - return data.get("token", "") - except Exception as e: - raise FormSyncError(f"Failed to get CSRF token: {e}") - - -def get_config_path_from_form_path(form_path: str) -> str: - """ - Convert form path to cloud configuration path. - - Args: - form_path: Form path like /content/forms/af/forms-team/form/pl/etb-wo-v1 - - Returns: - Config path like /conf/forms/forms-team/form/pl/etb-wo-v1/settings/cloudconfigs/edge-delivery-service-configuration/_jcr_content - """ - if form_path.startswith("/content/forms/af/"): - relative_path = form_path[len("/content/forms/af/") :] - else: - relative_path = form_path.lstrip("/") - - return f"/conf/forms/{relative_path}/settings/cloudconfigs/edge-delivery-service-configuration/_jcr_content" - - -def update_edge_delivery_config( - client: AEMClient, - config: "Config", - form_path: str, - on_progress: Optional[callable] = None, -) -> dict: - """ - Update the Edge Delivery Service configuration for a form with the GitHub branch. - - This sets the 'ref' (branch) in the form's cloud configuration to match - the GITHUB_BRANCH environment variable. - - Args: - client: AEM HTTP client. - config: Configuration object with github_branch, github_owner, github_repo. - form_path: Path to the form (e.g., /content/forms/af/forms-team/myform). - on_progress: Optional callback for progress messages. - - Returns: - dict with keys: - success (bool): Whether the config was updated successfully. - message (str): Description of what happened. - remediation (str | None): Suggested fix if the update failed. - """ - - def log(message: str) -> None: - if on_progress: - on_progress(message) - - def result(success: bool, message: str, remediation: str = None) -> dict: - return {"success": success, "message": message, "remediation": remediation} - - # Skip if no branch configured - if not config.github_branch: - msg = "GITHUB_BRANCH is not set in .env" - log(f"Skipping Edge Delivery config update: {msg}") - return result( - False, - msg, - "Add GITHUB_BRANCH=main (or your branch name) to your workspace .env file and retry.", - ) - - owner = config.github_owner - repo = config.github_repo - - if not owner or not repo: - msg = "Could not parse owner/repo from GITHUB_URL" - log(f"Skipping Edge Delivery config update: {msg}") - return result( - False, - msg, - "Set GITHUB_URL=https://github.com/<owner>/<repo> in your workspace .env file and retry.", - ) - - # Get CSRF token - log("Getting CSRF token...") - try: - csrf_token = get_csrf_token(client) - except Exception as e: - msg = f"Failed to get CSRF token: {e}" - log(msg) - return result( - False, - msg, - "Verify AEM_HOST and AEM_TOKEN (or AEM_USERNAME/AEM_PASSWORD) are correct in .env. " - "The token may have expired — regenerate it from AEM Developer Console.", - ) - - # Build config path - config_path = get_config_path_from_form_path(form_path) - log(f"Updating Edge Delivery config at: {config_path}") - - # Build form data (URL-encoded) - form_data = { - "./owner": owner, - "./repo": repo, - "./ref": config.github_branch, - "./edgeHost@Delete": "", - "./edgeHost": "preview", - "./projectType@Delete": "", - "./projectType": "4", - "./siteAuthToken": "", - "./siteAuthToken@Encrypted": "", - "./auxiliaryScripts": "module:scripts/editor-support.js", - "./auxiliaryScripts@Delete": "", - ":cq_csrf_token": csrf_token, - } - - headers = { - "Authorization": config.basic_auth_header, - "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", - "csrf-token": csrf_token, - "X-Requested-With": "XMLHttpRequest", - } - - try: - url = f"{config.aem_host}{config_path}" - response = requests.post(url, data=form_data, headers=headers) - - if not response.ok: - msg = f"HTTP {response.status_code} from AEM at {config_path}" - detail = response.text[:200] if response.text else "(no response body)" - log(f"Warning: Edge Delivery config update failed — {msg}: {detail}") - - if response.status_code == 401: - remediation = ( - "Authentication failed. Regenerate your bearer token from AEM Developer Console " - "and update AEM_TOKEN in .env." - ) - elif response.status_code == 403: - remediation = ( - f"Permission denied writing to {config_path}. " - "Ensure the AEM user has write access to /conf/forms/ and that " - "the form path is included in AEM_WRITE_PATHS in .env." - ) - elif response.status_code == 404: - remediation = ( - f"Cloud config path not found: {config_path}. " - "The form may not have been created correctly on AEM, or the " - "cloud config node does not exist yet. Try re-creating the form." - ) - else: - remediation = ( - f"AEM returned HTTP {response.status_code}. Check AEM logs for details. " - "Verify AEM_HOST is correct and the AEM instance is healthy." - ) - - return result(False, f"{msg} — {detail}", remediation) - else: - msg = ( - f"Edge Delivery config updated: branch set to '{config.github_branch}'" - ) - log(msg) - return result(True, msg) - - except requests.RequestException as e: - msg = f"Network error updating Edge Delivery config: {e}" - log(msg) - return result( - False, - msg, - "Check network connectivity to AEM_HOST. Verify the URL is correct and " - "the AEM instance is reachable from your machine.", - ) - - -def create_empty_form( - client: AEMClient, - config: Config, - form_title: str, - folder_path: str, -) -> str: - """ - Create an empty form on AEM. - - Args: - client: AEM HTTP client. - config: Configuration with GitHub URL. - form_title: Title for the new form. - folder_path: DAM folder path for the form. - - Returns: - The URL path of the created form (e.g., /content/forms/af/myform-v1.html). - - Raises: - FormCreationError: If form creation fails. - """ - payload = { - "queryType": "create_form", - "result": { - "formTitle": form_title, - "formJson": '{"items": []}', - "queryType": "create_form", - "folderPath": folder_path, - "templatePath": "/libs/fd/franklin/templates/page", - "githubUrl": config.github_url, - }, - } - - try: - response = client.post("/adobe/forms/genaiaction/create_form", json=payload) - data = response.json() - - # Extract the form URL from response - form_url = data.get("result", {}).get("url", "") - if not form_url: - raise FormCreationError( - f"Form creation response missing URL. Response: {data}" - ) - - return form_url - - except FormSyncError: - raise - except Exception as e: - raise FormCreationError(f"Failed to create form: {e}") - - -def create_empty_fragment( - client: AEMClient, - config: Config, - fragment_title: str, - fragment_name: str, - folder_path: str, -) -> str: - """ - Create an empty fragment on AEM. - - Args: - client: AEM HTTP client. - config: Configuration with GitHub URL. - fragment_title: Title for the new fragment. - fragment_name: Name (slug) for the new fragment. - folder_path: DAM folder path for the fragment. - - Returns: - The path of the created fragment (e.g., /content/forms/af/team/fragments/my-fragment). - - Raises: - FormCreationError: If fragment creation fails. - """ - payload = { - "githuburl": config.github_url, - "title": fragment_title, - "name": fragment_name, - "templatePath": "/libs/fd/franklin/templates/fragment", - "themePath": "", - "folderPath": folder_path, - } - - try: - response = client.post("/adobe/forms/fm/v1/fragments", json=payload) - data = response.json() - - # Extract the fragment path from response - # The response format may vary - check for common patterns - fragment_path = data.get("path", "") or data.get("fragmentPath", "") - - if not fragment_path: - # Try to construct path from folder and name - # Convert DAM path to forms path - forms_folder = folder_path.replace( - "/content/dam/formsanddocuments/", "/content/forms/af/" - ) - fragment_path = f"{forms_folder}/{fragment_name}" - - return fragment_path - - except FormSyncError: - raise - except Exception as e: - raise FormCreationError(f"Failed to create fragment: {e}") - - -def create_form_via_sling_import( - client: AEMClient, - config: Config, - form_title: str, - form_path: str, - on_progress: Optional[callable] = None, -) -> str: - """ - Create a form on local AEM SDK via Sling POST import API. - - This is the local-mode alternative to create_empty_form() which relies on - the GenAI endpoint that is only available on AEM Cloud. - - Creates the full EDS Franklin page structure: - cq:Page / jcr:content (page) / root (root) / section (section) / form (form) - - Args: - client: AEM HTTP client. - config: Configuration object. - form_title: Title for the new form. - form_path: Full AEM path (e.g., /content/forms/af/forms-team/myform). - on_progress: Optional callback for progress messages. - - Returns: - The path of the created form. - - Raises: - FormCreationError: If form creation fails. - """ - - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Build the full JCR page structure with correct EDS Franklin resource types - page_json = { - "jcr:primaryType": "cq:Page", - "jcr:content": { - "jcr:primaryType": "cq:PageContent", - "jcr:title": form_title, - "sling:resourceType": "core/franklin/components/page/v1/page", - "cq:template": "/libs/fd/franklin/templates/page", - "jcr:language": "en", - "author": "adobe", - "sling:configRef": f"/conf/forms/{form_path.replace('/content/forms/af/', '')}/", - "root": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/franklin/components/root/v1/root", - "section": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/franklin/components/section/v1/section", - "form": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "fd/franklin/components/form/v1/form", - "fd:version": "2.1", - "fieldType": "form", - "jcr:title": form_title, - "name": form_title.lower().replace(" ", "-"), - }, - }, - }, - }, - } - - try: - # Ensure parent folder exists - parent_path = "/".join(form_path.rstrip("/").split("/")[:-1]) - log(f"Ensuring parent folder exists: {parent_path}") - requests.post( - f"{config.aem_host}{parent_path}", - data={ - "jcr:primaryType": "sling:OrderedFolder", - "jcr:title": parent_path.split("/")[-1], - }, - headers={"Authorization": config.basic_auth_header}, - ) - - # Import the page structure via Sling POST - log(f"Creating form page at: {form_path}") - response = requests.post( - f"{config.aem_host}{form_path}", - data={ - ":operation": "import", - ":contentType": "json", - ":content": json.dumps(page_json), - ":replace": "true", - ":replaceProperties": "true", - }, - headers={"Authorization": config.basic_auth_header}, - ) - - # AEM may return 409 for Sling import but still succeed - if response.status_code not in (200, 201, 409): - raise FormCreationError( - f"Sling import failed: HTTP {response.status_code} - {response.text[:200]}" - ) - - log(f"Form page created at: {form_path}") - return form_path - - except FormCreationError: - raise - except Exception as e: - raise FormCreationError(f"Failed to create form via Sling import: {e}") - - -def get_form_path_from_url(form_url: str) -> str: - """ - Extract form path from URL. - - Args: - form_url: Form URL like /content/forms/af/myform.html - - Returns: - Form path like /content/forms/af/myform - """ - # Remove .html extension if present - if form_url.endswith(".html"): - return form_url[:-5] - return form_url - - -def add_component_to_form( - config: Config, - cloud_token: CloudToken, - form_path: str, - component_key: str, - component_data: dict, -) -> None: - """ - Add a component to a form via Universal Editor API. - - Args: - config: Configuration object. - cloud_token: Cloud token for authentication. - form_path: Path to the form (without .html). - component_key: The key of the component. - component_data: The component data dict. - - Raises: - ComponentAddError: If adding the component fails. - """ - # Build the payload - payload = build_add_component_payload( - aem_host=config.aem_host, - form_path=form_path, - component_key=component_key, - component_data=component_data, - ) - - # Build headers - headers = { - "Authorization": f"Bearer {cloud_token.access_token}", - "x-aemconnection-authorization": config.basic_auth_header, - "Content-Type": "application/json", - } - - try: - response = requests.post( - f"{config.ue_service_url}/add", json=payload, headers=headers - ) - - if not response.ok: - raise ComponentAddError( - f"Failed to add component '{component_key}': " - f"HTTP {response.status_code} - {response.text[:200]}", - component_name=component_key, - form_path=form_path, - ) - - except requests.RequestException as e: - raise ComponentAddError( - f"Network error adding component '{component_key}': {e}", - component_name=component_key, - form_path=form_path, - ) - - -def patch_form_content( - config: Config, - cloud_token: CloudToken, - form_path: str, - form_data: dict, -) -> None: - """ - Patch entire form content via Universal Editor API. - - Args: - config: Configuration object. - cloud_token: Cloud token for authentication. - form_path: Path to the form (without .html). - form_data: The complete form data dict to patch. - - Raises: - FormSyncError: If patching the form fails. - """ - # Build the payload for patch API - payload = { - "connections": [ - { - "name": "aemconnection", - "protocol": "xwalk", - "uri": config.aem_host, - } - ], - "patch": [ - { - "op": "add", - "path": "/form", - "value": form_data, - } - ], - "target": { - "prop": "", - "resource": f"urn:aemconnection:{form_path}/jcr:content/root/section", - "type": "component", - }, - } - - # Build headers - headers = { - "Authorization": f"Bearer {cloud_token.access_token}", - "x-aemconnection-authorization": config.basic_auth_header, - "Content-Type": "application/json", - } - - try: - response = requests.post( - f"{config.ue_service_url}/patch", json=payload, headers=headers - ) - - if not response.ok: - raise FormSyncError( - f"Failed to patch form content: " - f"HTTP {response.status_code} - {response.text[:200]}" - ) - - except requests.RequestException as e: - raise FormSyncError(f"Network error patching form: {e}") - - -def get_form_details( - config: Config, - cloud_token: CloudToken, - form_path: str, -) -> dict: - """ - Get form details via Universal Editor API. - - Args: - config: Configuration object. - cloud_token: Cloud token for authentication. - form_path: Path to the form (without .html). - - Returns: - The form details data dict. - - Raises: - FormSyncError: If getting form details fails. - """ - # Build the payload for details API - payload = { - "connections": [ - { - "name": "aemconnection", - "protocol": "xwalk", - "uri": config.aem_host, - } - ], - "target": { - "prop": "", - "resource": f"urn:aemconnection:{form_path}/jcr:content/root/section/form", - "type": "container", - }, - } - - # Build headers - headers = { - "Authorization": f"Bearer {cloud_token.access_token}", - "x-aemconnection-authorization": config.basic_auth_header, - "Content-Type": "application/json", - } - - try: - response = requests.post( - f"{config.ue_service_url}/details", json=payload, headers=headers - ) - - if not response.ok: - raise FormSyncError( - f"Failed to get form details: " - f"HTTP {response.status_code} - {response.text[:200]}" - ) - - return response.json() - - except requests.RequestException as e: - raise FormSyncError(f"Network error getting form details: {e}") - - -def extract_root_level_components(details_data: dict) -> list[str]: - """ - Extract root-level component names from form details. - - A root-level component is any key in the 'data' dict whose value is a JSON object (dict), - excluding form-level metadata keys (fd:*, jcr:*, sling:*). - - Args: - details_data: The response from the details API. - - Returns: - List of component names (keys) that are root-level components. - """ - if "data" not in details_data: - return [] - - # Keys that are form-level metadata, NOT components to remove - METADATA_PREFIXES = ("fd:", "jcr:", "sling:") - METADATA_KEYS = { - "fieldType", - "title", - "thankYouOption", - "action", - "dataRef", - "customFunctionsPath", - "schemaRef", - "schemaType", - "name", - } - - data = details_data["data"] - components = [] - - for key, value in data.items(): - # Skip metadata keys - these are form properties, not components - if key.startswith(METADATA_PREFIXES) or key in METADATA_KEYS: - continue - # Any remaining value that is a dict is considered a component - if isinstance(value, dict): - components.append(key) - - return components - - -def remove_component( - config: Config, - cloud_token: CloudToken, - form_path: str, - component_name: str, -) -> None: - """ - Remove a component from a form via Universal Editor API. - - Args: - config: Configuration object. - cloud_token: Cloud token for authentication. - form_path: Path to the form (without .html). - component_name: Name of the component to remove. - - Raises: - FormSyncError: If removing the component fails. - """ - # Build the payload for remove API - payload = { - "connections": [ - { - "name": "aemconnection", - "protocol": "xwalk", - "uri": config.aem_host, - } - ], - "target": { - "component": { - "prop": "", - "resource": f"urn:aemconnection:{form_path}/jcr:content/root/section/form/{component_name}", - "type": "container", - }, - "container": { - "prop": "", - "resource": f"urn:aemconnection:{form_path}/jcr:content/root/section/form", - "type": "container", - }, - }, - } - - # Build headers - headers = { - "Authorization": f"Bearer {cloud_token.access_token}", - "x-aemconnection-authorization": config.basic_auth_header, - "Content-Type": "application/json", - } - - try: - response = requests.post( - f"{config.ue_service_url}/remove", json=payload, headers=headers - ) - - if not response.ok: - raise FormSyncError( - f"Failed to remove component '{component_name}': " - f"HTTP {response.status_code} - {response.text[:200]}" - ) - - except requests.RequestException as e: - raise FormSyncError(f"Network error removing component '{component_name}': {e}") - - -def clear_form_components( - config: Config, - cloud_token: CloudToken, - form_path: str, - on_progress: Optional[callable] = None, -) -> None: - """ - Clear all root-level components from a form before updating it. - - Args: - config: Configuration object. - cloud_token: Cloud token for authentication. - form_path: Path to the form (without .html). - on_progress: Optional callback for progress messages. - - Raises: - FormSyncError: If clearing components fails. - """ - - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Get current form details - log("Getting form details...") - details_data = get_form_details(config, cloud_token, form_path) - - # Extract root-level components - components = extract_root_level_components(details_data) - - if not components: - log("No components to remove") - return - - log( - f"Found {len(components)} root-level component(s) to remove: {', '.join(components)}" - ) - - # Remove each component - for component_name in components: - log(f"Removing component: {component_name}") - remove_component(config, cloud_token, form_path, component_name) - - log("All components removed successfully") - - -def push_form( - form_path: str, - config: Config, - source_file: Optional[str] = None, - suffix: str = "-v1", - force_new: bool = False, - on_progress: Optional[callable] = None, - preview_path: Optional[str] = None, -) -> tuple[str, bool]: - """ - Push a local form to AEM. - - First push creates a new form with suffix and patches content. - Subsequent pushes update the existing form via patch API. - - Args: - form_path: Original AEM form path (e.g., /content/forms/af/myform). - config: Configuration object. - source_file: Optional path to source JSON file. - suffix: Suffix to append to form name (default: -v1). - force_new: Force creation of new form even if one exists. - on_progress: Optional callback for progress messages. - preview_path: Optional preview folder path (DAM path). When set, creates - a new form at this path instead of updating existing form. - - Returns: - Tuple of (AEM form path, is_new_form). - - Raises: - PathNotAllowedError: If form path is not in the push allowlist. - FormSyncError: If push operation fails. - """ - - def log(message: str) -> None: - if on_progress: - on_progress(message) - - # Initialize - client = AEMClient(config) - auth_manager = AuthManager(config, client) - metadata_manager = MetadataManager() - - # Determine form key and load metadata - form_name = extract_form_name(form_path) - - # Find the form in metadata - form_key = _find_form_key(metadata_manager, form_path, form_name, source_file) - form_metadata = metadata_manager.get_form(form_key) - - if form_metadata is None: - raise VersionFileError( - f"Form '{form_key}' not found in metadata.json. " - "Please pull the form first using: form-sync pull {form_path}" - ) - - # Check if form is in refs location (read-only) - skip for preview mode - if form_metadata.location == "refs" and not preview_path: - raise FormSyncError( - f"Cannot push form '{form_key}' - it's in refs directory (read-only).\n" - f"Pull the form without --no-edit to sync an editable copy to repo." - ) - - # Check allowlist against the target path - if preview_path: - # For preview mode, check the preview path - # preview_path is a DAM path like /content/dam/formsanddocuments/preview - preview_forms_path = preview_path.replace( - "/content/dam/formsanddocuments/", "/content/forms/af/" - ) - client.check_path_allowed(preview_forms_path) - else: - # Convert DAM folder path to forms path for allowlist check - dam_folder = form_metadata.folder_path - forms_folder = dam_folder.replace( - "/content/dam/formsanddocuments/", "/content/forms/af/" - ) - client.check_path_allowed(forms_folder) - - # Also check currentPath if updating existing form - if form_metadata.current_path: - client.check_path_allowed(form_metadata.current_path) - - # Load the local form JSON - # Determine base directory from form location - base_dir = config.repo_dir if form_metadata.location == "repo" else config.refs_dir - - if source_file: - # User-provided source file - local_path = ( - Path(source_file) - if Path(source_file).is_absolute() - else get_working_dir() / source_file - ) - else: - # Use path from metadata (relative to base_dir) - local_path = base_dir / form_metadata.local_file - - if not local_path.exists(): - raise FormSyncError(f"Local form file not found: {local_path}") - - with open(local_path, "r", encoding="utf-8") as f: - form_data = json.load(f) - - # Restore rules from rule.json file before pushing - # Rules file is in the same directory as the form file - working_dir = local_path.parent - load_and_restore_rules(form_data, form_metadata, base_dir) - - # Get cloud token for Universal Editor API - log("Fetching cloud token...") - cloud_token = auth_manager.get_cloud_token() - log("Cloud token obtained") - - # Determine if we should update existing form or create new one - # Preview mode always creates a new form at the preview path - current_path = form_metadata.current_path - is_new_form = False - - if preview_path: - # Preview mode: always create a new form/fragment at preview path - is_new_form = True - - # Create form title with suffix - use original form name from originalPath - original_form_name = extract_form_name(form_metadata.original_path) - form_title = f"{original_form_name}{suffix}" - - if form_metadata.fragment: - log(f"Creating preview fragment: {form_title}") - target_path = create_empty_fragment( - client=client, - config=config, - fragment_title=form_title, - fragment_name=form_title, - folder_path=preview_path, - ) - log(f"Created empty preview fragment: {target_path}") - else: - log(f"Creating preview form: {form_title}") - form_url = create_empty_form( - client=client, - config=config, - form_title=form_title, - folder_path=preview_path, - ) - target_path = get_form_path_from_url(form_url) - log(f"Created empty preview form: {target_path}") - - # Wait for form/fragment to be ready before patching - log("Waiting 2 seconds for form/fragment to be ready...") - time.sleep(2) - - # Patch form content - log("Patching form content...") - patch_form_content( - config=config, - cloud_token=cloud_token, - form_path=target_path, - form_data=form_data, - ) - log("Preview form/fragment content added successfully") - - # Note: Don't update metadata for preview forms/fragments - elif current_path and not force_new: - # Update existing form/fragment via patch API - entity_type = "fragment" if form_metadata.fragment else "form" - log(f"Updating existing {entity_type}: {current_path}") - - # Patch form content directly (no need to clear first - patch replaces) - log(f"Patching {entity_type} with new content...") - patch_form_content( - config=config, - cloud_token=cloud_token, - form_path=current_path, - form_data=form_data, - ) - log(f"{entity_type.capitalize()} content updated successfully") - target_path = current_path - else: - # Create new form or fragment - is_new_form = True - - # Create form title with suffix - use original form name from originalPath - original_form_name = extract_form_name(form_metadata.original_path) - form_title = f"{original_form_name}{suffix}" - - if config.create_form_strategy == "sling_import": - # Local mode: use Sling POST import (no GenAI endpoint) - if form_metadata.fragment: - log(f"Creating new fragment via Sling import: {form_title}") - # For fragments, construct the target path from folder_path + name - dam_folder = form_metadata.folder_path - forms_folder = dam_folder.replace( - "/content/dam/formsanddocuments/", "/content/forms/af/" - ) - target_path = f"{forms_folder}/{form_title}" - # TODO: Sling import for fragments (similar structure, different template) - raise FormCreationError( - "Fragment creation via Sling import is not yet implemented.\n" - "Create the fragment manually on AEM and set currentPath in metadata.json." - ) - else: - # Construct target path from original_path + suffix - base_path = form_metadata.original_path.rstrip("/") - target_path = f"{base_path}{suffix}" - log(f"Creating new form via Sling import: {target_path}") - target_path = create_form_via_sling_import( - client=client, - config=config, - form_title=form_title, - form_path=target_path, - on_progress=on_progress, - ) - log(f"Created form via Sling import: {target_path}") - else: - # Stage/Prod: use GenAI endpoint - if form_metadata.fragment: - log(f"Creating new fragment: {form_title}") - target_path = create_empty_fragment( - client=client, - config=config, - fragment_title=form_title, - fragment_name=form_title, - folder_path=form_metadata.folder_path, - ) - log(f"Created empty fragment: {target_path}") - else: - log(f"Creating new form: {form_title}") - form_url = create_empty_form( - client=client, - config=config, - form_title=form_title, - folder_path=form_metadata.folder_path, - ) - target_path = get_form_path_from_url(form_url) - log(f"Created empty form: {target_path}") - - # Wait for form/fragment to be ready before patching - log("Waiting 2 seconds for form/fragment to be ready...") - time.sleep(2) - - # Patch form content - log("Patching form content...") - patch_form_content( - config=config, - cloud_token=cloud_token, - form_path=target_path, - form_data=form_data, - ) - log("Form/fragment content added successfully") - - # Update metadata with current path - log("Updating metadata...") - metadata_manager.set_current_path(form_key, target_path) - - # Update Edge Delivery config for new forms/fragments - if is_new_form: - log("Updating Edge Delivery configuration...") - eds_config_result = update_edge_delivery_config( - client, config, target_path, on_progress - ) - if not eds_config_result["success"]: - log(f"⚠ Edge Delivery config update failed: {eds_config_result['message']}") - if eds_config_result.get("remediation"): - log(f" Remediation: {eds_config_result['remediation']}") - - return target_path, is_new_form - - -def _find_form_key( - metadata_manager: MetadataManager, - form_path: str, - form_name: str, - source_file: Optional[str], -) -> str: - """ - Find the form key in metadata. - - Tries multiple strategies: - 1. If source_file provided, derive key from filename - 2. Search metadata for exact originalPath match - - Args: - metadata_manager: Metadata manager instance. - form_path: Original AEM form path. - form_name: Extracted form name (unused, kept for compatibility). - source_file: Optional source file path. - - Returns: - Form key found in metadata. - - Raises: - VersionFileError: If form not found. - """ - # Strategy 1: Derive from source file - if source_file: - filename = Path(source_file).name - key = get_form_key_from_filename(filename) - if metadata_manager.get_form(key): - return key - - # Strategy 2: Search by exact originalPath match - metadata_path = metadata_manager.metadata_path - if metadata_path.exists(): - with open(metadata_path, "r", encoding="utf-8") as f: - all_metadata = json.load(f) - - for key, data in all_metadata.items(): - if isinstance(data, dict) and data.get("originalPath") == form_path: - return key - - # Not found - raise VersionFileError( - f"Form not found in metadata.json for path: {form_path}\n" - "Please pull the form first." - ) diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/SKILL.md deleted file mode 100644 index ea0eae14..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/SKILL.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -name: integration -description: > - Domain router for API & data-integration skills. Routes user intents - to the correct integration skill based on the operation requested. -type: domain -triggers: - - API - - FDM - - sync APIs - - add API - - build client - - OpenAPI - - cURL -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Integration — Domain Router - -- **ID:** `integration` -- **Version:** 0.1 -- **Description:** Routes API and data-integration intents to the appropriate skill. This router does not implement — it delegates. - ---- - -## Routing Table - -First match wins. - -| Intent | Skill | -|--------|-------| -| Sync APIs from AEM FDM, discover APIs | `manage-apis` | -| Add new API definition, cURL → OpenAPI | `manage-apis` | -| Build / rebuild JS API clients | `manage-apis` | -| List / show API details | `manage-apis` | - -> All integration intents currently route to `manage-apis`, which handles the full API lifecycle (sync, define, build, inspect). - ---- - -## Skills - -All skills owned by this domain. - -| # | Skill | Purpose | Triggers | -|---|-------|---------|----------| -| 1 | `manage-apis` | Sync FDM, add API definitions, build JS clients | API, FDM, sync APIs, add API, build client, OpenAPI, cURL | - -### Skill Locations - -| Skill | Path | -|-------|------| -| `manage-apis` | [`references/manage-apis/SKILL.md`](references/manage-apis/SKILL.md) | - ---- - -## Guard Policies - -Guard policies are constraints that apply across all skills in this domain. They prevent unsafe or incorrect operations. - -> **no-guessing-endpoints:** Never guess API endpoints or service URLs. Mark any unknowns as `TBD` and ask the user for the correct value. - -> **staging-before-live:** API client files must be generated into the staging path (`refs/apis/api-clients/`) first, then promoted to the live path (`code/blocks/form/api-clients/`) only after validation. - ---- - -## File Locations - -Canonical paths for assets managed by skills in this domain. - -| Asset | Path | -|-------|------| -| API clients (live) | `code/blocks/form/api-clients/` | -| API clients (staging) | `refs/apis/api-clients/` | -| API definitions | `refs/apis/` | - ---- - -## Dependencies - -Other domains or skills that this domain's skills may delegate to or depend on. - -| Dependency | Direction | Reason | -|------------|-----------|--------| -| `logic` | `logic` → This domain | Logic domain may call `manage-apis` when creating functions that need API clients | - ---- - -## Plan Integration - -How this domain participates in plan-driven execution. - -| Plan Type | Skill(s) Invoked | Role | -|-----------|-------------------|------| -| Integration plans | `manage-apis` | Syncs API definitions, builds JS API clients, and wires up data integrations | - ---- - -## Extending This Domain - -### Adding a New Skill - -1. Create the skill folder: `references/integration/references/<skill-name>/` -2. Add a `SKILL.md` inside the skill folder — this is the skill's entry point -3. Add the skill to the **Routing Table** above with its intent patterns -4. Add the skill to the **Skills** table and **Skill Locations** table above -5. Register the skill in the domain registry (`domains/SKILL.md`) — both the **Skills Catalog** and **Intent → Domain Routing** tables -6. If the skill manages new file types, add them to the **File Locations** table -7. If needed, add guard policies that apply to the new skill \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/SKILL.md deleted file mode 100644 index fa27ac35..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/SKILL.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -name: manage-apis -description: > - Manages AEM Form Data Model API definitions using the api-manager CLI tool. - Discovers, adds, syncs, and builds OpenAPI 3.0 specs into generated JS clients. - Use when discovering, adding, syncing, or building API definitions and generated clients. - Triggers: api, apis, endpoint, registry, fdm, form data model, sync APIs, build clients, - api-manager, api integration, api client, curl to api. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# API Manager Skill - -Manages API integrations for AEM Forms using OpenAPI 3.0 specifications and the `api-manager` CLI. - -## When to Use - -- User wants to discover, list, or inspect available API integrations -- Adding a new API definition (from scratch, from AEM FDM, or from a cURL command) -- Syncing API specs from an AEM Form Data Model instance -- Building/regenerating JavaScript API clients from YAML specs -- Comparing staging vs deployed API clients -- Troubleshooting API integration issues in forms - -**Do NOT use for:** Writing custom function logic that calls APIs — use the **create-function** skill instead (it covers the async wrapper + `globals.functions.request()` pattern). - -## Critical Rules - -1. **Always use `globals.functions.request()`** — NEVER use `fetch()` directly in AEM Forms -2. **Always `--dry-run` first** — run `build --dry-run` or `sync --dry-run` before actual execution -3. **Staging-then-copy workflow** — generated clients go to `refs/apis/api-clients/` (staging), user manually copies needed clients to `code/blocks/form/api-clients/` -4. **Never fabricate API names or endpoints** — always discover via `list` / `show` or sync from AEM -5. **CLI-first** — always use the `api-manager` CLI for all API operations; do not hand-edit generated files - -## Tool Commands - -| Action | Command | -|--------|---------| -| List all APIs | `api-manager list` | -| List APIs as JSON | `api-manager list --json` | -| Show API details | `api-manager show <name>` | -| Show API as JSON | `api-manager show <name> --json` | -| Build clients (preview) | `api-manager build --dry-run` | -| Build clients | `api-manager build` | -| Add new API | `api-manager add` | -| Sync from AEM (preview) | `api-manager sync --dry-run` | -| Sync from AEM | `api-manager sync` | -| Test for spec changes | `api-manager test` | -| Generate from cURL | `api-skill <curl-command>` | - -### Sync Requirements - -The `sync` command requires environment variables `AEM_HOST` and `AEM_TOKEN` to be set (see Environment section). - -## Workflow - -1. **Discover** — `list` and `show` to inspect existing APIs -2. **Sync or Add** — `sync` from AEM FDM or `add` a new spec manually -3. **Build** — `build --dry-run` first, then `build` to generate JS clients -4. **Compare** — diff staging vs code to see what changed: - ``` - diff -rq refs/apis/api-clients/ code/blocks/form/api-clients/ - ``` -5. **Deploy** — copy needed clients from staging to code directory - -## OpenAPI YAML Template - -Each API is defined as an OpenAPI 3.0 YAML file in `refs/apis/`: - -```yaml -openapi: 3.0.3 - -info: - title: API Name - version: 1.0.0 - description: Brief description - -x-aem-config: - source: local # 'local' or 'aem-api-integration' - executeAtClient: true - encryptionRequired: false - authType: None - isOutputAnArray: false - bodyStructure: requestString # 'requestString', 'none', or custom wrapper - -paths: - /api/endpoint.json: - post: - operationId: apiName - summary: API Display Name - parameters: [] - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/RequestBody' - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/Response' - x-success-condition: response.body?.status?.responseCode === '0' - -components: - schemas: - RequestBody: - type: object - properties: - requestString: - type: object - required: [mobileNumber] - properties: - mobileNumber: - type: string - Response: - type: object - properties: - status: - type: object - properties: - responseCode: - type: string -``` - -### Key Fields - -| Field | Purpose | -|-------|---------| -| `x-aem-config.bodyStructure` | `"requestString"` wraps body in `{ requestString: {...} }`, `"none"` sends flat | -| `x-aem-config.source` | `"local"` for manual, `"aem-api-integration"` for synced | -| `x-success-condition` | JS expression to evaluate success from response | -| `operationId` | Becomes the exported function name in generated client | - -## Generated Client Pattern - -The `build` command generates JavaScript clients like this: - -```javascript -/** - * API Name - Brief description - * @param {Object} params - * @param {string} params.mobileNumber - Customer mobile number [required] - * @param {Object} globals - AEM Forms globals object - * @returns {Promise<Object>} API response - */ -export async function apiName(params, globals) { - if (params.mobileNumber === undefined || params.mobileNumber === null) { - throw new Error('Required parameter "mobileNumber" is missing'); - } - const response = await globals.functions.request({ - url: '/api/endpoint.json', - method: 'POST', - contentType: 'application/json', - body: { requestString: { mobileNumber: params.mobileNumber } } - }); - return response; -} -``` - -## Using APIs in Custom Functions - -Import the generated client and call it from a sync exported wrapper: - -```javascript -import { apiName } from './api-clients'; - -// Internal async helper -async function callApi(mobileNumber, globals) { - const response = await apiName({ mobileNumber }, globals); - if (response.body?.status?.responseCode === '0') { - globals.functions.setProperty(globals.form.result, { value: response.body.data }); - } -} - -// Exported sync wrapper (required for rule editor visibility) -/** - * @name fetchData Fetch Data - * @param {string} mobileNumber - Mobile number - * @param {scope} globals - Globals object - */ -function fetchData(mobileNumber, globals) { - callApi(mobileNumber, globals).catch(function(err) { console.error(err); }); -} - -export { fetchData }; -``` - -**Note:** Generated api-clients are `async` functions — they won't appear in the visual rule editor directly. Always create a sync wrapper (see **create-function** skill for the full pattern). - -## File Structure - -``` -refs/apis/ # Source of truth (OpenAPI 3.0 YAML) -├── _template.yaml # Template for new APIs -├── *.yaml # Individual API specs -└── generated/ - ├── spec/*.yaml # Generated OpenAPI specs (from sync) - ├── api-clients/*.js # Generated JavaScript clients (staging) - └── registry.json # API registry - -code/blocks/form/api-clients/ # Deployed clients (copied from staging) -└── *.js -``` - -## Environment - -Create `.env` in project root for AEM sync: - -``` -AEM_HOST=https://author.aem.example.com -AEM_TOKEN=your-bearer-token -``` - -Both `AEM_HOST` and `AEM_TOKEN` are required for `sync` operations. Other commands (`list`, `show`, `build`, `add`, `test`) work without them. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-api-manager.sh b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-api-manager.sh deleted file mode 100755 index c47788e9..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-api-manager.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env bash -# Eval: API Manager smoke test for manage-apis skill -# Verifies api_manager CLI can be invoked and responds to --help. -# -# Usage: bash skills/manage-apis/eval/eval-api-manager.sh - -set -euo pipefail - -EVAL_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$EVAL_DIR/../../.." && pwd)" -PASS=0; FAIL=0; SKIP=0; TOTAL=0 - -pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo " ✅ $1"; } -fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo " ❌ $1: $2"; } -skip() { SKIP=$((SKIP + 1)); TOTAL=$((TOTAL + 1)); echo " ⏭️ $1 (skipped: $2)"; } - -TMPDIR_EVAL="$(mktemp -d)" -trap 'rm -rf "$TMPDIR_EVAL"' EXIT - -echo "API Manager Eval" -echo "=================" - -# ── Prerequisites ── - -HAS_PYTHON=false -if command -v python3 &>/dev/null; then - pass "Python 3 available ($(python3 --version))" - HAS_PYTHON=true -else - skip "Python 3" "python3 not found in PATH" -fi - -# ── API Manager --help ── - -echo "" -echo "── API Manager (--help) ──" - -if [[ "$HAS_PYTHON" == true ]]; then - STDOUT_FILE="$TMPDIR_EVAL/api_manager_stdout.txt" - STDERR_FILE="$TMPDIR_EVAL/api_manager_stderr.txt" - - CLICK_CHECK=0 - python3 -c "import click" 2>/dev/null || CLICK_CHECK=$? - - if [[ "$CLICK_CHECK" -ne 0 ]]; then - skip "api_manager --help" "click package not installed" - else - EXIT_CODE=0 - PYTHONPATH="$PLUGIN_ROOT/scripts" python3 -m api_manager.cli --help \ - >"$STDOUT_FILE" 2>"$STDERR_FILE" || EXIT_CODE=$? - - if [[ "$EXIT_CODE" -eq 0 ]]; then - pass "api_manager --help exits with code 0" - else - fail "api_manager --help exit code $EXIT_CODE" "$(head -5 "$STDERR_FILE")" - fi - - if grep -qi "api manager\|api-manager\|manage api" "$STDOUT_FILE" 2>/dev/null; then - pass "api_manager --help output contains API Manager reference" - else - fail "api_manager --help output missing API Manager reference" "$(head -5 "$STDOUT_FILE")" - fi - fi -else - skip "api_manager --help" "Python 3 not available" -fi - -# ── Summary ── - -echo "" -echo "════════════════════════════════" -echo " $PASS passed, $FAIL failed, $SKIP skipped ($TOTAL total)" -echo "════════════════════════════════" -[[ "$FAIL" -gt 0 ]] && exit 1 || exit 0 diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-plan.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-plan.md deleted file mode 100644 index e5af43ea..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-plan.md +++ /dev/null @@ -1,24 +0,0 @@ -# manage-apis — Eval Plan - -## Automated - -Run the API Manager smoke test: - -```bash -bash skills/manage-apis/eval/eval-api-manager.sh -``` - -## Manual (E2E) - -### Prompt -> Sync APIs from AEM and show me what's available. - -### Expected Behavior -- Runs `api-manager list` to show existing APIs -- If AEM credentials are set, can `api-manager sync` to fetch from FDM -- Shows API details with `api-manager show <name>` - -### Checklist -- [ ] `api-manager list` works (even with empty result) -- [ ] `api-manager show <name>` works for existing APIs -- [ ] `api-manager build --dry-run` works when specs exist \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api-skill b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api-skill deleted file mode 100755 index 3a3dfcc2..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api-skill +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -e -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../../../../../../.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" "$SCRIPT_DIR/api_skill/cli.py" "$@" diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/__init__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/__init__.py deleted file mode 100644 index 537d45a0..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -"""API Skill generator. - -Generates `refs/apis/<api>.md` documentation from a cURL request and updates -`refs/apis/_index.md`. -""" - -__all__ = ["__version__"] - -__version__ = "0.1.0" - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/__main__.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/__main__.py deleted file mode 100644 index 2f98dd38..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/__main__.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python3 -"""Generate an API reference ("skill") from a cURL request. - -Usage: - python -m tools.api_skill --curl-file <path> [--title <title>] [--out <dir>] - python -m tools.api_skill --curl "<curl ...>" [--title <title>] [--out <dir>] - -This will: - - Create `refs/apis/<slug>.md` based on `refs/apis/_template.md` - - Update `refs/apis/_index.md` by inserting a new row -""" - -from .cli import main - - -if __name__ == "__main__": - raise SystemExit(main()) - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/cli.py b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/cli.py deleted file mode 100644 index 6b6b1149..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts/api_skill/cli.py +++ /dev/null @@ -1,550 +0,0 @@ -#!/usr/bin/env python3 -"""CLI for generating an API ref ("skill") markdown doc from a cURL request.""" - -from __future__ import annotations - -import argparse -import json -import re -import sys -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Dict, Iterable, List, Optional, Tuple -from urllib.parse import parse_qsl, urlparse - - -DEFAULT_REPO_ROOT = Path(__file__).resolve().parents[2] - -# Headers that are generally browser noise; keep docs focused on the integration contract. -NOISY_HEADERS = { - "accept", - "accept-language", - "cache-control", - "pragma", - "priority", - "referer", - "sec-ch-ua", - "sec-ch-ua-mobile", - "sec-ch-ua-platform", - "sec-fetch-dest", - "sec-fetch-mode", - "sec-fetch-site", - "user-agent", - "origin", - "cookie", -} - - -@dataclass(frozen=True) -class ParsedCurl: - method: str - url: str - headers: Dict[str, str] - body_text: Optional[str] - - -def _slugify(value: str) -> str: - value = value.strip().lower() - value = re.sub(r"[^\w\s-]", "", value) - value = re.sub(r"[\s_]+", "-", value) - value = re.sub(r"-{2,}", "-", value) - return value.strip("-") or "api" - - -def _read_text_file(path: Path) -> str: - return path.read_text(encoding="utf-8") - - -def _parse_curl(curl: str) -> ParsedCurl: - """ - Supports patterns similar to `fd-api-integration/src/ApiIntegrationForm.js`. - Not a full shell parser, but robust for typical `curl ... -H 'k: v' --data-raw '...json...'`. - """ - curl = curl.strip() - if not curl: - raise ValueError("Empty cURL input") - - # URL (single-quoted, double-quoted, or bare) - url = None - url_patterns = [ - r"curl(?:\s+--location(?:\s+--globoff)?)?\s+'([^']+)'", - r'curl(?:\s+--location(?:\s+--globoff)?)?\s+"([^"]+)"', - r"curl(?:\s+--location(?:\s+--globoff)?)?\s+(\S+)", - ] - for pat in url_patterns: - m = re.search(pat, curl) - if m: - candidate = m.group(1) - if candidate.startswith("http") or candidate.startswith("/"): - url = candidate - break - if not url: - raise ValueError("Could not find URL in cURL") - - # Method - method = "GET" - m = re.search(r"\s-X\s+(\w+)", curl) - if m: - method = m.group(1).upper() - - # Headers - headers: Dict[str, str] = {} - for hm in re.finditer(r"(?:-H|--header)\s+'([^:]+):\s*([^']*)'", curl): - headers[hm.group(1).strip()] = hm.group(2).strip() - for hm in re.finditer(r'(?:-H|--header)\s+"([^:]+):\s*([^"]*)"', curl): - headers[hm.group(1).strip()] = hm.group(2).strip() - - # Body (raw) - support --data* and -d forms. - body_text = None - data_patterns = [ - r"--data(?:-raw|-binary|-urlencode)?\s+'([\s\S]+?)'", - r'--data(?:-raw|-binary|-urlencode)?\s+"([\s\S]+?)"', - r"-d\s+'([\s\S]+?)'", - r'-d\s+"([\s\S]+?)"', - ] - for pat in data_patterns: - dm = re.findall(pat, curl) - if dm: - # pick the last payload occurrence - body_text = dm[-1] - if not m: # method not explicitly set; curl with data defaults to POST - method = "POST" - break - - return ParsedCurl(method=method, url=url, headers=headers, body_text=body_text) - - -def _header_lookup(headers: Dict[str, str], key: str) -> Optional[str]: - for k, v in headers.items(): - if k.lower() == key.lower(): - return v - return None - - -def _detect_auth(headers: Dict[str, str]) -> str: - auth = _header_lookup(headers, "Authorization") - if auth: - if auth.lower().startswith("basic "): - return "Basic" - if auth.lower().startswith("bearer "): - return "Bearer" - return "Authorization" - if _header_lookup(headers, "X-API-Key") or _header_lookup(headers, "x-api-key"): - return "API Key" - return "None" - - -def _infer_content_type(headers: Dict[str, str], body_text: Optional[str]) -> str: - ct = _header_lookup(headers, "Content-Type") - if ct: - return ct - if body_text: - # default for payloads - return "application/json" - return "application/json" - - -def _split_url(url: str) -> Tuple[str, str, List[Tuple[str, str]]]: - """ - Returns: (path_for_doc, server_hint, query_params) - - path_for_doc: for template URL row (prefer path+query stripped) - - server_hint: origin if absolute, else empty - - query_params: list of (key, value) - """ - p = urlparse(url) - if p.scheme and p.netloc: - path = p.path or "/" - query = list(parse_qsl(p.query, keep_blank_values=True)) - return path, f"{p.scheme}://{p.netloc}", query - # Relative URL - if "?" in url: - path, q = url.split("?", 1) - return path, "", list(parse_qsl(q, keep_blank_values=True)) - return url, "", [] - - -def _json_loads_maybe(s: Optional[str]) -> Optional[Any]: - if not s: - return None - s = s.strip() - if not s: - return None - try: - return json.loads(s) - except Exception: - # Common when a cURL payload is pasted with escaped quotes, e.g. {\"a\":1} - # or doubly-escaped, e.g. {\\\"a\\\":1}. Try a few unescape passes. - candidates: List[str] = [] - - # 1) Replace backslash-escaped quotes once - candidates.append(s.replace('\\"', '"')) - - # 2) Decode escape sequences once/twice (handles \\\" -> \", then \" -> ") - try: - s1 = bytes(s, "utf-8").decode("unicode_escape") - candidates.append(s1) - try: - s2 = bytes(s1, "utf-8").decode("unicode_escape") - candidates.append(s2) - except Exception: - pass - except Exception: - pass - - # 3) Combine: decode then replace quotes - for c in list(candidates): - candidates.append(c.replace('\\"', '"')) - - for cand in candidates: - cand = cand.strip() - if not cand: - continue - try: - return json.loads(cand) - except Exception: - continue - - return None - - -def _type_name(value: Any) -> str: - if value is None: - return "null" - if isinstance(value, bool): - return "boolean" - if isinstance(value, int) and not isinstance(value, bool): - return "integer" - if isinstance(value, float): - return "number" - if isinstance(value, str): - return "string" - if isinstance(value, list): - return "array" - if isinstance(value, dict): - return "object" - return "string" - - -def _flatten_json_for_table(value: Any, prefix: str = "") -> List[Dict[str, str]]: - """ - Produces rows for markdown table: - - Field (dot notation; arrays use `[]`) - - Required (unknown -> Yes for fields present in example) - - Type - - Description (TBD) - """ - rows: List[Dict[str, str]] = [] - - def rec(v: Any, path: str) -> None: - if isinstance(v, dict): - if not v and path: - rows.append({"field": path, "required": "Yes", "type": "object", "desc": "TBD"}) - return - for k, vv in v.items(): - new_path = f"{path}.{k}" if path else str(k) - rec(vv, new_path) - return - - if isinstance(v, list): - array_path = f"{path}[]" if path else "[]" - if not v: - rows.append({"field": array_path, "required": "Yes", "type": "array", "desc": "TBD"}) - return - first = v[0] - if isinstance(first, dict): - # recurse with array item prefix - for k, vv in first.items(): - rec(vv, f"{array_path}.{k}") - else: - rows.append( - { - "field": array_path, - "required": "Yes", - "type": f"array<{_type_name(first)}>", - "desc": "TBD", - } - ) - return - - # primitive - if path: - rows.append({"field": path, "required": "Yes", "type": _type_name(v), "desc": "TBD"}) - - rec(value, prefix) - return rows - - -def _schema_skeleton(value: Any) -> Any: - """ - Create a JSON skeleton with type placeholders (no real values). - """ - if isinstance(value, dict): - return {k: _schema_skeleton(v) for k, v in value.items()} - if isinstance(value, list): - if not value: - return [] - return [_schema_skeleton(value[0])] - t = _type_name(value) - if t == "string": - return "string" - if t == "integer": - return 0 - if t == "number": - return 0.0 - if t == "boolean": - return False - if t == "null": - return None - return "string" - - -def _md_table(rows: Iterable[Iterable[str]], headers: Iterable[str]) -> str: - headers_list = list(headers) - out = [] - out.append("| " + " | ".join(headers_list) + " |") - out.append("|" + "|".join(["-" * (len(h) + 2) for h in headers_list]) + "|") - for r in rows: - out.append("| " + " | ".join(r) + " |") - return "\n".join(out) - - -def _render_api_ref( - *, - title: str, - description: str, - method: str, - url_path: str, - content_type: str, - execute_at_client: bool, - encryption_required: bool, - public_key: Optional[str], - headers: Dict[str, str], - query_params: List[Tuple[str, str]], - request_json: Optional[Any], - response_json: Optional[Any], -) -> str: - # Headers table: hide values; keep names + some inferred descriptions - header_rows: List[List[str]] = [] - for name in sorted(headers.keys(), key=lambda s: s.lower()): - lname = name.lower() - if lname in NOISY_HEADERS: - continue - required = "Yes" if lname in {"content-type", "authorization", "x-api-key"} else "No" - desc = "TBD" - if lname == "authorization": - desc = "Authentication header (Bearer/Basic/etc.)" - elif lname == "content-type": - desc = f"Request content type (e.g. `{content_type}`)" - elif lname == "x-api-key": - desc = "API key for authentication" - header_rows.append([name, required, "string", desc]) - - if _header_lookup(headers, "Content-Type") is None: - header_rows.insert(0, ["Content-Type", "Yes", "string", f"Request content type (e.g. `{content_type}`)"]) - - qp_rows = [[k, "No", "string", (f"`{v}`" if v != "" else ""), "TBD"] for k, v in query_params] - - req_rows = _flatten_json_for_table(request_json) if request_json is not None else [] - - req_schema_block = "" - if request_json is not None: - req_schema_block = "```json\n" + json.dumps(_schema_skeleton(request_json), indent=2) + "\n```" - else: - req_schema_block = "```json\n{}\n```" - - resp_schema_block = "" - resp_rows: List[Dict[str, str]] = [] - if response_json is not None: - resp_rows = _flatten_json_for_table(response_json) - resp_schema_block = "```json\n" + json.dumps(_schema_skeleton(response_json), indent=2) + "\n```" - else: - resp_schema_block = "```json\n{\n \"success\": true,\n \"data\": {}\n}\n```" - - parts = [] - parts.append(f"# {title}\n") - parts.append(description.strip() or "TBD\n") - parts.append("\n## Endpoint\n") - parts.append( - _md_table( - [ - ["Method", f"`{method}`"], - ["URL", f"`{url_path}`"], - ["Content-Type", f"`{content_type}`"], - ], - headers=["Property", "Value"], - ) - + "\n" - ) - parts.append("\n## Execution Info\n") - parts.append( - _md_table( - [ - ["Execute at Client", "Yes" if execute_at_client else "No"], - ["Encryption Required", "Yes" if encryption_required else "No"], - ["Public Key", public_key if (encryption_required and public_key) else "N/A"], - ], - headers=["Property", "Value"], - ) - + "\n" - ) - - parts.append("\n## Headers\n\n") - parts.append( - _md_table( - header_rows if header_rows else [["(none)", "No", "string", ""]], - headers=["Header", "Required", "Type", "Description"], - ) - + "\n" - ) - - parts.append("\n## Query Parameters\n\n") - if qp_rows: - parts.append(_md_table(qp_rows, headers=["Parameter", "Required", "Type", "Default", "Description"]) + "\n") - else: - parts.append("_No query parameters._\n") - - parts.append("\n## Request Body\n\n") - if req_rows: - parts.append( - _md_table( - [[r["field"], r["required"], r["type"], r["desc"]] for r in req_rows], - headers=["Field", "Required", "Type", "Description"], - ) - + "\n" - ) - else: - parts.append("_No request body fields detected from cURL._\n") - - parts.append("\n### Request Schema (JSON)\n\n") - parts.append(req_schema_block + "\n") - - parts.append("\n## Response Body\n\n### Success Response (2xx)\n\n") - if resp_rows: - parts.append( - _md_table( - [[r["field"], r["type"], r["desc"]] for r in resp_rows], - headers=["Field", "Type", "Description"], - ) - + "\n" - ) - parts.append(resp_schema_block + "\n") - - parts.append("\n### Error Response (4xx/5xx)\n\n") - parts.append( - "```json\n{\n \"success\": false,\n \"error\": {\n \"code\": \"TBD\",\n \"message\": \"TBD\",\n \"details\": {}\n }\n}\n```\n" - ) - - parts.append("\n## Notes\n\n- Auth detected from cURL: **" + _detect_auth(headers) + "**\n- Fill in required/optional flags and descriptions once the API contract is confirmed.\n") - - return "".join(parts).rstrip() + "\n" - - -def _update_api_index(index_path: Path, api_title: str, api_file: str, description: str, client_side: bool, encrypted: bool) -> None: - text = _read_text_file(index_path) - lines = text.splitlines() - - marker = "<!-- Add new APIs above this line -->" - try: - idx = lines.index(marker) - except ValueError: - raise RuntimeError(f"Could not find marker in {index_path}: {marker}") - - # Keep description short in index - short_desc = description.strip().splitlines()[0].strip() - if len(short_desc) > 80: - short_desc = short_desc[:77] + "..." - - row = f"| {api_title} | [{api_file}]({api_file}) | {short_desc or 'TBD'} | {'Yes' if client_side else 'No'} | {'Yes' if encrypted else 'No'} |" - - # Avoid duplicate insertion (by file) - for l in lines: - if f"[{api_file}]({api_file})" in l: - return - - lines.insert(idx, row) - index_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8") - - -def main(argv: Optional[List[str]] = None) -> int: - parser = argparse.ArgumentParser(description="Generate API ref markdown from a cURL request.") - src = parser.add_mutually_exclusive_group(required=True) - src.add_argument("--curl", help="cURL command as a single string") - src.add_argument("--curl-file", help="Path to file containing the cURL command") - - parser.add_argument("--repo-root", default=str(DEFAULT_REPO_ROOT), help="Repo root path (default: this workspace)") - parser.add_argument("--out", default="refs/apis", help="Output directory relative to repo root (default: refs/apis)") - parser.add_argument("--title", help="API title (default: '<METHOD> <PATH>')") - parser.add_argument("--description", default="TBD", help="API description text") - parser.add_argument("--name", help="Output base name/slug (default: derived from title/path)") - parser.add_argument("--execute-at-client", choices=["yes", "no"], default="no") - parser.add_argument("--encryption-required", choices=["yes", "no"], default="no") - parser.add_argument("--public-key", help="Public key reference/path to include when encryption-required=yes") - parser.add_argument("--response-file", help="Optional JSON file containing a sample success response") - parser.add_argument("--force", action="store_true", help="Overwrite existing API ref file if it exists") - - args = parser.parse_args(argv) - - repo_root = Path(args.repo_root).expanduser().resolve() - out_dir = (repo_root / args.out).resolve() - out_dir.mkdir(parents=True, exist_ok=True) - - curl_text = args.curl - if args.curl_file: - curl_text = _read_text_file(Path(args.curl_file).expanduser().resolve()) - if not curl_text: - print("ERROR: No cURL provided", file=sys.stderr) - return 2 - - parsed = _parse_curl(curl_text) - url_path, _server_hint, query_params = _split_url(parsed.url) - content_type = _infer_content_type(parsed.headers, parsed.body_text) - - req_json = _json_loads_maybe(parsed.body_text) - resp_json = None - if args.response_file: - resp_path = Path(args.response_file).expanduser().resolve() - resp_json = json.loads(_read_text_file(resp_path)) - - title = args.title - if not title: - title = f"{parsed.method} {url_path}" - - slug = args.name or _slugify(title.replace("/", " ")) - api_filename = f"{slug}.md" - api_path = out_dir / api_filename - - md = _render_api_ref( - title=title, - description=args.description, - method=parsed.method, - url_path=url_path, - content_type=content_type, - execute_at_client=args.execute_at_client == "yes", - encryption_required=args.encryption_required == "yes", - public_key=args.public_key, - headers=parsed.headers, - query_params=query_params, - request_json=req_json, - response_json=resp_json, - ) - - if api_path.exists() and not args.force: - print(f"ERROR: {api_path} already exists. Use --force to overwrite.", file=sys.stderr) - return 1 - - api_path.write_text(md, encoding="utf-8") - - index_path = repo_root / "refs/apis/_index.md" - _update_api_index( - index_path=index_path, - api_title=title, - api_file=api_filename, - description=args.description, - client_side=args.execute_at_client == "yes", - encrypted=args.encryption_required == "yes", - ) - - print(f"Wrote: {api_path}") - print(f"Updated: {index_path}") - return 0 - diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/SKILL.md deleted file mode 100644 index 9fb7c369..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/SKILL.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -name: logic -description: > - Domain router for business-rules & custom-function skills -type: domain -triggers: - - add rule - - show hide - - validate - - navigate - - event - - business logic - - custom function - - calculation - - optimize rules -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Logic — Domain Router - -**ID:** `logic` -**Version:** 0.1 -**Description:** Domain router for business-rules & custom-function skills - -This router does not implement — it delegates. It matches user intents to the correct skill within this domain. - ---- - -## Routing Table - -First match wins. - -| Intent | Examples | Skill | -|--------|----------|-------| -| Add rule | "show/hide", "enable/disable", "set value", "validate", "navigate", "dispatch event", "business logic" | `add-rules` | -| Create custom JS function | "calculation", "API call function", "data transformation" | `create-function` | -| Optimize / refactor rules | "visual vs function split", "rule audit" | `optimize-rules` | - -> If the intent is ambiguous between two skills, present the options to the user and let them choose. - ---- - -## Skills - -All skills owned by this domain. - -| # | Skill | Purpose | Triggers | -|---|-------|---------|----------| -| 1 | `add-rules` | Add business rules (show/hide, validate, navigate, events) | add rule, show hide, validate, navigate, event, business logic | -| 2 | `create-function` | Create custom JS functions (calculations, API calls) | custom function, calculation | -| 3 | `optimize-rules` | Refactor & audit rules (visual vs function split) | optimize rules | - -### Skill Locations - -| Skill | Path | -|-------|------| -| `add-rules` | [`references/add-rules/SKILL.md`](references/add-rules/SKILL.md) | -| `create-function` | [`references/create-function/SKILL.md`](references/create-function/SKILL.md) | -| `optimize-rules` | [`references/optimize-rules/SKILL.md`](references/optimize-rules/SKILL.md) | - ---- - -## Guard Policies - -Guard policies are constraints that apply across all skills in this domain. They prevent unsafe or incorrect operations. - -> **no-direct-rule-edits:** Never edit `.rule.json` / `fd:events` directly. Never invoke `rule-validate`, `rule-save`, `rule-transform` outside `add-rules`. All business logic → `add-rules`. - -> **no-direct-function-writes:** Never write custom-function JS without `create-function`. It ensures JSDoc, exports, and parser compatibility. - ---- - -## File Locations - -Canonical paths for assets managed by skills in this domain. - -| Asset | Path | -|-------|------| -| Rule stores | `repo/content/forms/af/<team>/<path>/<name>.rule.json` | -| Fragment scripts | `code/blocks/form/scripts/fragment/<fragment>.js` | -| Form-level scripts | `code/blocks/form/scripts/form/<form>.js` | -| Shared libraries | `code/blocks/form/scripts/script-libs/libs.js` | - ---- - -## Dependencies - -Other domains or skills that this domain's skills may delegate to or depend on. - -| Dependency | Direction | Reason | -|------------|-----------|--------| -| `build` | `build` → This domain | Form JSON must exist before rules can be added | - ---- - -## Plan Integration - -How this domain participates in plan-driven execution. - -| Plan Type | Skill(s) Invoked | Role | -|-----------|-------------------|------| -| Workflow plans | `add-rules` | Adds visibility, validation, and navigation rules for workflow screens | -| Logic plans | `add-rules`, `create-function` | Adds business rules and creates custom JS functions for calculations/transformations | -| Integration plans | `create-function` | Creates custom JS functions that call API clients | - ---- - -## Extending This Domain - -### Adding a New Skill - -1. Create the skill folder: `references/logic/references/<skill-name>/` -2. Add a `SKILL.md` inside the skill folder — this is the skill's entry point -3. Add the skill to the **Routing Table** above with its intent patterns -4. Add the skill to the **Skills** table and **Skill Locations** table above -5. Register the skill in the domain registry (`domains/SKILL.md`) — both the **Skills Catalog** and **Intent → Domain Routing** tables -6. If the skill manages new file types, add them to the **File Locations** table -7. If needed, add guard policies that apply to the new skill \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/SKILL.md deleted file mode 100644 index 28ae8e7d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/SKILL.md +++ /dev/null @@ -1,315 +0,0 @@ ---- -name: add-rules -description: > - ENTRY POINT for all AEM Forms business logic. Implements visibility, validation, - value computation, navigation, custom functions, events, and more. Routes to - appropriate rule types. Use for show/hide, validate, set value, enable/disable, - calculate, navigate, dispatch event, submit, and any business logic. - Triggers: show/hide, validate, set value, enable/disable, calculate, business logic, - form rules, navigate, dispatch event, submit. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# Form Rules Expert - -You implement all AEM Forms business logic via rules. Every interactive behavior — show/hide, validation, calculations, API calls, navigation — is a rule. - -## Critical Rules - -| Rule | What to Do | -|------|------------| -| **NEVER add unrequested behavior** | Only generate what user asked. If an else branch might help, ASK first. | -| **NEVER add Else without asking** | If user says "Show X when Y", ask before adding hide behavior. | -| **Prefer OPERATORS over functions** | For conditions, use IS_EMPTY, IS_NOT_EMPTY, etc. NOT function calls like isEmpty(). | -| **Prefer DIRECT ACTIONS over functions** | For simple show/hide/enable/disable, use SHOW_STATEMENT, etc. NOT custom functions. | -| **MUST validate before saving** | Run the validator. Fix errors before proceeding. | -| **NEVER invent nodeNames** | Only use nodeNames from the grammar whitelist. See [references/grammar-reference.md](references/grammar-reference.md). | -| **NEVER use $parent references** | `$parent` doesn't resolve in Rule Editor. Use events for cross-fragment communication. | -| **No DOM access in custom functions** | Use `globals`/`scope` only. NEVER use `document`, `window`, jQuery. | -| **Use variables, not hidden fields** | For runtime state, use setVariable/getVariable, not hidden form fields. | - -## Decision: Simple Rule vs Custom Function - -``` -User Requirement - │ - ▼ -┌─────────────────────┐ -│ Can this be done │ -│ with simple actions │ -│ and simple inputs? │ -└─────────────────────┘ - │ - ┌───┴───┐ - YES NO - ↓ ↓ -SIMPLE FUNCTION -RULE RULE -``` - -**Simple Rule (Direct Actions):** -- Show/hide → SHOW_STATEMENT, HIDE_STATEMENT -- Enable/disable → ENABLE_STATEMENT, DISABLE_STATEMENT -- Set/clear value → SET_VALUE_STATEMENT, CLEAR_VALUE_STATEMENT -- Submit, reset, validate → SUBMIT_FORM, RESET_FORM, VALIDATE_FORM -- Navigate → NAVIGATE_TO, NAVIGATE_IN_PANEL -- Set focus → SET_FOCUS -- Dispatch event → DISPATCH_EVENT -- Set variable → SET_VARIABLE - -**Function Rule (FUNCTION_CALL) — only when needed:** -- Arithmetic calculations (a + b * c) -- String concatenation -- API/service calls -- Complex multi-field logic -- Data transformation - -## Action Type Router - -| Action Type | When to Use | -|-------------|-------------| -| Show/Hide | "show X when...", "hide X if...", "toggle visibility" | -| Set/Clear Value | "set value", "clear", "copy value" | -| Enable/Disable | "enable", "disable", "make editable", "make read-only" | -| Submit/Reset/Validate | "submit", "reset", "validate", "save", "clear form" | -| Set Property | "change label", "set placeholder", "make required" | -| Set Variable | "store value", "save to variable", "set flag" | -| Navigate | "go to", "redirect", "next step", "open URL" | -| Add/Remove Instance | "add row", "remove row", "duplicate" | -| Dispatch Event | "fire event", "trigger event", "signal" | -| Validation Check | "is valid", "check validity" | -| Function Call | "calculate", "call API", "sum", "average" | - -For detailed JSON structures of each rule type, see [references/rule-types.md](references/rule-types.md). - -## Workflow - -### Step 1: Understand Requirements - -Parse the user's request into discrete rules: - -``` -**Target:** <field-name> -**Trigger Event:** is initialized | is clicked | is changed | custom:<eventName> -**Condition:** <condition expression or None> -**Actions:** <action list> -**ElseActions:** (only if explicitly requested) -``` - -### Step 1.5: Present Rule Plan - -Present the plan and let user choose: - -> "I've identified N rules. Would you like me to: (1) Show the plan for review, or (2) Implement directly?" - -**If user picks review**, present the rule plan: - -``` -Rule Plan: <Screen/Component Name> -════════════════════════════════════ - -Rule 1: <Short Name> - Component: <fieldName> - Trigger: <event> - Condition: <condition or —> - Actions: <action 1> - <action 2> - Else: <else actions or —> - -Custom Functions Needed: - <functionName> — <purpose> → <file path> -``` - -Wait for user to approve or request changes before proceeding. - -### Step 2: Analyze Form Context - -```bash -# Get component tree with qualified names -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-transform" <form>.form.json - -# Check existing rules on target field -cat <form>.rule.json | jq '.[] | select(.componentName == "<fieldName>")' -``` - -If similar rules exist, inform user and ask if they want to proceed. - -### Step 3: Choose Approach - -- Simple action? → Direct rule (see Action Type Router) -- Complex logic/API? → Write custom function first (use **create-function** skill), then FUNCTION_CALL rule - -### Step 4: Check Existing Functions & APIs (if needed) - -```bash -# Parse custom functions -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/parse-functions" <path-to-functions.js> - -# List available APIs -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/api-manager" list - -# Show API details -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/api-manager" show <apiName> --json -``` - -Do NOT ask the user which API to use if you can find it by searching. - -### Step 5: Generate Rule JSON - -Build the rule following the grammar. See [references/grammar-reference.md](references/grammar-reference.md) for the complete structure reference and [references/rule-types.md](references/rule-types.md) for action-specific patterns. - -**Key grammar rules:** Every CONDITION needs `"nested": false`. Empty condition = `"choice": null`. Literal tokens (When/Then/Else/to/of/on) = `{"nodeName": "X", "value": null}`. FUNCTION_CALL uses `functionName` (object) + `params` (array). No arithmetic nodes — use FUNCTION_CALL instead. - -### Step 6: VALIDATE (Mandatory) - -```bash -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-validate" <rule.json> -``` - -**STOP if errors. Fix before proceeding. NEVER save invalid rules.** - -### Step 7: Save to Rule Store - -```bash -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-save" <rule.json> \ - --rule-store <form>.rule.json \ - --form <form>.form.json -``` - -The tool auto-generates context from form.json (component tree + custom functions). No manual `--context` needed. - -### Step 7.1: If Save Fails - -```bash -# Debug with stack trace -DEBUG=true "${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-save" <rule.json> \ - --rule-store <form>.rule.json --form <form>.form.json -``` - -| Error | Fix | -|-------|-----| -| `Cannot read properties of undefined (reading 'nodeName')` | Wrong item structure — check grammar for correct item order | -| `Field 'X' not found in form` | Field name doesn't exist in form.json — verify field name | - -```bash -# Validate against grammar source of truth -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-grammar" | jq '.<NODE_NAME>' -``` - -### Re-save Existing Rules - -Regenerate `fd:events` for all rules in a rule store: - -```bash -"${CLAUDE_PLUGIN_ROOT}/forms-orchestrator/scripts/rule-save" resave \ - --rule-store <form>.rule.json --form <form>.form.json -``` - -## Complex Request Handling - -### Multiple Actions -When a request includes multiple actions, combine into a single rule with multiple BLOCK_STATEMENTS (preferred) or generate separate rules per action. - -### Conditional Logic (If/Else) -Use TRIGGER_EVENT_SCRIPTS with else block. Both then and else can have multiple BLOCK_STATEMENTS. - -### Chained Rules -When rules need to trigger other rules: first rule dispatches custom event, second rule listens for that event. - -## Cross-Fragment Communication - -Fragments cannot use `$parent`. Instead, use events: - -| Fragment | What It Does | -|----------|--------------| -| Sender | Dispatches event on `globals.form` | -| Receiver | Listens for the custom event, acts on its own fields | - -Any event dispatched on `globals.form` is visible to the **entire form tree** — parent form, sibling fragments, nested child fragments. No special routing needed. - -In rules: use DISPATCH_EVENT action. In custom functions: use `globals.functions.dispatchEvent`. - -## Repeatable Panel Population - -**Array of objects:** Set value to an array where keys match component IDs inside the repeatable panel: -```javascript -globals.functions.setProperty(globals.form.accountDetailsPanel, { - value: [ - { accountNumber: '123', customerId: 'C001', accountType: 'Savings' }, - { accountNumber: '456', customerId: 'C002', accountType: 'Current' } - ] -}); -``` - -**importData (bulk):** Use `globals.functions.importData(data)` for populating multiple fields/panels at once. Requires `FT_FORMS-20002` feature toggle. - -## OOTB Functions Quick Reference - -**Math:** sum, avg, abs, ceil, floor, round, min, max, power, mod, sqrt -**String:** concat, contains, startsWith, endsWith, lower, upper, trim, replace, split, join -**Array:** length, sort, reverse, unique, toArray -**Type:** type, keys, values, toString, toNumber -**Date:** today - -## Tool Commands Summary - -| Tool | Command | -|------|---------| -| Transform form (get tree) | `rule-transform <form>.form.json` | -| Validate rule | `rule-validate <rule.json>` | -| Save rule | `rule-save <rule.json> --rule-store <form>.rule.json --form <form>.form.json` | -| Re-save all rules | `rule-save resave --rule-store <form>.rule.json --form <form>.form.json` | -| Parse functions | `parse-functions <path>` | -| List APIs | `api-manager list` | -| Show API details | `api-manager show <apiName> --json` | - -## Error Recovery - -### "Component not found" -1. Search by partial name in form.json -2. Check for typos or different casing -3. Verify component exists in form structure - -### "Function not found" -1. Check OOTB functions (sum, concat, contains, etc.) -2. Verify custom function file path -3. Parse functions file to confirm function exists - -### "Validation failed" -1. Check nodeNames against whitelist in [references/grammar-reference.md](references/grammar-reference.md) -2. Ensure CONDITION has `"nested": false` -3. Verify literal tokens have `"value": null` -4. Check COMPONENT has all required fields (id, type, name, parent) - -## Rule Examples - -Concrete JSON examples for each rule type are available in [references/examples/](references/examples/): - -| Rule Type | Examples | -|-----------|----------| -| Visibility (show/hide) | [references/examples/visibility/](references/examples/visibility/) | -| Value (set/clear/enable/disable) | [references/examples/value/](references/examples/value/) | -| Form Actions (submit/reset/validate) | [references/examples/form-action/](references/examples/form-action/) | -| Properties (label/placeholder/required) | [references/examples/property/](references/examples/property/) | -| Variables (set/get) | [references/examples/variable/](references/examples/variable/) | -| Navigation (panel/URL) | [references/examples/navigation/](references/examples/navigation/) | -| Repeatable Instances (add/remove) | [references/examples/instance/](references/examples/instance/) | -| Dispatch Events (custom events) | [references/examples/dispatch-event/](references/examples/dispatch-event/) | -| Function Calls (API/calculation) | [references/examples/function/](references/examples/function/) | -| Conditions (boolean/comparison) | [references/examples/conditions/](references/examples/conditions/) | - -Use these as reference when constructing rules. Each file shows the exact JSON structure for that rule type. - -## Review Checklist - -- [ ] Rule JSON valid (ran validator) -- [ ] Field paths exist in form.json -- [ ] Function signatures match parsed custom functions -- [ ] COMPONENT references have correct id, type, name, parent -- [ ] No $parent references -- [ ] Simple operations use direct actions, not FUNCTION_CALL \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-plan.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-plan.md deleted file mode 100644 index 6b94881c..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-plan.md +++ /dev/null @@ -1,29 +0,0 @@ -# add-rules — Eval Plan - -## Automated - -Run the rule tools smoke test: - -```bash -bash skills/add-rules/eval/eval-rule-tools.sh -``` - -## Manual (E2E) - -### Prompt -> Add business rules: when inquiry type is "Support", show the message field. -> When inquiry type changes away from "Support", hide the message field. - -### Expected Behavior -- Runs `rule-transform` to get the component tree -- Creates a rule JSON for visibility toggle -- Validates the rule with `rule-validate` -- Saves the rule with `rule-save` - -### Checklist -- [ ] transform-form was called first to get field qualified names -- [ ] Rule JSON uses correct grammar nodes (IF_ELSE_STATEMENT, CONDITION, etc.) -- [ ] Validator was run BEFORE save -- [ ] Validator reports valid -- [ ] Rule was saved to rule store -- [ ] Rule uses field names from transform-form output (not guessed names) \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-rule-tools.sh b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-rule-tools.sh deleted file mode 100755 index 68c4c774..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-rule-tools.sh +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env bash -# Eval: Rule tool smoke tests for add-rules skill -# Tests transform-form, rule-validate, and save-rule against fixtures. -# -# Usage: bash skills/add-rules/eval/eval-rule-tools.sh - -set -euo pipefail - -EVAL_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$EVAL_DIR/../../.." && pwd)" -FIXTURES="$EVAL_DIR/fixtures" -PASS=0; FAIL=0; SKIP=0; TOTAL=0 - -pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo " ✅ $1"; } -fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo " ❌ $1: $2"; } -skip() { SKIP=$((SKIP + 1)); TOTAL=$((TOTAL + 1)); echo " ⏭️ $1 (skipped: $2)"; } - -TMPDIR_EVAL="$(mktemp -d)" -trap 'rm -rf "$TMPDIR_EVAL"' EXIT - -echo "Rule Tools Eval" -echo "================" - -# ── Prerequisites ── - -HAS_NODE=false -if command -v node &>/dev/null; then - pass "Node.js available ($(node --version))" - HAS_NODE=true -else - skip "Node.js" "node not found in PATH" -fi - -HAS_PYTHON=false -if command -v python3 &>/dev/null; then - pass "Python 3 available ($(python3 --version))" - HAS_PYTHON=true -else - skip "Python 3" "python3 not found in PATH" -fi - -HAS_BRIDGE_MODULES=false -if [[ -d "$PLUGIN_ROOT/scripts/rule_coder/bridge/node_modules" ]]; then - pass "Bridge node_modules installed" - HAS_BRIDGE_MODULES=true -else - skip "Bridge node_modules" "not installed — run: cd scripts/rule_coder/bridge && npm install" -fi - -FIXTURE_FORM_CRISPR="$FIXTURES/sample-contact-crispr.form.json" -FIXTURE_FORM="$FIXTURES/sample-contact.form.json" -FIXTURE_RULE="$FIXTURES/sample-contact.rule.json" - -# ── Transform Form ── - -echo "" -echo "── Transform Form (transform-form.js) ──" - -if [[ "$HAS_NODE" == true && "$HAS_BRIDGE_MODULES" == true && -f "$FIXTURE_FORM_CRISPR" ]]; then - STDOUT_FILE="$TMPDIR_EVAL/transform_stdout.txt" - STDERR_FILE="$TMPDIR_EVAL/transform_stderr.txt" - - EXIT_CODE=0 - node "$PLUGIN_ROOT/scripts/rule_coder/bridge/cli/transform-form.js" "$FIXTURE_FORM_CRISPR" \ - >"$STDOUT_FILE" 2>"$STDERR_FILE" || EXIT_CODE=$? - - if [[ "$EXIT_CODE" -eq 0 ]]; then - pass "transform-form.js exits with code 0" - else - fail "transform-form.js exit code $EXIT_CODE" "$(head -5 "$STDERR_FILE")" - fi - - JSON_CHECK_EXIT=0 - node -e "JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'))" \ - <"$STDOUT_FILE" 2>/dev/null || JSON_CHECK_EXIT=$? - - if [[ "$JSON_CHECK_EXIT" -eq 0 ]]; then - pass "transform-form.js output is valid JSON" - else - fail "transform-form.js output is not valid JSON" "$(head -3 "$STDOUT_FILE")" - fi - - if grep -q '"success": true' "$STDOUT_FILE" 2>/dev/null; then - pass "transform-form.js output contains \"success\": true" - else - fail "transform-form.js output missing success" "$(head -5 "$STDOUT_FILE")" - fi - - if grep -q '"treeJson"' "$STDOUT_FILE" 2>/dev/null; then - pass "transform-form.js output contains \"treeJson\"" - else - fail "transform-form.js output missing treeJson" "$(head -5 "$STDOUT_FILE")" - fi -else - skip "transform-form.js" "prerequisites not met" -fi - -# ── Rule Validator ── - -echo "" -echo "── Rule Validator (Python) ──" - -if [[ "$HAS_PYTHON" == true && -f "$FIXTURE_RULE" ]]; then - STDOUT_FILE="$TMPDIR_EVAL/rule_validator_stdout.txt" - STDERR_FILE="$TMPDIR_EVAL/rule_validator_stderr.txt" - - EXIT_CODE=0 - PYTHONPATH="$PLUGIN_ROOT/scripts" python3 -m rule_coder.validator "$FIXTURE_RULE" \ - >"$STDOUT_FILE" 2>"$STDERR_FILE" || EXIT_CODE=$? - - if [[ "$EXIT_CODE" -eq 0 || "$EXIT_CODE" -eq 1 ]]; then - pass "rule_coder.validator runs without crashing (exit code $EXIT_CODE)" - else - fail "rule_coder.validator crashed with exit code $EXIT_CODE" "$(head -5 "$STDERR_FILE")" - fi - - COMBINED_SIZE=$(( $(wc -c < "$STDOUT_FILE" | tr -d ' ') + $(wc -c < "$STDERR_FILE" | tr -d ' ') )) - if [[ "$COMBINED_SIZE" -gt 0 ]]; then - pass "rule_coder.validator produced output (${COMBINED_SIZE} bytes)" - else - fail "rule_coder.validator produced no output" "expected validation result" - fi -else - skip "rule_coder.validator" "prerequisites not met" -fi - -# ── Save Rule (dry-run) ── - -echo "" -echo "── Save Rule (dry-run) ──" - -if [[ "$HAS_NODE" == true && "$HAS_BRIDGE_MODULES" == true && -f "$FIXTURE_RULE" && -f "$FIXTURE_FORM_CRISPR" ]]; then - STDOUT_FILE="$TMPDIR_EVAL/save_rule_stdout.txt" - STDERR_FILE="$TMPDIR_EVAL/save_rule_stderr.txt" - - EXIT_CODE=0 - node "$PLUGIN_ROOT/scripts/rule_coder/bridge/cli/save-rule.js" \ - "$FIXTURE_RULE" \ - --rule-store /dev/null \ - --form "$FIXTURE_FORM_CRISPR" \ - --dry-run \ - >"$STDOUT_FILE" 2>"$STDERR_FILE" || EXIT_CODE=$? - - COMBINED_OUTPUT="$(cat "$STDOUT_FILE" "$STDERR_FILE" 2>/dev/null)" - if [[ "$EXIT_CODE" -eq 0 ]]; then - pass "save-rule.js --dry-run exits with code 0" - elif [[ -n "$COMBINED_OUTPUT" ]]; then - pass "save-rule.js --dry-run ran (exit $EXIT_CODE, produced output)" - else - fail "save-rule.js --dry-run crashed with exit code $EXIT_CODE" "no output" - fi -else - skip "save-rule.js --dry-run" "prerequisites not met" -fi - -# ── Summary ── - -echo "" -echo "════════════════════════════════" -echo " $PASS passed, $FAIL failed, $SKIP skipped ($TOTAL total)" -echo "════════════════════════════════" -[[ "$FAIL" -gt 0 ]] && exit 1 || exit 0 diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact-crispr.form.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact-crispr.form.json deleted file mode 100644 index bab94723..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact-crispr.form.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "fieldType": "form", - "title": "Contact Us", - "fd:version": "2.1", - "items": [ - { - "fieldType": "panel", - "name": "contactInfoPanel", - "jcr:title": "Contact Information", - "items": [ - { - "fieldType": "text-input", - "name": "fullName", - "jcr:title": "Full Name", - "required": true, - "colspan": "6", - "minLength": 2, - "maxLength": 50 - }, - { - "fieldType": "email", - "name": "email", - "jcr:title": "Email", - "required": true, - "colspan": "6" - }, - { - "fieldType": "telephone-input", - "name": "phone", - "jcr:title": "Phone", - "required": false, - "colspan": "6" - } - ] - }, - { - "fieldType": "panel", - "name": "inquiryPanel", - "jcr:title": "Inquiry Details", - "items": [ - { - "fieldType": "drop-down", - "name": "inquiryType", - "jcr:title": "Inquiry Type", - "required": true, - "enum": ["General", "Support", "Sales"], - "enumNames": ["General", "Support", "Sales"] - }, - { - "fieldType": "text-input", - "name": "message", - "jcr:title": "Message", - "required": true, - "multiLine": true, - "minLength": 10 - } - ] - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact.form.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact.form.json deleted file mode 100644 index 069ee2a1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact.form.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "fd/franklin/components/form/v1/form", - "fieldType": "form", - "fd:version": "2.1", - "title": "Contact Us", - "contactInfoPanel": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/panelcontainer/v1/panelcontainer", - "fieldType": "panel", - "name": "contactInfoPanel", - "jcr:title": "Contact Information", - "fullName": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/textinput/v1/textinput", - "fieldType": "text-input", - "name": "fullName", - "jcr:title": "Full Name", - "required": true, - "colspan": "6", - "minLength": 2, - "minLengthMessage": "Minimum 2 characters required", - "maxLength": 50, - "maxLengthMessage": "Maximum 50 characters allowed", - "mandatoryMessage": "Full Name is required" - }, - "email": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/emailinput/v1/emailinput", - "fieldType": "email", - "name": "email", - "jcr:title": "Email", - "required": true, - "colspan": "6", - "mandatoryMessage": "Email is required" - }, - "phone": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/telephoneinput/v1/telephoneinput", - "fieldType": "telephone-input", - "name": "phone", - "jcr:title": "Phone", - "required": false, - "colspan": "6" - } - }, - "inquiryPanel": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/panelcontainer/v1/panelcontainer", - "fieldType": "panel", - "name": "inquiryPanel", - "jcr:title": "Inquiry Details", - "inquiryType": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/dropdown/v1/dropdown", - "fieldType": "drop-down", - "name": "inquiryType", - "jcr:title": "Inquiry Type", - "required": true, - "enum": ["General", "Support", "Sales"], - "enumNames": ["General", "Support", "Sales"], - "mandatoryMessage": "Please select an inquiry type" - }, - "message": { - "jcr:primaryType": "nt:unstructured", - "sling:resourceType": "core/fd/components/form/textinput/v1/textinput", - "fieldType": "text-input", - "name": "message", - "jcr:title": "Message", - "required": true, - "multiLine": true, - "minLength": 10, - "minLengthMessage": "Message must be at least 10 characters", - "mandatoryMessage": "Message is required" - } - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact.rule.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact.rule.json deleted file mode 100644 index 8edd36e3..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/fixtures/sample-contact.rule.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "550e8400-e29b-41d4-a716-446655440000": { - "componentPath": "inquiryPanel/inquiryType", - "componentName": "inquiryType", - "fd:rules": { - "jcr:primaryType": "nt:unstructured", - "fd:change": [ - { - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Show Message Required Alert", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "IF_ELSE_STATEMENT", - "condition": { - "nodeName": "CONDITION", - "items": [ - { - "nodeName": "COMPARISON_EXPRESSION", - "left": { - "nodeName": "FIELD_REFERENCE", - "value": "inquiryType" - }, - "operator": "EQUALS", - "right": { - "nodeName": "STRING_LITERAL", - "value": "Support" - } - } - ] - }, - "thenClause": { - "nodeName": "THEN_CLAUSE", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "SHOW_STATEMENT", - "field": { - "nodeName": "FIELD_REFERENCE", - "value": "message" - } - } - } - ] - } - } - } - ] - } - ] - } - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/boolean-and.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/boolean-and.json deleted file mode 100644 index a8d04f43..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/boolean-and.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_description": "AND condition: customerType equals 'Business' AND revenue > 100000", - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "BOOLEAN_BINARY_EXPRESSION", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerType", - "displayName": "Customer Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "customerType", - "parent": "$form.main" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Business" - } - } - ] - } - }, - { - "nodeName": "BOOLEAN_BINARY_OPERATOR", - "choice": { - "nodeName": "AND", - "value": null - } - }, - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.revenue", - "displayName": "Annual Revenue", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/Financial/", - "name": "revenue", - "parent": "$form.financial" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "GREATER_THAN", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "NUMERIC_LITERAL", - "value": 100000 - } - } - ] - } - } - ] - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/boolean-or.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/boolean-or.json deleted file mode 100644 index 12e14209..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/boolean-or.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_description": "OR condition: status equals 'Approved' OR status equals 'Pending'", - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "BOOLEAN_BINARY_EXPRESSION", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.status", - "displayName": "Status", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "status", - "parent": "$form.main" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Approved" - } - } - ] - } - }, - { - "nodeName": "BOOLEAN_BINARY_OPERATOR", - "choice": { - "nodeName": "OR", - "value": null - } - }, - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.status", - "displayName": "Status", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "status", - "parent": "$form.main" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Pending" - } - } - ] - } - } - ] - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/comparison-equals.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/comparison-equals.json deleted file mode 100644 index c5b04337..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/comparison-equals.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "_description": "Simple equals comparison: customerType equals 'Business'", - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerType", - "displayName": "Customer Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "customerType", - "parent": "$form.main" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Business" - } - } - ] - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/comparison-unary.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/comparison-unary.json deleted file mode 100644 index cb557833..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/conditions/comparison-unary.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "_description": "Unary comparison: email is not empty (no right operand)", - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.email", - "displayName": "Email", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Contact/", - "name": "email", - "parent": "$form.contact" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "IS_NOT_EMPTY", - "value": null - } - } - ] - } -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/dispatch-event/fire-custom-event.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/dispatch-event/fire-custom-event.json deleted file mode 100644 index 378f694f..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/dispatch-event/fire-custom-event.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "_description": "Dispatch a custom 'processComplete' event on the form when Process button is clicked", - "_natural_language": "When Process button is clicked, dispatch 'processComplete' on form", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Fire Process Complete Event", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.processButton", - "displayName": "Process Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Process Button/", - "name": "processButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "DISPATCH_EVENT", - "items": [ - { - "nodeName": "STRING_LITERAL", - "value": "processComplete" - }, - { - "nodeName": "on", - "value": null - }, - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form", - "displayName": "FORM", - "type": "FORM", - "displayPath": "FORM/", - "name": "FORM", - "parent": "", - "metadata": { - "isAncestorRepeatable": false - } - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/reset-panel.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/reset-panel.json deleted file mode 100644 index f02bf954..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/reset-panel.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_description": "Reset the contact details panel when Clear button is clicked", - "_natural_language": "When Clear button is clicked, reset contactDetails panel", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Reset Contact Details", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.clearButton", - "displayName": "Clear Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Clear Button/", - "name": "clearButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "RESET_FORM", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.contactDetails", - "displayName": "Contact Details", - "type": "AFCOMPONENT|PANEL", - "isDuplicate": false, - "displayPath": "FORM/Contact Details/", - "name": "contactDetails", - "parent": "$form" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/submit-form.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/submit-form.json deleted file mode 100644 index a5bffadb..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/submit-form.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_description": "Submit the form when Submit button is clicked", - "_natural_language": "When Submit button is clicked, submit form", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Submit Form", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.submitButton", - "displayName": "Submit Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Submit Button/", - "name": "submitButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SUBMIT_FORM", - "items": [] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/validate-field.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/validate-field.json deleted file mode 100644 index 68fb8d8a..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/form-action/validate-field.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_description": "Validate the email field when it loses focus (value changes)", - "_natural_language": "When email field is changed, validate email field", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Validate Email on Change", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactDetails.email", - "displayName": "Email", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/ContactDetails/Email", - "name": "email", - "parent": "$form.contactDetails" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "VALIDATE_FORM", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.contactDetails.email", - "displayName": "Email", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/ContactDetails/Email", - "name": "email", - "parent": "$form.contactDetails" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/api-call/rule.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/api-call/rule.json deleted file mode 100644 index e23d522d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/api-call/rule.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "_description": "Call a custom API function when form is initialized to fetch customer data", - "_natural_language": "When form is initialized, call fetchCustomerDetails(customerId)", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Fetch Customer Details on Load", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form", - "displayName": "FORM", - "type": "FORM", - "displayPath": "FORM/", - "name": "FORM", - "parent": "", - "metadata": { - "isAncestorRepeatable": false - } - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is initialized" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "FUNCTION_CALL", - "parentNodeName": "BLOCK_STATEMENT", - "functionName": { - "id": "fetchCustomerDetails", - "displayName": "Fetch Customer Details", - "type": "VOID", - "isDuplicate": false, - "displayPath": "", - "args": [ - { - "type": "STRING", - "name": "customerId", - "description": "Customer ID to fetch", - "isMandatory": true - }, - { - "type": "scope", - "name": "globals", - "description": "Globals object for setting values", - "isMandatory": true - } - ], - "impl": "$0($1, $2)" - }, - "params": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "1" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/calculation/rule.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/calculation/rule.json deleted file mode 100644 index c28245ca..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/calculation/rule.json +++ /dev/null @@ -1,156 +0,0 @@ -{ - "_description": "Calculate total by calling sum function and set result to total field", - "_natural_language": "When Calculate button is clicked, set total to sum(item1, item2, item3)", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Calculate Total", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.calculateButton", - "displayName": "Calculate Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Actions/", - "name": "calculateButton", - "parent": "$form.actions" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_VALUE_STATEMENT", - "items": [ - { - "nodeName": "VALUE_FIELD", - "value": { - "id": "$form.total", - "displayName": "Total", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/Summary/", - "name": "total", - "parent": "$form.summary" - } - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "FUNCTION_CALL", - "parentNodeName": "EXPRESSION", - "functionName": { - "id": "sum", - "displayName": "Sum", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "", - "args": [ - { - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "name": "values", - "description": "Numbers to sum", - "isMandatory": true - } - ], - "impl": "$0($1)" - }, - "params": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.item1", - "displayName": "Item 1", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/Items/", - "name": "item1", - "parent": "$form.items" - } - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.item2", - "displayName": "Item 2", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/Items/", - "name": "item2", - "parent": "$form.items" - } - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.item3", - "displayName": "Item 3", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/Items/", - "name": "item3", - "parent": "$form.items" - } - } - } - ] - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/common-mistakes.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/common-mistakes.md deleted file mode 100644 index 384a28fa..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/function/common-mistakes.md +++ /dev/null @@ -1,270 +0,0 @@ -# FUNCTION_CALL — Common Mistakes - -These errors cause `rule-save` to fail with cryptic messages like `"getChoiceModel is not a function"`. Use this reference to diagnose and fix them. - -## Quick Reference - -| Mistake | What happens | Fix | -|---------|-------------|-----| -| **Missing `choice` wrapper on params** | Param becomes a `TerminalModel` instead of `ChoiceModel`, crashes the transformer | Every param MUST be `{ "nodeName": "EXPRESSION", "choice": { ... } }` — never put `value` directly on the param | -| **Missing `description` in args** | Validation fails during preprocessing | Every arg needs all 4 fields: `{ "type", "name", "description", "isMandatory" }` | -| **Missing `isMandatory` in args** | Validation fails during preprocessing | Set `"isMandatory": true` (or `false` for optional params) on every arg | -| **Wrong `displayPath` format** | Component lookup fails | Format is `"FORM/panelName/"` — traces from form root to the component's parent panel. Use `""` for functions | -| **Missing `impl` in functionName** | Transform produces no output | Use positional pattern: `"$0($1, $2)"` for 2-param function | -| **`params` count ≠ `args` count** | Validation rejects the rule | `params` array must have exactly one entry per `args` entry | -| **Param without `nodeName`** | Model factory can't determine type | Every param needs `"nodeName": "EXPRESSION"` | -| **Missing `displayPath` on functionName** | Inconsistent behavior | For custom/OOTB functions, set `"displayPath": ""` (empty string) | -| **COMPONENT value missing fields** | Crash during type filtering or transform | Every COMPONENT value needs: `id`, `displayName`, `type`, `isDuplicate`, `displayPath`, `name`, `parent`, `metadata` | - ---- - -## 1. Param missing `choice` wrapper - -This is the **#1 cause** of the `getChoiceModel is not a function` crash. - -### ❌ Wrong - -```json -{ - "nodeName": "EXPRESSION", - "value": { "id": "$form.panel.field", "name": "field", "type": "STRING" } -} -``` - -The model factory sees `value` → creates a `TerminalModel` → which has no `getChoiceModel()` method → crash. - -### ✅ Correct - -```json -{ - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.panel.field", - "displayName": "field", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/panel/", - "name": "field", - "parent": "$form.panel", - "metadata": {} - } - } -} -``` - -The `choice` wrapper tells the model factory to create a `ChoiceModel`, which has the `getChoiceModel()` method the transformer expects. - ---- - -## 2. Args missing `description` and `isMandatory` - -### ❌ Wrong - -```json -"args": [ - { "type": "STRING", "name": "custId" } -] -``` - -### ✅ Correct - -```json -"args": [ - { "type": "STRING", "name": "custId", "description": "Customer ID", "isMandatory": true } -] -``` - -Every entry in `functionName.args` requires all four fields. The `preprocessFunctionCallTypes` validation checks for this and will reject the rule with a clear error if any are missing. - ---- - -## 3. Wrong `displayPath` format - -### ❌ Wrong - -```json -{ - "id": "$form.personalInfo.firstName", - "displayName": "firstName", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "displayPath": "personalInfo", - "name": "firstName", - "parent": "$form.personalInfo" -} -``` - -### ✅ Correct - -```json -{ - "id": "$form.personalInfo.firstName", - "displayName": "firstName", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/personalInfo/", - "name": "firstName", - "parent": "$form.personalInfo", - "metadata": {} -} -``` - -`displayPath` format: `"FORM/<panel1>/<panel2>/"` — starts with `FORM`, includes each ancestor panel, ends with `/`. For the form root itself, use `"FORM/"`. For function names (not components), use `""`. - ---- - -## 4. Missing or wrong `impl` pattern - -### ❌ Wrong - -```json -"functionName": { - "id": "calculateTotal", - "displayName": "Calculate Total", - "type": "NUMBER", - "args": [ - { "type": "NUMBER", "name": "price", "description": "Item price", "isMandatory": true }, - { "type": "NUMBER", "name": "qty", "description": "Quantity", "isMandatory": true } - ] -} -``` - -Missing `impl` — the transformer won't know how to compose the function call. - -### ✅ Correct - -```json -"functionName": { - "id": "calculateTotal", - "displayName": "Calculate Total", - "type": "NUMBER", - "isDuplicate": false, - "displayPath": "", - "args": [ - { "type": "NUMBER", "name": "price", "description": "Item price", "isMandatory": true }, - { "type": "NUMBER", "name": "qty", "description": "Quantity", "isMandatory": true } - ], - "impl": "$0($1, $2)" -} -``` - -`impl` rules: -- `$0` = function name (replaced by `functionName.id`) -- `$1`, `$2`, ... = parameters in order -- 0 params: `"$0()"` -- 1 param: `"$0($1)"` -- 2 params: `"$0($1, $2)"` -- 3 params: `"$0($1, $2, $3)"` - ---- - -## 5. Literal value params — wrong wrapper - -### ❌ Wrong - -```json -{ - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "choice": "Hello" - } -} -``` - -Literals use `value`, not `choice`, inside the inner node. - -### ✅ Correct - -```json -{ - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Hello" - } -} -``` - -The outer param always has `choice`. The inner literal node has `value`. Don't confuse the two levels. - ---- - -## 6. Params count mismatch - -### ❌ Wrong — function declares 2 args but provides 1 param - -```json -"functionName": { - "id": "concat", - "args": [ - { "type": "STRING", "name": "a", "description": "First", "isMandatory": true }, - { "type": "STRING", "name": "b", "description": "Second", "isMandatory": true } - ], - "impl": "$0($1, $2)" -}, -"params": [ - { "nodeName": "EXPRESSION", "choice": { "nodeName": "STRING_LITERAL", "value": "hello" } } -] -``` - -### ✅ Correct — params count matches args count - -```json -"params": [ - { "nodeName": "EXPRESSION", "choice": { "nodeName": "STRING_LITERAL", "value": "hello" } }, - { "nodeName": "EXPRESSION", "choice": { "nodeName": "STRING_LITERAL", "value": " world" } } -] -``` - ---- - -## 7. COMPONENT value missing required fields - -### ❌ Wrong — minimal component - -```json -{ - "nodeName": "COMPONENT", - "value": { - "id": "$form.panel.field", - "name": "field" - } -} -``` - -### ✅ Correct — complete component - -```json -{ - "nodeName": "COMPONENT", - "value": { - "id": "$form.panel.field", - "displayName": "field", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/panel/", - "name": "field", - "parent": "$form.panel", - "metadata": {} - } -} -``` - -All 8 fields are required: `id`, `displayName`, `type`, `isDuplicate`, `displayPath`, `name`, `parent`, `metadata`. - ---- - -## Debugging Tips - -1. **Run with DEBUG=true** to get stack traces: - ``` - DEBUG=true rule-save <rule.json> --rule-store <form>.rule.json --form <form>.form.json - ``` - -2. **Validate first** — always run `rule-validate` before `rule-save`. It catches structural issues earlier. - -3. **Check the grammar** — use `rule-grammar | jq '.FUNCTION_CALL'` to see the expected node structure. - -4. **Compare with working examples** — see [api-call/rule.json](api-call/rule.json) and [calculation/rule.json](calculation/rule.json) for known-good FUNCTION_CALL structures. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/instance/add-instance.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/instance/add-instance.json deleted file mode 100644 index 6d2ea38e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/instance/add-instance.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_description": "Add a new row to a repeatable contact panel when Add Row button is clicked", - "_natural_language": "When Add Row button is clicked, add instance of contactRows", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Add Contact Row", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactSection[getRelativeInstanceIndex($form.contactSection)].addRowButton", - "displayName": "Add Row Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/ContactSection/Add Row Button", - "name": "addRowButton", - "parent": "$form.contactSection[getRelativeInstanceIndex($form.contactSection)]" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "ADD_INSTANCE", - "items": [ - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "REPEATABLE_COMPONENT", - "value": { - "id": "$form.contactSection", - "displayName": "ContactSection", - "type": "AFCOMPONENT|PANEL", - "isDuplicate": false, - "displayPath": "FORM/ContactSection/", - "name": "contactSection", - "parent": "$form" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/instance/remove-instance.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/instance/remove-instance.json deleted file mode 100644 index 6444d028..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/instance/remove-instance.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_description": "Remove a row from a repeatable contact panel when Remove button is clicked", - "_natural_language": "When Remove button is clicked, remove instance of contactRows", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Remove Contact Row", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactSection[getRelativeInstanceIndex($form.contactSection)].removeButton", - "displayName": "Remove Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/ContactSection/Remove Button", - "name": "removeButton", - "parent": "$form.contactSection[getRelativeInstanceIndex($form.contactSection)]" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "REMOVE_INSTANCE", - "items": [ - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "REPEATABLE_COMPONENT", - "value": { - "id": "$form.contactSection", - "displayName": "Contact Rows", - "type": "AFCOMPONENT|PANEL", - "isDuplicate": false, - "displayPath": "FORM/ContactSection/", - "name": "contactRows", - "parent": "$form" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/navigation/navigate-panel.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/navigation/navigate-panel.json deleted file mode 100644 index 568ba0cd..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/navigation/navigate-panel.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_description": "Navigate to the next step in a wizard panel when Next button is clicked", - "_natural_language": "When Next button is clicked, navigate to next item of wizardPanel", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Go to Next Step", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.wizardPanel.nextButton", - "displayName": "Next Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/WizardPanel/Next Button/", - "name": "nextButton", - "parent": "$form.wizardPanel" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "NAVIGATE_IN_PANEL", - "items": [ - { - "nodeName": "PANEL_FOCUS_OPTION", - "choice": { - "nodeName": "NEXT_ITEM", - "value": null - } - }, - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "PANEL", - "value": { - "id": "$form.wizardPanel", - "displayName": "Wizard Panel", - "type": "AFCOMPONENT|PANEL", - "isDuplicate": false, - "displayPath": "FORM/Wizard Panel/", - "name": "wizardPanel", - "parent": "$form" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/navigation/navigate-url.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/navigation/navigate-url.json deleted file mode 100644 index c41d2555..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/navigation/navigate-url.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_description": "Navigate to a help URL in a new tab when Help button is clicked", - "_natural_language": "When Help button is clicked, navigate to 'https://help.example.com' in new tab", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Open Help Page", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.helpButton", - "displayName": "Help Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Help Button/", - "name": "helpButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "NAVIGATE_TO", - "items": [ - { - "nodeName": "NAVIGATE_TO_EXPRESSION", - "choice": { - "nodeName": "URL_LITERAL", - "value": "https://help.example.com" - } - }, - { - "nodeName": "in", - "value": null - }, - { - "nodeName": "NAVIGATE_METHOD_OPTIONS", - "choice": { - "nodeName": "NEW_TAB", - "value": null - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-label.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-label.json deleted file mode 100644 index 7634d35e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-label.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "_description": "Change the label of email field to 'Business Email' when form is initialized", - "_natural_language": "When form is initialized, set label of email to 'Business Email'", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "version": 0, - "eventName": "Set Business Email Label", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactDetails.email", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "name": "email" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is initialized" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_PROPERTY", - "items": [ - { - "nodeName": "MEMBER_EXPRESSION", - "items": [ - { - "nodeName": "PROPERTY_LIST", - "value": "label.value" - }, - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactDetails.email", - "displayName": "Email", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/ContactDetails/Email/", - "name": "email", - "parent": "$form.contactDetails" - } - } - ] - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXTENDED_EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Business Email" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-placeholder.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-placeholder.json deleted file mode 100644 index 8411c884..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-placeholder.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "_description": "Set placeholder of input field dynamically based on selected document type", - "_natural_language": "When documentType is changed, set placeholder of documentNumber to value of documentType", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Dynamic Placeholder", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.documentType", - "displayName": "Document Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/DocumentType/", - "name": "documentType", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_PROPERTY", - "items": [ - { - "nodeName": "MEMBER_EXPRESSION", - "items": [ - { - "nodeName": "PROPERTY_LIST", - "value": { - "displayName": "placeholder" - } - }, - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.documentNumber", - "displayName": "Document Number", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/DocumentNumber/", - "name": "documentNumber", - "parent": "$form" - } - } - ] - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXTENDED_EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.documentType", - "displayName": "Document Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/DocumentType/", - "name": "documentType", - "parent": "$form" - } - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-required.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-required.json deleted file mode 100644 index f75f332e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/property/set-required.json +++ /dev/null @@ -1,198 +0,0 @@ -{ - "_description": "Make phone field required when 'Contact by Phone' checkbox is checked", - "_natural_language": "When contactPreference is changed, if contactPreference equals 'phone', set required of phoneNumber to true, else set required of phoneNumber to false", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Phone Required When Selected", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactPreference", - "displayName": "Contact Preference", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/ContactPreference/", - "name": "contactPreference", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.contactPreference", - "displayName": "Contact Preference", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/ContactPreference/", - "name": "contactPreference", - "parent": "$form" - } - }, - { - "nodeName": "COMPARISON_OPERATOR", - "value": "is equal to" - }, - { - "nodeName": "STRING_LITERAL", - "value": "phone" - } - ] - } - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_PROPERTY", - "items": [ - { - "nodeName": "MEMBER_EXPRESSION", - "items": [ - { - "nodeName": "PROPERTY_LIST", - "value": { - "displayName": "required" - } - }, - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.phoneNumber", - "displayName": "Phone Number", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/PhoneNumber/", - "name": "phoneNumber", - "parent": "$form" - } - } - ] - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXTENDED_EXPRESSION", - "choice": { - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "True", - "value": null - } - } - } - ] - } - } - ] - }, - { - "nodeName": "ELSE_BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "Else", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_PROPERTY", - "items": [ - { - "nodeName": "MEMBER_EXPRESSION", - "items": [ - { - "nodeName": "PROPERTY_LIST", - "value": { - "displayName": "required" - } - }, - { - "nodeName": "of", - "value": null - }, - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.phoneNumber", - "displayName": "Phone Number", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/PhoneNumber/", - "name": "phoneNumber", - "parent": "$form" - } - } - ] - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXTENDED_EXPRESSION", - "choice": { - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "False", - "value": null - } - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/clear-on-change.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/clear-on-change.json deleted file mode 100644 index 5bdecedb..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/clear-on-change.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_description": "Clear the state field when country field changes", - "_natural_language": "When country is changed, clear state", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Clear State on Country Change", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.addressSection.country", - "displayName": "Country", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/AddressSection/Country/", - "name": "country", - "parent": "$form.addressSection" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "CLEAR_VALUE_STATEMENT", - "items": [ - { - "nodeName": "VALUE_FIELD", - "value": { - "id": "$form.addressSection.state", - "displayName": "State", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/AddressSection/State/", - "name": "state", - "parent": "$form.addressSection" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/enable-disable.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/enable-disable.json deleted file mode 100644 index cac9ac53..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/enable-disable.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "_description": "Enable adult options when age is greater than 17, otherwise disable them", - "_natural_language": "When age is changed, if age is greater than 17 then enable adultOptions, else disable adultOptions", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Enable Adult Options Based on Age", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.personalInfo.age", - "displayName": "Age", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/PersonalInfo/Age/", - "name": "age", - "parent": "$form.personalInfo" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.personalInfo.age", - "displayName": "Age", - "type": "AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER", - "isDuplicate": false, - "displayPath": "FORM/PersonalInfo/Age/", - "name": "age", - "parent": "$form.personalInfo" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "GREATER_THAN", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "NUMERIC_LITERAL", - "value": 17 - } - } - ] - } - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "ENABLE_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.adultOptions", - "displayName": "Adult Options", - "type": "AFCOMPONENT|PANEL", - "isDuplicate": false, - "displayPath": "FORM/Options/", - "name": "adultOptions", - "parent": "$form.options" - } - } - ] - } - } - ] - }, - { - "nodeName": "Else", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "DISABLE_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.adultOptions", - "displayName": "Adult Options", - "type": "AFCOMPONENT|PANEL", - "isDuplicate": false, - "displayPath": "FORM/Options/", - "name": "adultOptions", - "parent": "$form.options" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/set-from-field.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/set-from-field.json deleted file mode 100644 index ed99a71e..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/set-from-field.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_description": "Copy value from one field to another when Copy button is clicked", - "_natural_language": "When Copy button is clicked, set shippingAddress to billingAddress", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Copy Billing to Shipping", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.addressSection.copyAddressButton", - "displayName": "Copy Address Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/AddressSection/Copy Address Button/", - "name": "copyAddressButton", - "parent": "$form.addressSection" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_VALUE_STATEMENT", - "items": [ - { - "nodeName": "VALUE_FIELD", - "value": { - "id": "$form.addressSection.shippingAddress", - "displayName": "Shipping Address", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/AddressSection/Shipping Address/", - "name": "shippingAddress", - "parent": "$form.addressSection" - } - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.addressSection.billingAddress", - "displayName": "Billing Address", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/AddressSection/Billing Address/", - "name": "billingAddress", - "parent": "$form.addressSection" - } - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/set-value-literal.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/set-value-literal.json deleted file mode 100644 index ad41e7dc..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/value/set-value-literal.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_description": "Set field value to a literal string when button is clicked", - "_natural_language": "When resetButton is clicked, set status to 'Pending'", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Reset Status", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.resetButton", - "displayName": "Reset Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Reset Button/", - "name": "resetButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_VALUE_STATEMENT", - "items": [ - { - "nodeName": "VALUE_FIELD", - "value": { - "id": "$form.main.status", - "displayName": "Status", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/Status/", - "name": "status", - "parent": "$form.main" - } - }, - { - "nodeName": "to", - "value": null - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Pending" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/variable/set-variable.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/variable/set-variable.json deleted file mode 100644 index 1b1793f5..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/variable/set-variable.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "_description": "Set a boolean variable 'formSubmitted' to true on the form when Submit button is clicked", - "_natural_language": "When Submit button is clicked, set variable 'formSubmitted' to true on form", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Set Form Submitted Flag", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.submitButton", - "displayName": "Submit Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Submit Button/", - "name": "submitButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": null - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_VARIABLE", - "items": [ - { - "nodeName": "key", - "value": null - }, - { - "nodeName": "VARIABLE_NAME", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "formSubmitted" - } - }, - { - "nodeName": "value", - "value": null - }, - { - "nodeName": "VARIABLE_VALUE", - "choice": { - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "True", - "value": null - } - } - }, - { - "nodeName": "on", - "value": null - }, - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form", - "displayName": "FORM", - "type": "FORM", - "displayPath": "FORM/", - "name": "FORM", - "parent": "", - "metadata": { - "isAncestorRepeatable": false - } - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/variable/use-variable-condition.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/variable/use-variable-condition.json deleted file mode 100644 index 2860d792..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/variable/use-variable-condition.json +++ /dev/null @@ -1,140 +0,0 @@ -{ - "_description": "Check if variable 'formSubmitted' is true before allowing re-submit", - "_natural_language": "When ReSubmit button is clicked, if variable 'formSubmitted' from form equals true, show alreadySubmittedMessage", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Check Already Submitted", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.resubmitButton", - "displayName": "Re-Submit Button", - "type": "AFCOMPONENT|FIELD|BUTTON", - "isDuplicate": false, - "displayPath": "FORM/Re-Submit Button/", - "name": "resubmitButton", - "parent": "$form" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "GET_VARIABLE", - "items": [ - { - "nodeName": "key", - "value": null - }, - { - "nodeName": "VARIABLE_NAME", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "formSubmitted" - } - }, - { - "nodeName": "from", - "value": null - }, - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form", - "displayName": "FORM", - "type": "FORM", - "displayPath": "FORM/", - "name": "FORM", - "parent": "", - "metadata": { - "isAncestorRepeatable": false - } - } - } - ] - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "True", - "value": null - } - } - } - ] - } - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SHOW_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.messages.alreadySubmittedMessage", - "displayName": "Already Submitted Message", - "type": "AFCOMPONENT|STATIC TEXT|STRING", - "isDuplicate": false, - "displayPath": "FORM/Messages/Already Submitted Message/", - "name": "alreadySubmittedMessage", - "parent": "$form.messages" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/hide-multiple-fields.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/hide-multiple-fields.json deleted file mode 100644 index c07e583d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/hide-multiple-fields.json +++ /dev/null @@ -1,128 +0,0 @@ -{ - "_description": "Hide multiple fields (companyName and companyAddress) when isIndividual checkbox is checked", - "_natural_language": "When isIndividual checkbox is changed, if it is true then hide companyName and hide companyAddress", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Hide Company Fields for Individual", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerInfo.isIndividual", - "displayName": "Is Individual", - "type": "AFCOMPONENT|FIELD||BOOLEAN", - "isDuplicate": false, - "displayPath": "FORM/CustomerInfo/Is Individual/", - "name": "isIndividual", - "parent": "$form.customerInfo" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerInfo.isIndividual", - "displayName": "Is Individual", - "type": "AFCOMPONENT|FIELD||BOOLEAN", - "isDuplicate": false, - "displayPath": "FORM/CustomerInfo/Is Individual/", - "name": "isIndividual", - "parent": "$form.customerInfo" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "IS_TRUE", - "value": null - } - } - ] - } - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "HIDE_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.customerInfo.companyName", - "displayName": "Company Name", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/CustomerInfo/Company Name/", - "name": "companyName", - "parent": "$form.customerInfo" - } - } - ] - } - }, - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "HIDE_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.customerInfo.companyAddress", - "displayName": "Company Address", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/CustomerInfo/Company Address/", - "name": "companyAddress", - "parent": "$form.customerInfo" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/show-hide-with-else.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/show-hide-with-else.json deleted file mode 100644 index 808d31fb..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/show-hide-with-else.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "_description": "Show/hide panel based on condition with else block", - "_natural_language": "When customerType is changed, if it equals 'Business' then show companyName, else hide companyName", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Toggle Company Name", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerType", - "displayName": "Customer Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "customerType", - "parent": "$form.main" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerType", - "displayName": "Customer Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "customerType", - "parent": "$form.main" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Business" - } - } - ] - } - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SHOW_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.companyName", - "displayName": "Company Name", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "companyName", - "parent": "$form.main" - } - } - ] - } - } - ] - }, - { - "nodeName": "Else", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "HIDE_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.companyName", - "displayName": "Company Name", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "companyName", - "parent": "$form.main" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/show-on-dropdown.json b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/show-on-dropdown.json deleted file mode 100644 index bf06932a..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/examples/visibility/show-on-dropdown.json +++ /dev/null @@ -1,115 +0,0 @@ -{ - "_description": "Show companyName panel when customerType dropdown equals 'Business'", - "_natural_language": "When customerType is changed, if it equals 'Business' then show companyName", - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Show Company Name", - "items": [ - { - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerType", - "displayName": "Customer Type", - "type": "AFCOMPONENT|FIELD|DROPDOWN|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "customerType", - "parent": "$form.main" - } - }, - { - "nodeName": "TRIGGER_EVENT", - "value": "is changed" - }, - { - "nodeName": "When", - "value": null - }, - { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.customerType", - "displayName": "Customer Type", - "type": "STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "customerType", - "parent": "$form.main" - } - } - }, - { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - { - "nodeName": "EXPRESSION", - "choice": { - "nodeName": "STRING_LITERAL", - "value": "Business" - } - } - ] - } - }, - { - "nodeName": "Then", - "value": null - }, - { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SHOW_STATEMENT", - "items": [ - { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.companyName", - "displayName": "Company Name", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Main/", - "name": "companyName", - "parent": "$form.main" - } - } - ] - } - } - ] - } - ] - } - ] - } - ] - } - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/grammar-reference.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/grammar-reference.md deleted file mode 100644 index 1f7eda22..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/grammar-reference.md +++ /dev/null @@ -1,510 +0,0 @@ -# Grammar Reference - -**Source of truth:** `tools/rule_coder/grammar/annotated_subset_grammar.json` — Read this file directly when: (1) a rule fails validation or save, (2) you're unsure about a node's structure, or (3) the action type isn't covered below. - ---- - -## Grammar Rules - -| Rule | Details | -|------|---------| -| **CONDITION nested** | Every CONDITION must have `"nested": false` property | -| **Empty condition** | No condition = `"choice": null`, NOT `"choice": {}` | -| **Literal tokens** | When/Then/Else/to/of/on/key/value/from/in = `{"nodeName": "X", "value": null}` | -| **FUNCTION_CALL** | Uses `functionName` (object) + `params` (array), NOT `value.args` | -| **No arithmetic nodes** | For `a + b * c`, use FUNCTION_CALL, NOT BINARY_EXPRESSION | -| **Trigger ≠ Condition** | Trigger event (click/change) is separate from conditions. Never combine them with AND/OR. | -| **VARIABLE transparency** | When a node has rule `VARIABLE`, do NOT create a VARIABLE node. Put the actual value directly in the parent node. | -| **Else is optional** | Only include Else block and second BLOCK_STATEMENTS when else actions are explicitly mentioned. | - ---- - -## Master Rule JSON Structure - -All rules follow this pattern: `ROOT → STATEMENT → TRIGGER_SCRIPTS → SINGLE_TRIGGER_SCRIPTS` - -```json -{ - "nodeName": "ROOT", - "isValid": true, - "enabled": true, - "eventName": "Descriptive Event Name", - "items": [{ - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [{ - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - { /* 1. COMPONENT — what triggers the rule */ }, - { /* 2. TRIGGER_EVENT — the event type */ }, - { "nodeName": "When", "value": null }, - { /* 4. TRIGGER_EVENT_SCRIPTS — condition + actions */ } - ] - }] - } - }] -} -``` - -### TRIGGER_EVENT_SCRIPTS (with else) - -```json -{ - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { /* CONDITION */ }, - { "nodeName": "Then", "value": null }, - { /* BLOCK_STATEMENTS (then actions) */ }, - { "nodeName": "Else", "value": null }, - { /* BLOCK_STATEMENTS (else actions) */ } - ] -} -``` - -### TRIGGER_EVENT_SCRIPTS (without else) - -```json -{ - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - { /* CONDITION */ }, - { "nodeName": "Then", "value": null }, - { /* BLOCK_STATEMENTS (then actions) */ } - ] -} -``` - ---- - -## COMPONENT Structure - -Used as trigger component (nodeName `COMPONENT`), action target (nodeName `AFCOMPONENT` or `VALUE_FIELD`), or panel reference (nodeName `PANEL`). - -```json -{ - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.panel.fieldName", - "displayName": "Field Display Name", - "type": "AFCOMPONENT", - "isDuplicate": false, - "displayPath": "FORM/panel/", - "name": "fieldName", - "parent": "$form.panel", - "metadata": {} - } -} -``` - -**Component type variants:** - -| nodeName | When to Use | type field | -|----------|------------|------------| -| `COMPONENT` | Trigger component (item 1 in SINGLE_TRIGGER_SCRIPTS) | Full type from treeJson (e.g. `AFCOMPONENT\|FIELD\|TEXT FIELD\|STRING`) | -| `AFCOMPONENT` | Action targets (show/hide/enable/disable/dispatch/variable) | `AFCOMPONENT` | -| `VALUE_FIELD` | Set value / clear value targets | Full type from treeJson (e.g. `AFCOMPONENT\|FIELD\|NUMBER FIELD\|NUMBER`) | -| `PANEL` | Panel navigation targets | `AFCOMPONENT\|PANEL` | -| `REPEATABLE_COMPONENT` | Add/remove instance targets | `AFCOMPONENT` | - -**Fields:** -- `id` — Qualified path: `$form.panel.fieldName` -- `displayName` — Human-readable name -- `type` — Component type string from treeJson -- `isDuplicate` — `false` (set `true` only if duplicate names exist) -- `displayPath` — Breadcrumb path: `FORM/panel/` -- `name` — Component name (last segment of id) -- `parent` — Parent qualified path: `$form.panel` -- `metadata` — `{}` (empty object) - ---- - -## TRIGGER_EVENT Options - -### Field-Level Events - -| Event Value | Valid For | Description | -|-------------|-----------|-------------| -| `is clicked` | Button only | When component is clicked | -| `is changed` | Input fields (text, number, date, checkbox, file) | When field value changes (Value Commit) | -| `is initialized` | Any component, form | When component initializes/loads | - -### Form Root Node Events - -| Event Value | Description | -|-------------|-------------| -| `is submitted successfully` | Successful form submission | -| `submission fails` | Error in submission | -| `is saved successfully` | Form saved successfully | -| `fails to save` | Error while saving the form | - -### Custom Events - -Any string not matching a standard event is treated as a custom event name: - -```json -{ "nodeName": "TRIGGER_EVENT", "value": "custom:myEventName" } -``` - -**Note:** `is blurred` and `is focused` are NOT valid OOTB events. Use `is changed` for validation on value commit. - ---- - -## Condition Structure - -### CONDITION Node - -```json -{ - "nodeName": "CONDITION", - "nested": false, - "choice": { /* COMPARISON_EXPRESSION or BOOLEAN_BINARY_EXPRESSION or null */ } -} -``` - -**Empty condition (always execute):** - -```json -{ - "nodeName": "CONDITION", - "nested": false, - "choice": null -} -``` - -### COMPARISON_EXPRESSION (Single Comparison) - -Binary comparison (field equals value): - -```json -{ - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { "nodeName": "COMPONENT", "value": { "id": "...", "name": "..." } } - }, - { - "nodeName": "OPERATOR", - "choice": { "nodeName": "EQUALS_TO", "value": null } - }, - { - "nodeName": "EXPRESSION", - "choice": { "nodeName": "STRING_LITERAL", "value": "someValue" } - } - ] -} -``` - -Unary comparison (field is empty — **NO right EXPRESSION**): - -```json -{ - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { - "nodeName": "EXPRESSION", - "choice": { "nodeName": "COMPONENT", "value": { "id": "...", "name": "..." } } - }, - { - "nodeName": "OPERATOR", - "choice": { "nodeName": "IS_EMPTY", "value": null } - } - ] -} -``` - -### BOOLEAN_BINARY_EXPRESSION (AND/OR) - -Combines two conditions: - -```json -{ - "nodeName": "BOOLEAN_BINARY_EXPRESSION", - "items": [ - { - "nodeName": "CONDITION", - "nested": false, - "choice": { "nodeName": "COMPARISON_EXPRESSION", "items": [ /* ... */ ] } - }, - { - "nodeName": "BOOLEAN_BINARY_OPERATOR", - "choice": { "nodeName": "AND", "value": null } - }, - { - "nodeName": "CONDITION", - "nested": false, - "choice": { "nodeName": "COMPARISON_EXPRESSION", "items": [ /* ... */ ] } - } - ] -} -``` - -For 3+ conditions, nest BOOLEAN_BINARY_EXPRESSIONs: left side is a CONDITION wrapping another BOOLEAN_BINARY_EXPRESSION, right side is the new condition. - ---- - -## Expression Types - -Expressions appear inside COMPARISON_EXPRESSION items and as values in SET_VALUE_STATEMENT, SET_VARIABLE, etc. - -```json -{ - "nodeName": "EXPRESSION", - "choice": { /* one of the types below */ } -} -``` - -| Expression Type | choice.nodeName | choice.value | Example | -|-----------------|-----------------|--------------|---------| -| Form field | `COMPONENT` | `{ "id": "...", "name": "...", ... }` | Reference to a form component | -| String | `STRING_LITERAL` | `"hello world"` | Text value | -| Number | `NUMERIC_LITERAL` | `42` or `10.5` | Numeric value | -| Boolean | `BOOLEAN_LITERAL` | N/A — uses nested choice | true/false | -| Date | `DATE_LITERAL` | `"2024-01-15"` | ISO date string | -| Function result | `FUNCTION_CALL` | `{ functionName: {...}, params: [...] }` | Calculated value | -| UTM parameter | `UTM_PARAMETER` | `"utm_source"` | UTM tracking param | -| Query parameter | `QUERY_PARAMETER` | `"paramName"` | URL query param | -| Browser details | `BROWSER_DETAILS` | `"userAgent"` / `"language"` / `"platform"` | Browser info | -| URL details | `URL_DETAILS` | `"hostname"` / `"pathname"` | URL components | -| Stored variable | `GET_VARIABLE` | N/A — uses items array | Retrieved variable | - -### BOOLEAN_LITERAL (Nested Choice Pattern) - -BOOLEAN_LITERAL is a CHOICE node, not a terminal. It wraps True/False: - -```json -{ - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "True", - "value": null - } -} -``` - -```json -{ - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "False", - "value": null - } -} -``` - -### GET_VARIABLE (Sequence) - -GET_VARIABLE is a SEQUENCE with 4 items: - -```json -{ - "nodeName": "GET_VARIABLE", - "items": [ - { "nodeName": "key", "value": null }, - { "nodeName": "STRING_LITERAL", "value": "myVariableName" }, - { "nodeName": "from", "value": null }, - { "nodeName": "AFCOMPONENT", "value": { "id": "...", "name": "..." } } - ] -} -``` - ---- - -## Conditions: Operators vs Functions - -**ALWAYS prefer built-in operators over function calls:** - -| User Says | Use Operator | NOT This | -|-----------|-------------|----------| -| "is empty", "is blank" | `IS_EMPTY` | ~~isEmpty(field)~~ | -| "is not empty", "has value" | `IS_NOT_EMPTY` | ~~!isEmpty(field)~~ | -| "is true", "is checked" | `IS_TRUE` | ~~field == true~~ | -| "is false", "is unchecked" | `IS_FALSE` | ~~field == false~~ | -| "equals", "is", "same as" | `EQUALS_TO` | — | -| "not equals", "!=" | `NOT_EQUALS_TO` | — | -| "contains", "includes" | `CONTAINS` | ~~contains(field, val)~~ | -| "starts with", "begins with" | `STARTS_WITH` | — | -| "ends with" | `ENDS_WITH` | — | -| "greater than", ">" | `GREATER_THAN` | — | -| "less than", "<" | `LESS_THAN` | — | -| "is valid" | `IS_VALID` | — | -| "is not valid", "invalid" | `IS_NOT_VALID` | — | -| "is before" (date) | `IS_BEFORE` | — | -| "is after" (date) | `IS_AFTER` | — | -| "has selected" (multi-select) | `HAS_SELECTED` | — | - ---- - -## Full Operator Catalog - -### Binary Operators (13) — Require Left + Right EXPRESSION - -| nodeName | Natural Language | Notes | -|----------|-----------------|-------| -| `EQUALS_TO` | equals, is equal to, is, same as | Any type | -| `NOT_EQUALS_TO` | not equals, is not equal to, !=, different from | Any type | -| `GREATER_THAN` | greater than, more than, > | Numeric | -| `LESS_THAN` | less than, smaller than, < | Numeric | -| `GREATER_THAN_OR_EQUAL` | greater than or equal, >=, at least | Numeric | -| `LESS_THAN_OR_EQUAL` | less than or equal, <=, at most | Numeric | -| `CONTAINS` | contains, includes | String | -| `DOES_NOT_CONTAIN` | does not contain, excludes | String | -| `STARTS_WITH` | starts with, begins with | String | -| `ENDS_WITH` | ends with, finishes with | String | -| `IS_BEFORE` | is before, before | Date comparison | -| `IS_AFTER` | is after, after | Date comparison | -| `HAS_SELECTED` | has selected, selected | Multi-select / checkbox group | - -All binary operators use this pattern: - -```json -{ - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { "nodeName": "EXPRESSION", "choice": { /* left operand */ } }, - { "nodeName": "OPERATOR", "choice": { "nodeName": "EQUALS_TO", "value": null } }, - { "nodeName": "EXPRESSION", "choice": { /* right operand */ } } - ] -} -``` - -### Unary Operators (6) — NO Right EXPRESSION - -| nodeName | Natural Language | Notes | -|----------|-----------------|-------| -| `IS_EMPTY` | is empty, is blank, has no value | Any field | -| `IS_NOT_EMPTY` | is not empty, has value, is filled | Any field | -| `IS_TRUE` | is true, is checked | Boolean / checkbox | -| `IS_FALSE` | is false, is unchecked | Boolean / checkbox | -| `IS_VALID` | is valid, valid | Validation check | -| `IS_NOT_VALID` | is not valid, invalid | Validation check | - -All unary operators use this pattern (only 2 items, no right EXPRESSION): - -```json -{ - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - { "nodeName": "EXPRESSION", "choice": { /* left operand */ } }, - { "nodeName": "OPERATOR", "choice": { "nodeName": "IS_EMPTY", "value": null } } - ] -} -``` - -### Boolean Combinators (AND/OR) - -Used in BOOLEAN_BINARY_EXPRESSION to combine conditions. NOT placed in COMPARISON_EXPRESSION. - -| nodeName | Natural Language | -|----------|-----------------| -| `AND` | and, && | -| `OR` | or, \|\| | - -```json -{ - "nodeName": "BOOLEAN_BINARY_OPERATOR", - "choice": { "nodeName": "AND", "value": null } -} -``` - ---- - -## BLOCK_STATEMENTS / BLOCK_STATEMENT - -Actions live inside BLOCK_STATEMENTS (array of BLOCK_STATEMENT nodes): - -```json -{ - "nodeName": "BLOCK_STATEMENTS", - "items": [ - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SHOW_STATEMENT", - "items": [ /* action-specific items */ ] - } - }, - { - "nodeName": "BLOCK_STATEMENT", - "choice": { - "nodeName": "SET_VALUE_STATEMENT", - "items": [ /* action-specific items */ ] - } - } - ] -} -``` - -Each BLOCK_STATEMENT selects exactly one action type as its choice. Multiple actions = multiple BLOCK_STATEMENT entries in the items array. - ---- - -## Valid NodeNames Whitelist - -**ONLY use these exact nodeNames. NEVER invent new ones.** - -### Structure Nodes - -`ROOT`, `STATEMENT`, `TRIGGER_SCRIPTS`, `SINGLE_TRIGGER_SCRIPTS`, `TRIGGER_EVENT_SCRIPTS`, `TRIGGER_EVENT`, `CONDITION`, `COMPARISON_EXPRESSION`, `BOOLEAN_BINARY_EXPRESSION`, `EXPRESSION`, `EXTENDED_EXPRESSION`, `OPERATOR`, `BOOLEAN_BINARY_OPERATOR`, `BLOCK_STATEMENTS`, `BLOCK_STATEMENT` - -### Literal Token Nodes - -`When`, `Then`, `Else`, `to`, `of`, `in`, `on`, `key`, `value`, `from` - -All literal tokens have the same shape: `{ "nodeName": "<token>", "value": null }` - -### Component Type Nodes - -`COMPONENT`, `AFCOMPONENT`, `VALUE_FIELD`, `PANEL`, `REPEATABLE_COMPONENT` - -### Literal Value Nodes - -`STRING_LITERAL`, `NUMERIC_LITERAL`, `BOOLEAN_LITERAL`, `DATE_LITERAL`, `URL_LITERAL` - -### Boolean Literal Choice Nodes - -`True`, `False` - -### Operator Nodes (Binary) - -`EQUALS_TO`, `NOT_EQUALS_TO`, `GREATER_THAN`, `LESS_THAN`, `GREATER_THAN_OR_EQUAL`, `LESS_THAN_OR_EQUAL`, `CONTAINS`, `DOES_NOT_CONTAIN`, `STARTS_WITH`, `ENDS_WITH`, `IS_BEFORE`, `IS_AFTER`, `HAS_SELECTED` - -### Operator Nodes (Unary) - -`IS_EMPTY`, `IS_NOT_EMPTY`, `IS_TRUE`, `IS_FALSE`, `IS_VALID`, `IS_NOT_VALID` - -### Boolean Combinator Nodes - -`AND`, `OR` - -### Action Nodes - -`SHOW_STATEMENT`, `HIDE_STATEMENT`, `SET_VALUE_STATEMENT`, `CLEAR_VALUE_STATEMENT`, `ENABLE_STATEMENT`, `DISABLE_STATEMENT`, `SET_FOCUS`, `DISPATCH_EVENT`, `FUNCTION_CALL`, `SET_PROPERTY`, `RESET_FORM`, `VALIDATE_FORM`, `SUBMIT_FORM`, `SAVE_FORM`, `NAVIGATE_TO`, `ADD_INSTANCE`, `REMOVE_INSTANCE`, `NAVIGATE_IN_PANEL`, `SET_VARIABLE` - -### Navigation Sub-Nodes - -`NAVIGATE_TO_EXPRESSION`, `NAVIGATE_METHOD_OPTIONS`, `NEW_WINDOW`, `NEW_TAB`, `SAME_TAB`, `PANEL_FOCUS_OPTION`, `NEXT_ITEM`, `PREVIOUS_ITEM`, `FIRST_ITEM` - -### Property Sub-Nodes - -`MEMBER_EXPRESSION`, `PROPERTY_LIST` - -### Variable Sub-Nodes - -`VARIABLE_NAME`, `VARIABLE_VALUE`, `GET_VARIABLE`, `SET_VARIABLE` - -### Context Expression Nodes - -`UTM_PARAMETER`, `QUERY_PARAMETER`, `BROWSER_DETAILS`, `URL_DETAILS` - ---- - -## Not Supported - -The following are NOT in the subset grammar. Do not use them: - -| Category | Names | Alternative | -|----------|-------|-------------| -| Actions | `WSDL_STATEMENT`, `ASYNC_FUNCTION_CALL` | Use `FUNCTION_CALL` with custom functions | -| Expressions | `BINARY_EXPRESSION`, `STRING_BINARY_EXPRESSION`, `ARITHMETIC_EXPRESSION` | Use `FUNCTION_CALL` for calculations | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/rule-types.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/rule-types.md deleted file mode 100644 index 6e9604f1..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/add-rules/references/rule-types.md +++ /dev/null @@ -1,369 +0,0 @@ -# Rule Types Reference - -Compact structural reference for all action types in AEM Forms rules. Each action is wrapped in a `BLOCK_STATEMENT` node. For complete JSON examples, see the [examples/](examples/) directory. - ---- - -## COMPONENT Value Template - -Every time a rule references a form component (AFCOMPONENT, VALUE_FIELD, COMPONENT, PANEL, REPEATABLE_COMPONENT), use this structure: - -```json -{ - "id": "$form.panelName.fieldName", - "displayName": "fieldName", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/panelName/", - "name": "fieldName", - "parent": "$form.panelName", - "metadata": {} -} -``` - -| Field | Format | Notes | -|-------|--------|-------| -| `id` | `$form.panel.field` | Dot-separated path from form root | -| `displayName` | `fieldName` | Last segment of the id | -| `type` | `AFCOMPONENT\|FIELD\|TEXT FIELD\|STRING` | Pipe-separated type chain from `rule-transform` output | -| `isDuplicate` | `false` | Set `true` only if multiple components share the same name | -| `displayPath` | `FORM/panelName/` | Slash-separated ancestor path, always starts with `FORM`, ends with `/` | -| `name` | `fieldName` | Component name (matches form.json) | -| `parent` | `$form.panelName` | Parent component id | -| `metadata` | `{}` | Usually empty object | - -> **Tip:** Run `rule-transform <form>.form.json` to get exact values for every component. - ---- - -## Literal Tokens - -Some actions use literal keyword tokens as items. These always have `"value": null`: - -```json -{ "nodeName": "to", "value": null } -{ "nodeName": "of", "value": null } -{ "nodeName": "on", "value": null } -{ "nodeName": "in", "value": null } -{ "nodeName": "key", "value": null } -{ "nodeName": "value", "value": null } -{ "nodeName": "from", "value": null } -``` - ---- - -## 1. SHOW_STATEMENT / HIDE_STATEMENT - -Show or hide a form component. - -| Property | Value | -|----------|-------| -| **Items** | `[AFCOMPONENT]` | -| **Component type** | `AFCOMPONENT` | -| **Examples** | [visibility/show-on-dropdown.json](examples/visibility/show-on-dropdown.json), [visibility/show-hide-with-else.json](examples/visibility/show-hide-with-else.json), [visibility/hide-multiple-fields.json](examples/visibility/hide-multiple-fields.json) | - -HIDE_STATEMENT is identical — just change the `nodeName`. - -> **Tip:** For simple show/hide, always use these direct actions. Do NOT use FUNCTION_CALL. - ---- - -## 2. SET_VALUE_STATEMENT - -Set a field's value. - -| Property | Value | -|----------|-------| -| **Items** | `[VALUE_FIELD, "to", EXPRESSION]` | -| **Component type** | `VALUE_FIELD` (uses full type chain, e.g. `AFCOMPONENT\|FIELD\|TEXT FIELD\|STRING`) | -| **EXPRESSION options** | `NUMERIC_LITERAL`, `STRING_LITERAL`, `BOOLEAN_LITERAL`, `COMPONENT` (from another field), `FUNCTION_CALL` (computed), `GET_VARIABLE` | -| **Examples** | [value/set-value-literal.json](examples/value/set-value-literal.json), [value/set-from-field.json](examples/value/set-from-field.json), [value/enable-disable.json](examples/value/enable-disable.json), [value/clear-on-change.json](examples/value/clear-on-change.json) | - -> **Note:** VALUE_FIELD uses the full type from treeJson (e.g. `AFCOMPONENT|FIELD|TEXT FIELD|STRING`), while AFCOMPONENT in show/hide uses just `AFCOMPONENT`. - ---- - -## 3. CLEAR_VALUE_STATEMENT - -Clear a field's value. - -| Property | Value | -|----------|-------| -| **Items** | `[VALUE_FIELD]` | -| **Examples** | [value/clear-on-change.json](examples/value/clear-on-change.json) | - ---- - -## 4. ENABLE_STATEMENT / DISABLE_STATEMENT - -Enable or disable a form component. - -| Property | Value | -|----------|-------| -| **Items** | `[AFCOMPONENT]` | -| **Examples** | [value/enable-disable.json](examples/value/enable-disable.json) | - -DISABLE_STATEMENT is identical — just change the `nodeName`. - ---- - -## 5. SET_VARIABLE - -Store a variable value on a component. **6 items** in strict order. - -| Property | Value | -|----------|-------| -| **Items** | `["key", VARIABLE_NAME, "value", VARIABLE_VALUE, "on", AFCOMPONENT]` | -| **Examples** | [variable/set-variable.json](examples/variable/set-variable.json), [variable/use-variable-condition.json](examples/variable/use-variable-condition.json) | - -**VARIABLE_NAME options:** `STRING_LITERAL`, `AFCOMPONENT`, `FUNCTION_CALL`, `GET_VARIABLE` - -**VARIABLE_VALUE options:** `STRING_LITERAL`, `NUMERIC_LITERAL`, `BOOLEAN_LITERAL`, `AFCOMPONENT`, `FUNCTION_CALL`, `GET_VARIABLE` - -> **Critical:** All 6 items must be present in exactly this order. The literal tokens `key`, `value`, and `on` must have `"value": null`. - ---- - -## 6. GET_VARIABLE - -Retrieve a stored variable. Used inside EXPRESSION (not as a standalone action). - -| Property | Value | -|----------|-------| -| **Items** | `["key", VARIABLE_NAME, "from", AFCOMPONENT]` | -| **Examples** | [variable/use-variable-condition.json](examples/variable/use-variable-condition.json) | - -GET_VARIABLE is typically used inside SET_VALUE_STATEMENT as the EXPRESSION, or inside a CONDITION. - ---- - -## 7. DISPATCH_EVENT - -Fire a custom event on a component. - -| Property | Value | -|----------|-------| -| **Items** | `[STRING_LITERAL, "on", AFCOMPONENT]` | -| **Event format** | `"custom:eventName"` | -| **Examples** | [dispatch-event/fire-custom-event.json](examples/dispatch-event/fire-custom-event.json) | - -**Listening for the event:** On the receiver side, use the custom event name as the TRIGGER_EVENT value: - -```json -{ "nodeName": "TRIGGER_EVENT", "value": "custom:paymentComplete" } -``` - -> **Cross-fragment communication:** Dispatch events on `$form` (the form root). Any component in the entire form tree can listen for events dispatched on the form root. - ---- - -## 8. FUNCTION_CALL - -Call a custom or OOTB function. Uses `functionName` (object) + `params` (array). - -| Property | Value | -|----------|-------| -| **Examples** | [function/api-call/rule.json](examples/function/api-call/rule.json), [function/calculation/rule.json](examples/function/calculation/rule.json) | -| **Common mistakes** | [function/common-mistakes.md](examples/function/common-mistakes.md) | - -### functionName object (required fields) - -| Field | Type | Description | -|-------|------|-------------| -| `id` | string | Function identifier (e.g. `"concat"`, `"fetchCustomer"`) | -| `displayName` | string | Display name for rule editor | -| `type` | string | Return type (`STRING`, `NUMBER`, `DATE`, `BOOLEAN`, `OBJECT`) | -| `isDuplicate` | boolean | Usually `false` | -| `displayPath` | string | `""` for custom/OOTB functions | -| `args` | array | Function signature — each entry: `{ "type", "name", "description", "isMandatory" }` | -| `impl` | string | Positional pattern: `"$0($1, $2)"` — `$0` = function id, `$1`+ = params | - -### params array - -Each param must be wrapped in EXPRESSION with `choice`: - -```json -{ "nodeName": "EXPRESSION", "choice": { "nodeName": "COMPONENT", "value": { ... } } } -{ "nodeName": "EXPRESSION", "choice": { "nodeName": "STRING_LITERAL", "value": "hello" } } -``` - -> **NEVER** put `value` directly on the param — always use the `choice` wrapper. Missing `choice` causes `"getChoiceModel is not a function"` crash. - -### parentNodeName rules - -| Context | parentNodeName | -|---------|----------------| -| Direct action in BLOCK_STATEMENT | `"BLOCK_STATEMENT"` | -| Value source in EXPRESSION | `"EXPRESSION"` | -| Value source in EXTENDED_EXPRESSION | `"EXTENDED_EXPRESSION"` | -| Inside VARIABLE_VALUE | `"VARIABLE_VALUE"` | -| Inside VARIABLE_NAME | `"VARIABLE_NAME"` | -| Inside NAVIGATE_TO_EXPRESSION | `"NAVIGATE_TO_EXPRESSION"` | - -### impl pattern - -| Params | impl | -|--------|------| -| 0 | `"$0()"` | -| 1 | `"$0($1)"` | -| 2 | `"$0($1, $2)"` | -| 3 | `"$0($1, $2, $3)"` | - -> **Critical:** `params` count must equal `args` count. `args` is the signature definition; `params` is the actual values. NEVER put arguments inside `functionName.args` at runtime. - ---- - -## 9. NAVIGATE_TO - -Navigate to a URL. - -| Property | Value | -|----------|-------| -| **Items** | `[NAVIGATE_TO_EXPRESSION, "in", NAVIGATE_METHOD_OPTIONS]` | -| **Examples** | [navigation/navigate-url.json](examples/navigation/navigate-url.json) | - -**NAVIGATE_TO_EXPRESSION options:** - -| Option | Use When | -|--------|----------| -| `URL_LITERAL` | Direct URL string | -| `COMPONENT` | URL stored in a form field | -| `FUNCTION_CALL` | URL constructed by a function | - -**NAVIGATE_METHOD_OPTIONS:** - -| Option | Opens In | -|--------|----------| -| `NEW_WINDOW` | New browser window | -| `NEW_TAB` | New browser tab | -| `SAME_TAB` | Current tab (replaces page) | - ---- - -## 10. NAVIGATE_IN_PANEL - -Navigate within a wizard or tabbed panel. - -| Property | Value | -|----------|-------| -| **Items** | `[PANEL_FOCUS_OPTION, "of", PANEL]` | -| **Examples** | [navigation/navigate-panel.json](examples/navigation/navigate-panel.json) | - -**PANEL_FOCUS_OPTION values:** - -| Option | Direction | -|--------|-----------| -| `NEXT_ITEM` | Go to next panel/tab | -| `PREVIOUS_ITEM` | Go to previous panel/tab | -| `FIRST_ITEM` | Go to first panel/tab | - -> **Note:** PANEL value uses `AFCOMPONENT|PANEL` type (not the full field type chain). - ---- - -## 11. SET_PROPERTY - -Set a property of a component. - -| Property | Value | -|----------|-------| -| **Items** | `[MEMBER_EXPRESSION, "to", EXTENDED_EXPRESSION]` | -| **Examples** | [property/set-label.json](examples/property/set-label.json), [property/set-placeholder.json](examples/property/set-placeholder.json), [property/set-required.json](examples/property/set-required.json) | - -MEMBER_EXPRESSION contains: `[PROPERTY_LIST, "of", COMPONENT]` - -**Available properties by component type:** - -| Property | Value Type | Description | Applicable To | -|----------|-----------|-------------|---------------| -| `visible` | BOOLEAN | Show/hide component | All components | -| `enabled` | BOOLEAN | Enable/disable interaction | All components | -| `label` | STRING | Field label text | All field types | -| `placeholder` | STRING | Placeholder text | Text inputs, dropdowns | -| `required` | BOOLEAN | Make field mandatory | All field types | -| `value` | varies | Field value | All field types | -| `readOnly` | BOOLEAN | Make field read-only | All field types | - -> **Note:** For simple visibility/enabled toggling, prefer SHOW/HIDE/ENABLE/DISABLE statements over SET_PROPERTY. Use SET_PROPERTY only for `label`, `placeholder`, `required`, etc. - ---- - -## 12. Additional Actions - -### SUBMIT_FORM - -| Items | `[]` (empty) | -|-------|-------------| -| **Examples** | [form-action/submit-form.json](examples/form-action/submit-form.json) | - -### RESET_FORM - -| Items | `[AFCOMPONENT]` | -|-------|-----------------| -| **Examples** | [form-action/reset-panel.json](examples/form-action/reset-panel.json) | - -### VALIDATE_FORM - -| Items | `[AFCOMPONENT]` | -|-------|-----------------| -| **Examples** | [form-action/validate-field.json](examples/form-action/validate-field.json) | - -### SAVE_FORM - -| Items | `[]` (empty) | -|-------|-------------| - -### SET_FOCUS - -| Items | `["to", AFCOMPONENT]` | -|-------|----------------------| - -### ADD_INSTANCE / REMOVE_INSTANCE - -| Items | `["of", REPEATABLE_COMPONENT]` | -|-------|-------------------------------| -| **Examples** | [instance/add-instance.json](examples/instance/add-instance.json), [instance/remove-instance.json](examples/instance/remove-instance.json) | - -REMOVE_INSTANCE is identical — just change the `nodeName`. - ---- - -## Conditions - -Conditions use the CONDITION node with `"nested": false` and a `choice` containing a comparison or boolean expression. - -| Type | Examples | -|------|----------| -| **Comparison (equals, not equals, etc.)** | [conditions/comparison-equals.json](examples/conditions/comparison-equals.json), [conditions/comparison-unary.json](examples/conditions/comparison-unary.json) | -| **Boolean (AND, OR)** | [conditions/boolean-and.json](examples/conditions/boolean-and.json), [conditions/boolean-or.json](examples/conditions/boolean-or.json) | - -**Unary operators (no right-hand side):** `IS_EMPTY`, `IS_NOT_EMPTY` - -**Binary operators:** `EQUALS`, `NOT_EQUALS`, `GREATER_THAN`, `GREATER_THAN_EQUALS`, `LESS_THAN`, `LESS_THAN_EQUALS`, `CONTAINS`, `STARTS_WITH`, `ENDS_WITH` - -> **Prefer operators over functions:** For conditions, use `IS_EMPTY`, `IS_NOT_EMPTY`, etc. NOT function calls like `isEmpty()`. - ---- - -## Quick Reference: Items Count by Action Type - -| Action | Items | Pattern | -|--------|-------|---------| -| SHOW_STATEMENT | 1 | `[AFCOMPONENT]` | -| HIDE_STATEMENT | 1 | `[AFCOMPONENT]` | -| ENABLE_STATEMENT | 1 | `[AFCOMPONENT]` | -| DISABLE_STATEMENT | 1 | `[AFCOMPONENT]` | -| CLEAR_VALUE_STATEMENT | 1 | `[VALUE_FIELD]` | -| SET_VALUE_STATEMENT | 3 | `[VALUE_FIELD, "to", EXPRESSION]` | -| SET_FOCUS | 2 | `["to", AFCOMPONENT]` | -| ADD_INSTANCE | 2 | `["of", REPEATABLE_COMPONENT]` | -| REMOVE_INSTANCE | 2 | `["of", REPEATABLE_COMPONENT]` | -| DISPATCH_EVENT | 3 | `[STRING_LITERAL, "on", AFCOMPONENT]` | -| NAVIGATE_TO | 3 | `[NAVIGATE_TO_EXPRESSION, "in", NAVIGATE_METHOD_OPTIONS]` | -| NAVIGATE_IN_PANEL | 3 | `[PANEL_FOCUS_OPTION, "of", PANEL]` | -| SET_PROPERTY | 3 | `[MEMBER_EXPRESSION, "to", EXTENDED_EXPRESSION]` | -| SET_VARIABLE | 6 | `["key", VARIABLE_NAME, "value", VARIABLE_VALUE, "on", AFCOMPONENT]` | -| SUBMIT_FORM | 0 | `[]` | -| SAVE_FORM | 0 | `[]` | -| RESET_FORM | 1 | `[AFCOMPONENT]` | -| VALIDATE_FORM | 1 | `[AFCOMPONENT]` | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/SKILL.md deleted file mode 100644 index cf2bae3c..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/SKILL.md +++ /dev/null @@ -1,222 +0,0 @@ ---- -name: create-function -description: > - Creates AEM Forms custom JavaScript functions with proper JSDoc annotations for the - visual rule editor. Handles async API patterns, form-level composition, fragment - re-exports, scope/globals usage, and parser compatibility. Use for calculations, - API calls, data transformations, or complex multi-field logic. NOT for simple - show/hide or enable/disable (use add-rules skill with direct actions instead). -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" -allowed-tools: Read, Write, Edit, Bash ---- - -# Custom Function Implementation - -Create JavaScript functions for AEM Adaptive Forms rule expressions. - -## When to Use - -- User needs custom business logic as a reusable function -- Calculations, validations, API calls, data transformations -- Complex multi-field logic that can't be done with simple rule actions - -**Do NOT use for:** Simple show/hide, enable/disable, set value — use the **add-rules** skill with direct action statements instead. - -## Critical Rule: No DOM Access - -Custom functions ONLY interact with the form model via `globals`/`scope`. - -| ❌ Don't | ✅ Do | -|----------|-------| -| `document.querySelector(...)` | `globals.form.panel.field.$value` | -| `element.classList.add(...)` | `globals.functions.setProperty(field, {...})` | -| `new CustomEvent(...)` | `globals.functions.dispatchEvent(target, "custom:event")` | -| `fetch(url)` | `globals.functions.request({url, method, body})` | - -## Function Format - -### Required Pattern: Declaration + Export - -```javascript -import { someHelper } from './libs.js'; - -/** - * Brief description - * @name myFunction My Function Display Name - * @param {string} param - Parameter description - * @param {scope} globals - Globals object - */ -function myFunction(param, globals) { - // implementation -} - -export { myFunction }; -``` - -### CRITICAL: Export Limitation - -```javascript -// ❌ DOES NOT WORK - Parser returns empty array -export function myFunction(param) { return param; } - -// ✅ WORKS - Regular function + export at end -function myFunction(param) { return param; } -export { myFunction }; -``` - -### NOT Supported as Exported Functions - -- `export function` (inline export) -- `async function` (won't appear in visual rule editor) -- Generator functions, class methods, rest parameters - -## Async Pattern: Helper + Sync Wrapper - -```javascript -// ✅ Internal helper (CAN use async/await) -async function fetchHelper(custId, globals) { - const response = await globals.functions.request({ - url: '/api/' + custId, - method: 'GET' - }); - if (!response.ok) throw new Error('Failed'); - return response.body; -} - -// ✅ Exported function (MUST be sync for rule editor) -/** - * @name fetchCustomer Fetch Customer - * @param {string} custId - Customer ID - * @param {scope} globals - Globals object - */ -function fetchCustomer(custId, globals) { - fetchHelper(custId, globals) - .then(function(data) { - globals.functions.setProperty(globals.form.name, { value: data.name }); - }) - .catch(function(err) { console.error(err); }); -} - -export { fetchCustomer }; -``` - -**Key rules:** -- **Exported functions** (with JSDoc `@name`) **MUST be sync** — async won't appear in rule editor -- **Helper functions** (internal) **CAN use async/await** -- Always use `globals.functions.request()` — NEVER use `fetch()` directly - -## Form-Level Composition (CRITICAL) - -AEM runtime loads ONLY the form-level script. Fragment scripts are authoring-only. - -### File Layout - -``` -code/blocks/form/scripts/ -├── form/ -│ └── my-form.js ← Loaded by AEM runtime -├── fragment/ -│ ├── fragment-a.js ← Authoring only -│ └── fragment-b.js ← Authoring only -└── script-libs/ - └── libs.js ← Shared utilities -``` - -### Pattern: Re-Export Fragment Functions - -```javascript -// form/my-form.js -import { handleBankClick } from '../fragment/chooseall.js'; -import { handleAccountRadio } from '../fragment/etbaccountselection.js'; - -/** - * @name formInit Form Init - * @param {scope} globals - Globals object - */ -function formInit(globals) { /* form-level logic */ } - -export { - formInit, // Form-level - handleBankClick, // Fragment: chooseall - handleAccountRadio, // Fragment: etbaccountselection -}; -``` - -| Rule | Details | -|------|---------| -| Form script must re-export ALL fragment functions | Otherwise "Unknown function" errors at runtime | -| Use unique function names | Form and fragment functions must never share names | -| When adding new fragment functions | Always add re-export in form-level script | - -## Fragment Functions: Pass Specific Fields - -```javascript -// ❌ Fragment root doesn't appear in Form Object dropdown -function handle(fragment, globals) { ... } - -// ✅ Pass specific fields as {object} parameters -/** - * @name handleBankSelection Handle Bank Selection - * @param {object} bankDropdown - Bank dropdown field - * @param {object} hiddenBankName - Hidden field for bank name - * @param {scope} globals - Globals object - */ -function handleBankSelection(bankDropdown, hiddenBankName, globals) { - globals.functions.setProperty(hiddenBankName, { value: bankDropdown.$value }); - globals.functions.dispatchEvent(globals.form, 'custom:bankSelected'); -} -``` - -**Cross-fragment:** child fragments CANNOT reference parent via `$parent`. Use events. - -## JSDoc Reference - -### Required Tags - -| Tag | Example | -|-----|---------| -| Description | `/** Calculates total price */` | -| `@param` | `@param {string} name - User name` | -| `@returns` | `@returns {number} The calculated total` | -| `@name` | `@name calculateTotal Calculate Total Price` | - -### Parameter Types - -| JSDoc Type | AEM Type | Notes | -|------------|----------|-------| -| `string` | STRING | | -| `number` | NUMBER | | -| `boolean` | BOOLEAN | | -| `date` | DATE | | -| `object` | OBJECT/AFCOMPONENT | Form components (fields, panels) | -| `scope` | SCOPE | Globals — MUST be last argument | -| `string[]` | STRING[] | Array types supported | - -Omit `@returns` for void functions. - -## Tool Commands - -| Tool | Command | -|------|---------| -| Parse functions | `parse-functions <path-to-js>` | -| List APIs | `api-manager list` | -| Show API details | `api-manager show <name> --json` | -| Build API clients | `api-manager build` | - -## Best Practices - -1. Always include JSDoc with description and param/return types -2. Use descriptive `@name` for rule editor discoverability -3. Validate inputs — check for null/undefined before processing -4. Keep functions focused — one function, one purpose -5. Use meaningful parameter names - -## Additional Resources - -- [references/api-patterns.md](references/api-patterns.md) — API integration patterns (api-clients, direct request, error handling) -- [references/implementation-patterns.md](references/implementation-patterns.md) — Code examples (calculations, validation, data transformation) -- [references/scope-functions-reference.md](references/scope-functions-reference.md) — Complete globals.functions API reference \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-parse-functions.sh b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-parse-functions.sh deleted file mode 100755 index 076e3a6f..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-parse-functions.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env bash -# Eval: Parse Functions smoke test for create-function skill -# Verifies parse-functions.js can parse JSDoc annotations from sample functions. -# -# Usage: bash skills/create-function/eval/eval-parse-functions.sh - -set -euo pipefail - -EVAL_DIR="$(cd "$(dirname "$0")" && pwd)" -PLUGIN_ROOT="$(cd "$EVAL_DIR/../../.." && pwd)" -FIXTURES="$EVAL_DIR/fixtures" -PASS=0; FAIL=0; SKIP=0; TOTAL=0 - -pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo " ✅ $1"; } -fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo " ❌ $1: $2"; } -skip() { SKIP=$((SKIP + 1)); TOTAL=$((TOTAL + 1)); echo " ⏭️ $1 (skipped: $2)"; } - -TMPDIR_EVAL="$(mktemp -d)" -trap 'rm -rf "$TMPDIR_EVAL"' EXIT - -echo "Parse Functions Eval" -echo "=====================" - -# ── Prerequisites ── - -HAS_NODE=false -if command -v node &>/dev/null; then - pass "Node.js available ($(node --version))" - HAS_NODE=true -else - skip "Node.js" "node not found in PATH" -fi - -HAS_BRIDGE_MODULES=false -if [[ -d "$PLUGIN_ROOT/scripts/rule_coder/bridge/node_modules" ]]; then - pass "Bridge node_modules installed" - HAS_BRIDGE_MODULES=true -else - skip "Bridge node_modules" "not installed — run: cd scripts/rule_coder/bridge && npm install" -fi - -FIXTURE_FUNCTIONS="$FIXTURES/sample-functions.js" -if [[ ! -f "$FIXTURE_FUNCTIONS" ]]; then - echo "FATAL: Required fixture missing: $FIXTURE_FUNCTIONS" - exit 1 -fi - -# ── Parse Functions ── - -echo "" -echo "── Parse Functions (parse-functions.js) ──" - -if [[ "$HAS_NODE" == true && "$HAS_BRIDGE_MODULES" == true ]]; then - STDOUT_FILE="$TMPDIR_EVAL/parse_functions_stdout.txt" - STDERR_FILE="$TMPDIR_EVAL/parse_functions_stderr.txt" - - EXIT_CODE=0 - node "$PLUGIN_ROOT/scripts/rule_coder/bridge/cli/parse-functions.js" "$FIXTURE_FUNCTIONS" \ - >"$STDOUT_FILE" 2>"$STDERR_FILE" || EXIT_CODE=$? - - if [[ "$EXIT_CODE" -eq 0 ]]; then - pass "parse-functions.js exits with code 0" - else - fail "parse-functions.js exit code $EXIT_CODE" "$(head -5 "$STDERR_FILE")" - fi - - if grep -q '"success"' "$STDOUT_FILE" 2>/dev/null && grep -q '"customFunction"' "$STDOUT_FILE" 2>/dev/null; then - pass "parse-functions.js output contains \"success\" and \"customFunction\"" - else - fail "parse-functions.js output missing expected keys" "$(head -5 "$STDOUT_FILE")" - fi -else - skip "parse-functions.js" "prerequisites not met" -fi - -# ── Summary ── - -echo "" -echo "════════════════════════════════" -echo " $PASS passed, $FAIL failed, $SKIP skipped ($TOTAL total)" -echo "════════════════════════════════" -[[ "$FAIL" -gt 0 ]] && exit 1 || exit 0 diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-plan.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-plan.md deleted file mode 100644 index 1a8e1377..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-plan.md +++ /dev/null @@ -1,28 +0,0 @@ -# create-function — Eval Plan - -## Automated - -Run the parse-functions smoke test: - -```bash -bash skills/create-function/eval/eval-parse-functions.sh -``` - -## Manual (E2E) - -### Prompt -> Create a custom function that prefills the message field with -> "I'm interested in learning more about..." when the inquiry type is "Sales". - -### Expected Behavior -- Creates a function file with proper JSDoc annotations -- Verifies with `parse-functions` -- Function uses `globals` parameter (no DOM access) -- Function is exported properly - -### Checklist -- [ ] Function file created at correct path -- [ ] Complete JSDoc annotations (`@name`, `@param`) -- [ ] Uses `globals` parameter -- [ ] `parse-functions` returns success -- [ ] Function is properly exported \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/fixtures/sample-functions.js b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/fixtures/sample-functions.js deleted file mode 100644 index 4a53e91c..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/fixtures/sample-functions.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Get Full Name - * @name getFullName Concatenates first and last name - * @param {string} firstName First name - * @param {string} lastName Last name - * @return {string} - */ -function getFullName(firstName, lastName) { - return `${firstName} ${lastName}`.trim(); -} - -/** - * Validate Phone Format - * @name validatePhone Checks if phone matches expected pattern - * @param {string} phone Phone number - * @return {boolean} - */ -function validatePhone(phone) { - if (!phone) return true; // optional field - const pattern = /^\+?[\d\s\-()]{7,15}$/; - return pattern.test(phone); -} - -export { getFullName, validatePhone }; diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/api-patterns.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/api-patterns.md deleted file mode 100644 index af0f42cf..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/api-patterns.md +++ /dev/null @@ -1,356 +0,0 @@ -# API Integration Patterns - -## Discovering APIs - -Use the `api-manager` CLI to find and understand available APIs: - -```bash -# List all available APIs -python3 scripts/api_manager/cli.py list - -# Search by keyword -python3 scripts/api_manager/cli.py list | grep -i otp -python3 scripts/api_manager/cli.py list | grep -i customer - -# Get full API details (parameters, URL, method, request/response shape) -python3 scripts/api_manager/cli.py show customerIdentification --json -``` - ---- - -## Two Approaches: api-clients (Preferred) vs Direct Request - -Both approaches return the same response format. Choose based on whether a typed client already exists. - -### Response Format (Same for Both) - -```javascript -{ - ok: true, // boolean — true for 2xx status codes - status: 200, // number — HTTP status code - body: { ... }, // object — parsed JSON response body - headers: { ... } // object — response headers -} -``` - ---- - -### Approach A: api-clients (Preferred) - -Generated async functions with typed parameters. Import from `./api-clients` in `script-libs/`. - -```javascript -import { customerIdentification } from './api-clients'; - -// api-clients are async — use inside async helper functions -async function fetchCustomerHelper(custId, globals) { - const response = await customerIdentification({ - customerId: custId - }, globals); - - if (response.ok && response.body?.status?.responseCode === '0') { - return response.body; - } - throw new Error('API failed: ' + response.status); -} - -// Exported function MUST be sync (async won't appear in rule editor) -/** - * Fetches customer data using api-clients - * @name fetchCustomer Fetch Customer - * @param {string} custId - Customer ID - * @param {scope} globals - Globals object - */ -function fetchCustomer(custId, globals) { - fetchCustomerHelper(custId, globals) - .then(function(data) { - globals.functions.setProperty(globals.form.customerName, { - value: data.customerName - }); - }) - .catch(function(error) { - console.error('API error:', error); - }); -} - -export { fetchCustomer }; -``` - -**Benefits:** Typed parameters, auto-validates required fields, auto-builds request body, IDE autocomplete. - ---- - -### Approach B: globals.functions.request() (Direct) - -Call any API endpoint directly when you need full control or the API isn't in api-clients yet. - -```javascript -/** - * Fetches customer data using direct request - * @name fetchCustomerDirect Fetch Customer Direct - * @param {string} custId - Customer ID - * @param {scope} globals - Globals object - */ -function fetchCustomerDirect(custId, globals) { - globals.functions.request({ - url: '/content/hdfc_hdb/api/customerIdentification.json', - method: 'POST', - body: { requestString: { customerId: custId } }, - headers: { 'Content-Type': 'application/json' } - }).then(function(response) { - if (response.ok) { - var data = response.body; - globals.functions.setProperty(globals.form.customerName, { - value: data.customerName - }); - } else { - console.error('API error:', response.status, response.body); - } - }); -} - -export { fetchCustomerDirect }; -``` - -**When to use direct:** API not in api-clients yet, need custom request building, quick testing/debugging. - ---- - -## API Call Patterns - -### Pattern A: Fire and Forget - -Use when the function triggers an API call without needing to update the UI (analytics, logging, background sync). - -```javascript -/** - * Sends analytics event to server - * @name sendAnalyticsEvent Send Analytics Event - * @param {string} eventName - Event name - * @param {string} eventData - Event payload as JSON string - * @param {scope} globals - Globals object - */ -function sendAnalyticsEvent(eventName, eventData, globals) { - globals.functions.request({ - url: '/api/analytics', - method: 'POST', - body: { event: eventName, data: eventData } - }).then(function(response) { - if (!response.ok) { - console.error('Analytics failed:', response.status); - } - }); -} - -export { sendAnalyticsEvent }; -``` - -### Pattern B: Handle with Scope (Most Common) - -Use when you need to act on the API response — populate fields, show/hide panels, display messages. - -```javascript -async function fetchAndPopulateHelper(custId, globals) { - const response = await globals.functions.request({ - url: '/api/customers/' + custId, - method: 'GET', - headers: { 'Content-Type': 'application/json' } - }); - - if (!response.ok) { - throw new Error('API error: ' + response.status); - } - return response.body; -} - -/** - * Fetches customer and populates form fields - * @name fetchAndPopulateCustomer Fetch And Populate Customer - * @param {string} custId - Customer ID - * @param {scope} globals - Globals object - */ -function fetchAndPopulateCustomer(custId, globals) { - fetchAndPopulateHelper(custId, globals) - .then(function(customer) { - globals.functions.setProperty(globals.form.firstName, { - value: customer.firstName - }); - globals.functions.setProperty(globals.form.lastName, { - value: customer.lastName - }); - globals.functions.setProperty(globals.form.addressPanel, { - visible: true - }); - }) - .catch(function(error) { - console.error('Failed to fetch customer:', error); - }); -} - -export { fetchAndPopulateCustomer }; -``` - -| Pattern | Use When | -|---------|----------| -| **A: Fire and Forget** | Trigger API without UI updates (analytics, logging, background sync) | -| **B: Handle with Scope** | Need to act on API response (populate fields, show/hide, validate) | - ---- - -## Chaining Multiple API Calls - -Use an async helper to sequence dependent API calls: - -```javascript -import { customerIdentification, generateOtp } from './api-clients'; - -async function loginFlowHelper(phone, dob, globals) { - // Step 1: Identify customer - const custResponse = await customerIdentification({ - mobileNumber: phone, - dateOfBirth: dob - }, globals); - - if (!custResponse.ok || custResponse.body?.status?.responseCode !== '0') { - throw new Error('Customer identification failed'); - } - - // Step 2: Generate OTP using customer ID from step 1 - const otpResponse = await generateOtp({ - customerId: custResponse.body.customerId - }, globals); - - if (!otpResponse.ok) { - throw new Error('OTP generation failed'); - } - - return { - customerId: custResponse.body.customerId, - otpSent: true - }; -} - -/** - * Handles login flow — identifies customer then sends OTP - * @name handleLogin Handle Login - * @param {scope} globals - Globals object - */ -function handleLogin(globals) { - loginFlowHelper( - globals.form.phone.$value, - globals.form.dob.$value, - globals - ).then(function(data) { - globals.functions.setProperty(globals.form.customerId, { - value: data.customerId - }); - globals.functions.setProperty(globals.form.otpPanel, { visible: true }); - }).catch(function(error) { - console.error('Login error:', error); - }); -} - -export { handleLogin }; -``` - ---- - -## When API is NOT in api-clients - -### Option 1: Add the API (Recommended for Reusable APIs) - -1. Create an OpenAPI YAML spec in `refs/apis/<api-name>.yaml` (use `refs/apis/_template.yaml` as a reference) -2. Run `python3 scripts/api_manager/cli.py build` to regenerate api-clients -3. Import and use: - -```javascript -import { newApiName } from './api-clients'; - -async function helper(globals) { - const response = await newApiName({ param1: 'value' }, globals); - // ... -} -``` - -### Option 2: Call Directly (Quick Testing or One-Off Use) - -```javascript -globals.functions.request({ - url: '/content/forms/api/endpoint.json', - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: { requestString: { param1: 'value' } } -}).then(function(response) { - if (response.ok && response.body?.status?.responseCode === '0') { - // handle success - } -}); -``` - ---- - -## Encryption (encrypt Extensibility Hook) - -If the API requires encrypted payloads, `globals.functions.request()` automatically calls the `encrypt` hook before sending. By default it's a no-op pass-through. - -Override `encrypt` as an exported function to add encryption: - -```javascript -/** - * Encrypts request payload with RSA - * @param {object} payload - { body, headers, cryptoMetadata?, options? } - * @returns {object} Encrypted payload with same structure - */ -function encrypt(payload) { - const { body, headers, cryptoMetadata, options } = payload; - - // Generate symmetric key, encrypt body - const symmetricKey = generateSymmetricKey(); - const encryptedBody = encryptWithSymmetricKey(JSON.stringify(body), symmetricKey); - const encryptedSymKey = encryptWithPublicKey(symmetricKey, PUBLIC_KEY); - - return { - body: encryptedBody, - headers: { ...headers, 'X-Encrypted': 'true' }, - encryptedSymKey: encryptedSymKey, - // cryptoMetadata passes through to decrypt hook for decryption - cryptoMetadata: { ...cryptoMetadata, symmetricKey }, - // options pass through unchanged to the Fetch request - options: options - }; -} - -export { encrypt }; -``` - -The full extensibility pipeline for `request()`: - -| Hook | Default | Override To | -|------|---------|-------------| -| `encrypt(payload)` | Pass-through | Encrypt request body before sending | -| `decrypt(body, req)` | Pass-through | Decrypt response body (2xx only) | -| `retryHandler(requestFn)` | Execute once | Add retry logic (e.g., refresh token on 401) | -| `externalize(url)` | Pass-through | Add context path prefix to URLs | - -See [scope-functions-reference.md](scope-functions-reference.md) for full `request()` API details. - ---- - -## API Integration Checklist - -| Step | Action | -|------|--------| -| 1 | **Search for APIs:** `python3 scripts/api_manager/cli.py list \| grep -i keyword` | -| 2 | **Get API details:** `python3 scripts/api_manager/cli.py show <apiName> --json` | -| 3 | **Import from api-clients:** `import { apiName } from './api-clients'` | -| 4 | **Write async helper** that calls the api-client (can use `async`/`await`) | -| 5 | **Write exported sync wrapper** with JSDoc `@name` for rule editor | -| 6 | **Handle success and error** — populate fields on success, log errors on failure | -| 7 | **Add re-export** if the function lives in a fragment script | - -### Key Rules Summary - -- **Exported functions** (with JSDoc `@name`) **MUST be sync** — `async` won't appear in rule editor -- **Helper functions** (internal, not exported) **CAN use async/await** -- **api-client functions are async** — always use them inside async helpers -- **NEVER use `fetch()` directly** — always use `globals.functions.request()` or api-clients \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/implementation-patterns.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/implementation-patterns.md deleted file mode 100644 index 58553012..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/implementation-patterns.md +++ /dev/null @@ -1,370 +0,0 @@ -# Implementation Patterns - -Concrete code examples for common custom function scenarios. - ---- - -## 1. Simple Calculation Function - -```javascript -/** - * Calculates the monthly payment for a loan - * @name calculateMonthlyPayment Calculate Monthly Payment - * @param {number} principal - Loan principal amount - * @param {number} annualRate - Annual interest rate (as decimal, e.g., 0.05 for 5%) - * @param {number} months - Number of months - * @returns {number} Monthly payment amount - */ -function calculateMonthlyPayment(principal, annualRate, months) { - if (months === 0) return 0; - var monthlyRate = annualRate / 12; - if (monthlyRate === 0) return principal / months; - - var payment = principal * (monthlyRate * Math.pow(1 + monthlyRate, months)) - / (Math.pow(1 + monthlyRate, months) - 1); - return Math.round(payment * 100) / 100; -} - -export { calculateMonthlyPayment }; -``` - -**Key points:** -- Pure function — no `globals` needed when returning a value without side effects -- Guard against division by zero -- Round currency to 2 decimal places - ---- - -## 2. Validation Function - -```javascript -/** - * Validates email format - * @name validateEmail Validate Email Address - * @param {string} email - Email address to validate - * @returns {boolean} True if email is valid - */ -function validateEmail(email) { - if (!email) return false; - var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - return emailRegex.test(email); -} - -export { validateEmail }; -``` - -**Key points:** -- Always check for null/undefined inputs first -- Return `boolean` for validation functions so they work with rule editor conditions - ---- - -## 3. Data Transformation - -```javascript -/** - * Formats a date to MM/DD/YYYY format - * @name formatDate Format Date - * @param {date} inputDate - Date to format - * @returns {string} Formatted date string - */ -function formatDate(inputDate) { - if (!inputDate) return ''; - var date = new Date(inputDate); - var month = String(date.getMonth() + 1).padStart(2, '0'); - var day = String(date.getDate()).padStart(2, '0'); - var year = date.getFullYear(); - return month + '/' + day + '/' + year; -} - -export { formatDate }; -``` - ---- - -## 4. Optional Parameters - -```javascript -/** - * Calculates discounted price - * @name calculateDiscount Calculate Discounted Price - * @param {number} originalPrice - Original price - * @param {number} [discountPercent=10] - Discount percentage (defaults to 10%) - * @returns {number} Discounted price - */ -function calculateDiscount(originalPrice, discountPercent) { - var pct = (discountPercent !== undefined && discountPercent !== null) ? discountPercent : 10; - var discount = originalPrice * (pct / 100); - return Math.round((originalPrice - discount) * 100) / 100; -} - -export { calculateDiscount }; -``` - -**Key points:** -- Use manual default checks instead of ES6 default params for maximum parser compatibility -- Document defaults in JSDoc with `[param=default]` syntax - ---- - -## 5. API Call Function with globals.functions.request - -**IMPORTANT:** Always use `globals.functions.request()` — never `fetch()` directly. - -```javascript -// Async helper — CAN use async/await (not exported) -async function fetchUserHelper(userId, globals) { - var response = await globals.functions.request({ - url: '/api/users/' + userId, - method: 'GET' - }); - - if (!response.ok) { - throw new Error('Failed to fetch user: ' + response.status); - } - return response.body; -} - -// Exported function — MUST be sync for rule editor -/** - * Fetches user data from API and populates form fields - * @name fetchUserData Fetch User Data - * @param {string} userId - User ID to fetch - * @param {scope} globals - Globals object - */ -function fetchUserData(userId, globals) { - fetchUserHelper(userId, globals) - .then(function(user) { - globals.functions.setVariable('userData', user, globals.form); - globals.functions.setProperty(globals.form.userName, { value: user.name }); - globals.functions.setProperty(globals.form.userEmail, { value: user.email }); - }) - .catch(function(error) { - console.error('Request failed:', error); - }); -} - -export { fetchUserData }; -``` - -### Chaining Sequential API Calls - -```javascript -async function fetchCustomerWithOrdersHelper(customerId, globals) { - // Step 1: Fetch customer - var customerResponse = await globals.functions.request({ - url: '/api/customers/' + customerId, - method: 'GET' - }); - if (!customerResponse.ok) { - throw new Error('Customer fetch failed'); - } - - // Step 2: Fetch orders using customer's order ID - var ordersResponse = await globals.functions.request({ - url: '/api/orders/' + customerResponse.body.orderId, - method: 'GET' - }); - - return { - customer: customerResponse.body, - orders: ordersResponse.body - }; -} - -/** - * Fetches customer with their orders - * @name fetchCustomerWithOrders Fetch Customer With Orders - * @param {string} customerId - Customer ID - * @param {scope} globals - Globals object - */ -function fetchCustomerWithOrders(customerId, globals) { - fetchCustomerWithOrdersHelper(customerId, globals) - .then(function(data) { - globals.functions.setProperty(globals.form.customerName, { - value: data.customer.name - }); - globals.functions.setProperty(globals.form.orderCount, { - value: data.orders.length - }); - }) - .catch(function(error) { - console.error('Error:', error); - }); -} - -export { fetchCustomerWithOrders }; -``` - ---- - -## 6. Repeatable Panel Population - -### Using setProperty with Array Value - -Set a repeatable panel's value to an array of objects. Each object maps to one panel instance, with keys matching field names inside the panel. - -```javascript -async function fetchAddressesHelper(custId, globals) { - var response = await globals.functions.request({ - url: '/api/customers/' + custId + '/addresses', - method: 'GET' - }); - if (!response.ok) throw new Error('Failed to load addresses'); - return response.body.addresses; -} - -/** - * Populates the address repeatable panel with API data - * @name loadAddresses Load Customer Addresses - * @param {string} custId - Customer ID - * @param {object} addressPanel - Repeatable address panel - * @param {scope} globals - Globals object - */ -function loadAddresses(custId, addressPanel, globals) { - fetchAddressesHelper(custId, globals) - .then(function(addresses) { - // Each array element creates one panel instance - // Keys must match field names inside the repeatable panel - var panelData = addresses.map(function(addr) { - return { - street: addr.streetLine1, - city: addr.city, - state: addr.stateCode, - zip: addr.postalCode - }; - }); - globals.functions.setProperty(addressPanel, { value: panelData }); - }) - .catch(function(error) { - console.error('Failed to load addresses:', error); - }); -} - -export { loadAddresses }; -``` - -### Using importData for Bulk Population - -`importData` sets values across the entire form using field paths as keys. Useful when populating many fields at once from a single API response. - -```javascript -/** - * Imports customer data into the form - * @name importCustomerData Import Customer Data - * @param {string} custId - Customer ID - * @param {scope} globals - Globals object - */ -function importCustomerData(custId, globals) { - globals.functions.request({ - url: '/api/customers/' + custId, - method: 'GET' - }).then(function(response) { - if (response.ok) { - var c = response.body; - // Keys are dot-notation paths matching form field structure - globals.functions.importData({ - firstName: c.firstName, - lastName: c.lastName, - email: c.email, - phone: c.phone, - // Repeatable panel — provide an array - addresses: c.addresses.map(function(a) { - return { street: a.street, city: a.city, zip: a.zip }; - }) - }); - } - }).catch(function(error) { - console.error('Import failed:', error); - }); -} - -export { importCustomerData }; -``` - -**Key differences:** - -| Approach | When to Use | -|----------|-------------| -| `setProperty(panel, { value: [...] })` | Populate a single repeatable panel with array data | -| `importData({ ... })` | Bulk-set many fields across the form in one call | - ---- - -## 7. Fragment Function — Pass Specific Fields - -Pass individual fields as `{object}` parameters. Fragment/Form root nodes have type `FORM` which doesn't appear in the Form Object dropdown. - -```javascript -// ❌ DOES NOT WORK — Fragment root doesn't appear in Form Object dropdown -function handleBankSelection(fragment, globals) { /* ... */ } - -// ✅ WORKS — Pass specific fields -/** - * Handles bank selection and enables continue button - * @name handleBankSelection Handle Bank Selection - * @param {object} bankDropdown - Bank selection dropdown field - * @param {object} hiddenBankName - Hidden field for bank name - * @param {object} continueButton - Continue button to enable/disable - * @param {scope} globals - Globals object - */ -function handleBankSelection(bankDropdown, hiddenBankName, continueButton, globals) { - globals.functions.setProperty(hiddenBankName, { value: bankDropdown.$value }); - globals.functions.setProperty(continueButton, { enabled: true }); - globals.functions.dispatchEvent(globals.form, 'custom:bankSelected'); -} - -export { handleBankSelection }; -``` - -### Cross-Fragment Communication via Events - -Child fragments CANNOT reference parent fields via `$parent` in rule parameters. Use custom events instead: - -```javascript -// Fragment function — dispatches event to form root -/** - * Handles radio selection in ETB account fragment - * @name handleAccountRadio Handle Account Radio - * @param {object} accountRadio - Radio button field - * @param {scope} globals - Globals object - */ -function handleAccountRadio(accountRadio, globals) { - if (accountRadio.$value) { - globals.functions.setVariable('selectedAccount', accountRadio.$value, globals.form); - globals.functions.dispatchEvent(globals.form, 'custom:accountSelected'); - } -} - -export { handleAccountRadio }; -``` - -The form-level script listens for `custom:accountSelected` and acts on its own fields. - ---- - -## Parser Output Format - -The custom function parser generates JSON used by the rule editor: - -```json -{ - "id": "functionName", - "displayName": "Display Name from @name", - "args": [ - { - "type": "STRING", - "name": "paramName", - "description": "Parameter description", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Function description from JSDoc", - "impl": "$0($1)" -} -``` - -- `$0` = function name -- `$1`, `$2`, etc. = parameters in order -- Verify with: `node scripts/rule_coder/bridge/cli/parse-functions.js <path-to-js>` diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/scope-functions-reference.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/scope-functions-reference.md deleted file mode 100644 index 045e0115..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/create-function/references/scope-functions-reference.md +++ /dev/null @@ -1,394 +0,0 @@ -# Scope Functions Reference - -Custom functions access the `globals` object to interact with form components programmatically. - -**Important:** The `globals` parameter must: -- Use type `{scope}` in JSDoc -- ALWAYS be the last argument in the function signature -- Is auto-injected by the runtime when called from a rule - ---- - -## Globals Object Structure - -```javascript -/** - * @param {string} param1 - First parameter - * @param {scope} globals - Globals object (auto-injected) - */ -function myFunction(param1, globals) { - const currentField = globals.field; // Field that triggered the rule - const form = globals.form; // Entire form model - const fns = globals.functions; // All scope functions below -} -``` - ---- - -## Reading Field Values - -Access any field through `globals.form.<path>.$value`: - -```javascript -const name = globals.form.personalInfo.firstName.$value; -const age = globals.form.personalInfo.age.$value; -const sel = globals.form.preferences.dropdown.$value; -``` - ---- - -## setProperty — Set Field Properties - -```javascript -globals.functions.setProperty(field, properties) -``` - -| Property | Type | Description | -|----------|------|-------------| -| `value` | `any` | Set the field's value | -| `visible` | `boolean` | Show or hide the field | -| `enabled` | `boolean` | Enable or disable the field | -| `required` | `boolean` | Mark field as required | -| `placeholder` | `string` | Set placeholder text | -| `readOnly` | `boolean` | Make field read-only | -| `valid` | `boolean` | Mark field valid/invalid | -| `label.value` | `string` | Change field label | -| `enum` | `any[]` | Set dropdown option values | -| `enumNames` | `string[]` | Set dropdown option display names | - -### Examples - -```javascript -// Set a single property -globals.functions.setProperty(globals.form.name, { value: 'John' }); - -// Set multiple properties at once -globals.functions.setProperty(globals.form.email, { - visible: true, - required: true, - enabled: true, - placeholder: 'Enter your email' -}); - -// Hide a field -globals.functions.setProperty(globals.form.panel.secretField, { visible: false }); - -// Populate dropdown options -globals.functions.setProperty(globals.form.stateDropdown, { - enum: ['CA', 'NY', 'TX'], - enumNames: ['California', 'New York', 'Texas'] -}); - -// Set field value to an array (repeatable panels) -globals.functions.setProperty(globals.form.addresses, { - value: [ - { street: '123 Main St', city: 'Austin' }, - { street: '456 Oak Ave', city: 'Dallas' } - ] -}); -``` - ---- - -## dispatchEvent — Dispatch Custom Events - -```javascript -globals.functions.dispatchEvent(target, eventName) -``` - -- `target` — form component to dispatch on (field, panel, or `globals.form`) -- `eventName` — string, typically prefixed with `custom:` - -**Important:** `dispatchEvent` does NOT support a data payload. Use `setVariable` before dispatching to pass data. - -### Example: Event with Data - -```javascript -function fireEventWithData(targetField, eventName, data, globals) { - // Store data first - globals.functions.setVariable(eventName + '_data', data, globals.form); - // Then dispatch - globals.functions.dispatchEvent(targetField, eventName); -} - -// Listener reads data via getVariable -function onMyEvent(globals) { - var data = globals.functions.getVariable('custom:myEvent_data', globals.form); - // ... use data -} -``` - -### Cross-Fragment Communication - -Child fragments CANNOT reference parent fields via `$parent`. Use events instead: - -```javascript -// In fragment function — dispatch event to form root -globals.functions.dispatchEvent(globals.form, 'custom:bankSelected'); - -// In form-level rule — listen for 'custom:bankSelected' and act on form fields -``` - ---- - -## setVariable / getVariable — Runtime Variables - -### setVariable - -```javascript -globals.functions.setVariable(name, value, target?) -``` - -- `name` — string key (stored as a **flat** key) -- `value` — any serializable value -- `target` — optional; defaults to `globals.form` - -### getVariable - -```javascript -globals.functions.getVariable(name, target?) -``` - -- `name` — string key; supports **dot notation** for nested reads -- Returns `undefined` if not found - -### Critical Asymmetry - -`setVariable` stores keys as flat strings. `getVariable` reads with dot notation into stored objects. - -```javascript -// ❌ WON'T WORK — 'address.city' stored as flat key, getVariable looks for nested path -globals.functions.setVariable('address.city', 'NYC'); -globals.functions.getVariable('address.city'); // undefined! - -// ✅ WORKS — store an object, then read nested path -globals.functions.setVariable('address', { city: 'NYC', zip: '10001' }); -globals.functions.getVariable('address.city'); // 'NYC' -globals.functions.getVariable('address.zip'); // '10001' - -// ✅ Simple (non-nested) keys always work -globals.functions.setVariable('customerId', '12345'); -globals.functions.getVariable('customerId'); // '12345' -``` - -### Chaining Async Rules - -1. **Rule 1:** Store data with `setVariable()`, then `dispatchEvent(globals.form, "custom:step2")` -2. **Rule 2:** Trigger on `custom:step2`, read data with `getVariable()` - -### Visual Rule Interoperability - -| Direction | How | -|-----------|-----| -| Visual rule → Custom function | Variables set via `SET_VARIABLE` action readable with `getVariable()` | -| Custom function → Visual rule | Variables set via `setVariable()` readable with `GET_VARIABLE` expression | - ---- - -## request — HTTP API Calls - -```javascript -globals.functions.request(options) -``` - -**CRITICAL:** Always use `globals.functions.request()` for ALL API calls — NEVER use `fetch()` directly. - -### Options - -| Property | Type | Required | Default | Description | -|----------|------|----------|---------|-------------| -| `url` | `string` | Yes | — | API endpoint URL | -| `method` | `string` | No | `'GET'` | HTTP method | -| `body` | `object` | No | — | Request payload (POST/PUT/PATCH) | -| `headers` | `object` | No | `{ 'Content-Type': 'application/json' }` | Request headers | -| `options` | `object` | No | — | Fetch API options (see below) | - -#### Fetch API Options (`options` sub-object) - -| Option | Values | -|--------|--------| -| `credentials` | `'omit'` \| `'same-origin'` \| `'include'` | -| `mode` | `'cors'` \| `'no-cors'` \| `'same-origin'` | -| `cache` | `'default'` \| `'no-store'` \| `'reload'` \| `'no-cache'` \| `'force-cache'` | -| `redirect` | `'follow'` \| `'error'` \| `'manual'` | -| `referrerPolicy` | Standard referrer policy values | -| `keepalive` | `boolean` | - -### Response Format - -Returns `Promise<Response>`: - -```javascript -{ - ok: true, // boolean — true for 2xx status - status: 200, // number — HTTP status code - body: { ... }, // object — parsed JSON response body - headers: { ... } // object — response headers -} -``` - -### Example - -```javascript -globals.functions.request({ - url: '/api/customers/' + custId, - method: 'GET', - headers: { 'Content-Type': 'application/json' } -}).then(function(response) { - if (response.ok) { - globals.functions.setProperty(globals.form.name, { value: response.body.name }); - } else { - console.error('API error:', response.status, response.body); - } -}).catch(function(error) { - console.error('Request failed:', error); -}); -``` - ---- - -## importData — Bulk Import Form Data - -```javascript -globals.functions.importData(data) -``` - -Imports an object whose keys map to form field paths. Supports dot notation. - -```javascript -globals.functions.importData({ - firstName: 'Jane', - lastName: 'Doe', - 'address.street': '123 Main St', - 'address.city': 'Austin' -}); -``` - ---- - -## Other Scope Functions - -| Function | Signature | Description | -|----------|-----------|-------------| -| `validate` | `validate(field)` | Validate a field, panel, or form. Returns array of errors. | -| `reset` | `reset(field)` | Reset field/panel/form to initial state | -| `submitForm` | `submitForm(options?)` | Submit the form | -| `setFocus` | `setFocus(field, option)` | Focus a field. Option: `'nextItem'`, `'previousItem'` | -| `exportData` | `exportData()` | Export all form data as object | -| `markFieldAsInvalid` | `markFieldAsInvalid(name, opts)` | Mark a field invalid with message | - -### markFieldAsInvalid Example - -```javascript -globals.functions.markFieldAsInvalid('$form.email', { - useId: true, - message: 'Please enter a valid email address' -}); -``` - -### validate + submitForm Example - -```javascript -function validateAndSubmit(globals) { - var errors = globals.functions.validate(globals.form); - if (errors.length === 0) { - globals.functions.submitForm(); - } -} -``` - ---- - -## Extensibility Hooks - -The `globals.functions.request()` pipeline calls four hooks (all no-op by default): - -| Hook | Signature | Called When | Purpose | -|------|-----------|------------|---------| -| `encrypt` | `encrypt(payload) → payload` | Before sending request | Encrypt request body | -| `decrypt` | `decrypt(body, originalReq) → body` | After 2xx response only | Decrypt response body | -| `retryHandler` | `retryHandler(requestFn) → Promise` | Wraps request execution | Retry logic (e.g., refresh token on 401) | -| `externalize` | `externalize(url) → url` | Before request | Add context path prefix to URLs | - -### encrypt - -Receives `{ body, headers, cryptoMetadata?, options? }`, returns same structure with encrypted body. - -```javascript -function encrypt(payload) { - var { body, headers, cryptoMetadata, options } = payload; - var encryptedBody = performEncryption(body); - return { - body: encryptedBody, - headers: { ...headers, 'X-Encrypted': 'true' }, - cryptoMetadata: cryptoMetadata, - options: options // MUST pass through unchanged - }; -} -``` - -### decrypt - -Receives `(body, originalRequest)` where `originalRequest` contains `cryptoMetadata`. - -```javascript -function decrypt(body, originalRequest) { - var { cryptoMetadata } = originalRequest; - return decryptWithKey(body, cryptoMetadata.symmetricKey); -} -``` - -### retryHandler - -Receives `requestFn` — call it to execute the request. Call multiple times for retries. Pass optional `{ headers, body }` to **merge** into the original request. - -```javascript -// Retry on 401 with refreshed token -function retryHandler(requestFn) { - return requestFn().then(function(response) { - if (response.status === 401) { - return refreshAuthToken().then(function(newToken) { - return requestFn({ - headers: { 'Authorization': 'Bearer ' + newToken } - }); - }); - } - return response; - }); -} -``` - -**Merge behavior:** Retry `{ headers, body }` values are shallow-merged with original request. New keys are added; existing keys are overwritten. - -### externalize - -Receives a URL string, returns the modified URL. - -```javascript -function externalize(url) { - var contextPath = '/content/mysite'; - if (url.startsWith('/') && !url.startsWith(contextPath)) { - return contextPath + url; - } - return url; -} -``` - ---- - -## Dynamic Variables (Utility Pattern) - -For convenience, import helpers from `code/blocks/form/functions.js`: - -```javascript -import { setProperty, getProperty, setFieldProperty, getFieldProperty } from '../functions.js'; - -// Form-level variable (stored in globals.form.$properties) -setProperty('myVar', { foo: 'bar' }, globals); -getProperty('myVar', globals); // { foo: 'bar' } -getProperty('myVar.foo', globals); // 'bar' (dot notation) - -// Field-level variable -setFieldProperty(field, 'tempData', value, globals); -getFieldProperty(field, 'tempData', globals); -``` diff --git a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/optimize-rules/SKILL.md b/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/optimize-rules/SKILL.md deleted file mode 100644 index 30708be5..00000000 --- a/skills/aem/forms/forms-orchestrator/references/domain-registry/references/logic/references/optimize-rules/SKILL.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -name: optimize-rules -description: > - Analyzes AEM Forms rules to decide what should be visual rules vs custom functions. - Produces an optimization report — never modifies rules directly. - Use when a fragment has 10+ rules, duplicate logic, scattered API calls, or - suspected bugs. Delegates implementation to add-rules / create-function skills. - Triggers: optimize rules, analyze rules, simplify rules, refactor rules, - too many rules, rule audit, consolidate rules. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Rule Optimization Analyst - -You analyze complex AEM Forms rule sets and produce an optimization report recommending the ideal balance between **visual rules** and **custom functions**. This skill is **pure analysis** — you never create, modify, or delete rules. - -## When to Use - -- Fragment or form has **10+ rules** that feel overly complex -- **Duplicate logic** across multiple fields (e.g., 7 bank buttons with identical code) -- **API calls scattered** across several rules instead of centralized -- Suspected **bugs** in rule conditions (inverted logic, redundant triggers) -- User asks to "clean up", "simplify", or "refactor" rules - -## Critical Rules - -| Rule | Why | -|------|-----| -| **Analysis only — never modify rules** | Produce a report. Delegate changes to `add-rules` / `create-function` skills. | -| **Read every rule before deciding** | Don't assume from field names. Read the actual rule JSON. | -| **Preserve existing behavior** | Optimizations must not change what the form does. Flag behavior changes explicitly. | -| **Document the interface contract** | Fragments can be embedded anywhere. Map events, hidden fields, variables, and API deps. | -| **Count before and after** | Every recommendation must show concrete metric improvement. | - -## Decision Framework: Visual Rule vs Custom Function - -| Signal | → Visual Rule | → Custom Function | -|--------|---------------|-------------------| -| **Conditions** | 1–2 simple conditions | 3+ conditions or nested logic | -| **Reuse** | Field-specific, used once | Same logic across 3+ fields | -| **Side effects** | Single show/hide/enable/disable | API calls, error handling, retries | -| **Async** | Never | Any fetch / service invocation | -| **Maintenance** | Rarely changes | Likely to evolve or extend | - -## Analysis Workflow - -### Step 1 — Inventory - -Count every rule in the rule store. Categorize each as: -- **Visual rule** (show/hide, enable/disable, set value — no function call) -- **Function rule** (FUNCTION_CALL action) -- **Disabled** (present but inactive) - -### Step 2 — Categorize by Pattern - -Group rules that share the same logic shape: -- Identical actions on different fields → consolidation candidate -- Multiple rules on one field → merge candidate -- Rules that dispatch/consume the same event → event-flow documentation - -### Step 3 — Detect Issues - -Scan for known bug patterns (see Bug Patterns below) and structural problems: -- Redundant rules (same trigger + same action on same field) -- Overly complex visual rules that should be functions -- Simple function calls that should be direct actions - -### Step 4 — Generate Report - -Produce `<FRAGMENT>_OPTIMIZATION.md` following the Output Template below. - -## Output Template - -The report must follow this structure: - -### 1. Overview - -| Metric | Before | After | -|--------|--------|-------| -| Total Rules | X | Y | -| Visual Rules | A | B | -| Function Rules | C | D | -| Disabled Rules | E | F | -| Custom Functions | 0 | G | -| Bugs Found | N | — | - -### 2. Fragment Interface Contract - -Document everything the fragment exposes or depends on: - -| Section | Columns | -|---------|---------| -| **Events PRODUCED** | Event Name · Trigger · Purpose · Data (via setVariable) | -| **Events CONSUMED** | Event Name · Handler · Action Taken | -| **Hidden Fields** | Field Name · Type · Set By · Read By · Purpose | -| **Variables** | Variable Name · Scope · Set By · Read By · Purpose | -| **Properties READ** | Property Path · Used In · Purpose | -| **API Dependencies** | API Name · Called By · Purpose | - -### 3. Field-by-Field Analysis - -For every field with rules, document: - -- **BEFORE:** Brief description of current rules -- **ISSUES:** Problems found (bugs, duplication, complexity) -- **AFTER:** Recommended approach — visual rule OR custom function, with rationale - -### 4. Custom Function Summary - -| Function | Replaces Rules | Fields Affected | Purpose | -|----------|---------------|-----------------|---------| -| handleX | Rules 1, 2, 3 | fieldA, fieldB | Centralizes Y logic | - -### 5. Integration Requirements - -What a parent form/fragment must do to embed this fragment: -- Events to listen for -- Properties to provide -- Hidden field values to handle - -## Common Patterns - -| Pattern | Recommendation | Rationale | -|---------|---------------|-----------| -| 3+ buttons with identical click logic | Custom function | 80%+ code reduction via single reusable handler | -| Dropdown with search + select API calls | Custom function | Centralizes API handling and error recovery | -| Simple enable when 1–2 conditions met | Visual rule | Readable, maintainable, no code needed | -| Checkbox mutual exclusion (3–4 fields) | Visual rule | Simple toggle logic | -| Checkbox mutual exclusion (5+ fields) | Custom function | Scales better, single source of truth | -| Multiple rules setting the same variable | Custom function | Eliminates race conditions | -| Scattered API calls across rules | Custom function | Single error-handling strategy | - -## Bug Patterns to Detect - -| Bug | Wrong | Correct | -|-----|-------|---------| -| Inverted validation | `validate().length != 0` → enables submit | `validate().length === 0` → enables submit | -| Duplicate rules | Same action fires from multiple rules on same event | Single rule, single execution | -| Missing else branch | Show on condition, never hides when false | Add corresponding hide in else | -| Stale disabled rules | Old rule disabled but newer copy exists | Remove disabled duplicate | -| Event without listener | Fragment dispatches event nobody consumes | Document or remove dead event | - -## After Analysis - -Hand off to implementation skills: - -- **Visual rules / simple rules** → `add-rules` skill -- **Custom functions** → `create-function` skill, then `add-rules` for the FUNCTION_CALL rule - -Always present the full optimization report to the user for approval before any implementation begins. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/SKILL.md b/skills/aem/forms/forms-orchestrator/references/planner/SKILL.md deleted file mode 100644 index 2409699a..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/SKILL.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -name: planner -description: > - Plan generator. Decomposes user requirements into ordered, executable plans - using a configurable strategy. The orchestrator routes here when no plans - exist for a journey and requirements need to be broken down into plans. - Triggers: plan, plans, journey, build, start, generate plans, create plans, - decompose, what plans, next plan. -type: skill -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Planner - -Generates ordered, executable plans from user requirements. The orchestrator routes here when a journey has requirements but no plans yet. - ---- - -## What the Planner Does - -``` -Requirements (journey docs, Screen.md, screenshots, v1 JSON) - │ - ▼ -┌────────────────────────────────┐ -│ Resolve strategy │ -│ (custom or default) │ -└─────────────┬──────────────────┘ - │ - ▼ -┌────────────────────────────────┐ -│ Analyze requirements │ -│ using analysis domain skills │ -└─────────────┬──────────────────┘ - │ - ▼ -┌────────────────────────────────┐ -│ Decompose into ordered plans │ -│ Write to plans/<journey>/ │ -└────────────────────────────────┘ -``` - -The planner takes requirements as input and produces a set of plan files ready for sequential execution by the orchestrator. - ---- - -## Strategies - -A strategy is a set of guidelines for how to decompose requirements into ordered plans. The orchestrator resolves the strategy before generating any plans. - -### Resolution Order - -| Priority | Location | Description | -|----------|----------|-------------| -| 1 (highest) | `plans/custom-strategy.md` in workspace | User-provided override — full control over plan decomposition | -| 2 (default) | [`references/default-strategy.md`](references/default-strategy.md) | Default strategy — workflow-focused decomposition based on real-world experience | - -**Resolution rule:** If `plans/custom-strategy.md` exists in the workspace, use it. Otherwise, use the default. - -### Default Strategy - -The default strategy ([`references/default-strategy.md`](references/default-strategy.md)) analyzes requirements and decomposes them into workflow-focused plans: - -1. Analyze requirements using `analysis` domain skills -2. Identify the form's structure (panels, fields, workflows) -3. Decompose into ordered plans — structure first, then workflows, then cross-cutting concerns - -### Custom Strategy - -Users can override the default by placing a strategy file at `plans/custom-strategy.md` in their workspace. A custom strategy can define any decomposition approach — by screen, by feature, by priority, or any other scheme that fits the project. - ---- - -## Output - -The planner produces plan files at `plans/<journey>/NN-<title>.md`, numbered sequentially, ready for execution by the orchestrator. - ---- - -## Plan Types - -The planner uses these plan type references when decomposing requirements into plans. Each type defines the specification patterns, typical steps, and characteristics for that category of work. - -| Type | Reference | When to Use | -|------|-----------|-------------| -| **Structure** | [`references/structure-plan.md`](references/structure-plan.md) | Building the form skeleton — panels, fields, basic validations | -| **Workflow** | [`references/workflow-plan.md`](references/workflow-plan.md) | Building a specific user flow or conditional branch | -| **Logic** | [`references/logic-plan.md`](references/logic-plan.md) | Adding cross-cutting validations and business rules | -| **Integration** | [`references/integration-plan.md`](references/integration-plan.md) | Wiring APIs — data loading, save/submit, external services | -| **Infrastructure** | [`references/infrastructure-plan.md`](references/infrastructure-plan.md) | Cross-cutting concerns — error handling, session management, toasts | - -A plan's type is not declared explicitly — it emerges from which specification sections and skills the plan uses. The planner should consult the relevant plan type reference(s) when generating each plan to ensure the specification follows the correct patterns. - ---- - -## Plan Conventions - -Generated plans follow a standard structure. Full template and field definitions: **[`assets/plan-template.md`](assets/plan-template.md)** - -| Property | Convention | -|----------|-----------| -| **Path** | `plans/<journey>/NN-<short-title>.md` | -| **Numbering** | Zero-padded two digits: `01`, `02`, ..., `10`, `11` | -| **Max per journey** | 15 plans — if more are needed, the journey is too complex; split it | -| **Template** | `assets/plan-template.md` | - ---- - -## Quick Reference - -| What | Where | -|------|-------| -| Default plan generation strategy | `references/default-strategy.md` | -| User strategy override | `plans/custom-strategy.md` (in workspace) | -| Plan template | `assets/plan-template.md` | -| Domain registry (skill resolution) | `../domain-registry/SKILL.md` | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/assets/plan-template.md b/skills/aem/forms/forms-orchestrator/references/planner/assets/plan-template.md deleted file mode 100644 index 57396f24..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/assets/plan-template.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -name: plan-template -description: > - Standard schema and template for plan files. Plans are sequentially ordered - execution units within a journey. Each plan implements a scoped feature, - workflow, or integration by invoking one or more skills. -type: template ---- - -# Plan Template - -Standard structure for plan files. Copy this template when creating a new plan. - -> **File path convention:** `plans/<journey>/NN-<short-title>.md` - ---- - -## Template - -```` -# Plan NN: <Plan Title> - -**Source:** `journeys/<journey>.md` sections <X.Y>, <X.Z> -<!-- Which sections of the journey/requirements doc does this plan implement? --> - -**Sub-task:** <TICKET-ID> (<N> SP) -<!-- Optional: Jira/ticket ID and story points --> - -**Skills:** `<skill-1>`, `<skill-2>`, `<skill-3>` -<!-- Which skills does this plan invoke? e.g. create-form, add-rules, create-function, manage-apis, create-component --> - -**Depends on:** Plan <NN> (<what it provides>), Plan <NN> (<what it provides>) -<!-- Explicit dependency chain. Use "Nothing (first plan)" for the first plan. --> - ---- - -## Objective - -<!-- One paragraph: what does this plan achieve and why? Keep it concise. --> -<!-- Example: "Build the complete form skeleton with all panels and implement the personal information fields with their validations." --> - -## Specification - -<!-- The detailed design. Content varies by plan type — see Plan Types below. --> - -<!-- FOR STRUCTURE PLANS: Panel hierarchy tree + field specification tables --> -<!-- -### Panel Structure - -``` -rootPanel -├── panelA -│ ├── fieldA1 (text-input) -│ └── fieldA2 (drop-down) -└── panelB (initially hidden) - └── fieldB1 (number-input) -``` - -### Field Specifications - -| Field | Type | Required | Min | Max | Pattern | Notes | -|-------|------|----------|-----|-----|---------|-------| -| fieldA1 | text-input | Yes | 2 | 30 | `^[A-Za-z]+$` | Auto-uppercase | -| fieldA2 | drop-down | Yes | — | — | — | Enum from API | ---> - -<!-- FOR WORKFLOW PLANS: Branching logic tables showing triggers, conditions, and actions --> -<!-- -### <Branch Name> Logic - -| Component | Trigger | Condition | Actions | -|-----------|---------|-----------|---------| -| fieldX | is changed | value EQUALS "Y" | Show panelA, Hide panelB, Set fieldZ required = true | -| fieldX | is changed | value EQUALS "N" | Hide panelA, Show panelB, Clear fieldZ | ---> - -<!-- FOR LOGIC PLANS: Validation rule tables, custom function signatures, algorithm pseudocode --> -<!-- -### Validation Rules - -| Trigger Fields | Condition | Error Message | Display As | -|---------------|-----------|---------------|------------| -| fieldA OR fieldB | fieldA > fieldB | "A cannot exceed B" | Toast | - -### Custom Functions - -| Function Name | Purpose | Parameters | Returns | -|---------------|---------|------------|---------| -| validateAvsB | Cross-field check | `a`, `b`, `errorMsg` | void (shows toast on failure) | - -### Algorithm - -``` -Input: fieldA, fieldB -Output: validation result - -Algorithm: - if fieldA > fieldB: - showErrorToast(errorMsg) - return false - return true -``` ---> - -<!-- FOR INTEGRATION PLANS: API definitions, request/response mappings, prefill logic --> -<!-- -### API Definition - -| Property | Value | -|----------|-------| -| Endpoint | `/api/path/to/endpoint` | -| Method | POST | -| Content-Type | application/json | -| Trigger | On form load / On button click | - -### Request Body - -```json -{ - "param": "<value source>" -} -``` - -### Response Handling - -| Response | Status | Action | -|----------|--------|--------| -| Success | 200 | Extract data → prefill form | -| Timeout | 401 | Clear session → show relogin | -| Error | 400 | Show error toast | - -### Prefill Mapping - -| API Field | Form Field | Transform | -|-----------|------------|-----------| -| `response.field_a` | fieldA | Direct | -| `response.date` | dateField | `convertDateApiToForm` | ---> - -## Steps to Execute - -<!-- Numbered, actionable steps. Each step should indicate which skill to invoke. --> - -1. **<Action verb> <artifact>** using `<skill-name>`: - <!-- Describe what to create/modify and how --> - -2. **<Action verb> <artifact>** using `<skill-name>`: - <!-- Describe wiring up rules, integrations, etc. --> - -3. **Validate:** - <!-- Always include a validation step --> - ``` - node tools/eds-form-validator/validate.js <path-to-form.json> - ``` - -4. **Push to AEM:** - <!-- Always include a deploy step (user may defer at checkpoint) --> - ``` - form-sync push <aem-content-path> - ``` - -## Acceptance Criteria - -<!-- Checklist of testable conditions. Each item should be independently verifiable. --> - -- [ ] <Condition 1 — what should be true when this plan is done> -- [ ] <Condition 2 — specific field/panel/rule behavior> -- [ ] <Condition 3 — error case handled correctly> -- [ ] Form passes validation without errors -- [ ] Form renders on AEM without errors - -## Notes - -<!-- Optional: Known issues, deferred items, edge cases, dependency notes, links to related plans. --> -<!-- Remove this section if not needed. --> - -<!-- Example: "This plan provides infrastructure functions used by Plans 07–09. --> -<!-- Build order may differ from plan number — see dependency chain." --> -```` - ---- - -## Plan Types - -Common plan patterns observed across production journeys. A plan's type is not declared explicitly — it emerges from which specification sections and skills the plan uses. - -Each type has its own detailed reference with specification patterns, typical steps, and examples. The planner uses these references when generating plans. - -| Type | Purpose | Primary Skills | Reference | -|------|---------|----------------|-----------| -| **Structure** | Form skeleton — panels, fields, basic validations | `create-form`, `scaffold-form` | [`references/structure-plan.md`](../references/structure-plan.md) | -| **Workflow** | Specific user flow or conditional branch | `create-form`, `add-rules`, `create-function` | [`references/workflow-plan.md`](../references/workflow-plan.md) | -| **Logic** | Cross-cutting validations and business rules | `add-rules`, `create-function` | [`references/logic-plan.md`](../references/logic-plan.md) | -| **Integration** | API wiring — data loading, save/submit, external calls | `manage-apis`, `create-function`, `add-rules` | [`references/integration-plan.md`](../references/integration-plan.md) | -| **Infrastructure** | Error handling, session mgmt, toasts, sanitization | `create-function`, `add-rules` | [`references/infrastructure-plan.md`](../references/infrastructure-plan.md) | - ---- - -## Conventions - -These rules govern all plans regardless of type. - -| Rule | Description | -|------|-------------| -| **Scope** | Each plan targets a single workflow, feature, or use-case. If a plan touches unrelated concerns, split it. | -| **Cross-skill** | A single plan can freely invoke multiple skills (build + logic + integration). Plans are scoped by *feature*, not by *skill*. | -| **Numbering** | Zero-padded two digits: `01`, `02`, ..., `10`, `11`. | -| **Execution** | Plans execute sequentially. Each plan declares its dependencies via `Depends on`. | -| **Max per journey** | 15 plans. If more are needed, the journey is too complex — decompose it. | -| **File path** | `plans/<journey>/NN-<short-title>.md` | -| **Validate + Deploy** | Every plan ends with a validate step and a deploy step. The user may defer deployment at the post-plan checkpoint. | -| **Dependency declaration** | Always state what each dependency provides, not just its number. e.g., `Plan 01 (panel skeleton)` not just `Plan 01`. | -| **Acceptance criteria** | Every criterion must be independently testable. Prefer specific observable behaviors over vague statements. | -| **Specification tables** | Use tables for structured data (field specs, rule definitions, API mappings). Use trees for hierarchical structures (panel layout). Use pseudocode for algorithms. | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/references/default-strategy.md b/skills/aem/forms/forms-orchestrator/references/planner/references/default-strategy.md deleted file mode 100644 index f43a493d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/references/default-strategy.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -name: default-strategy -description: > - Default plan-generation strategy. Decomposes form requirements into an ordered - set of workflow-focused plans. Analyzes inputs (journey docs, Screen.md, - screenshots, v1 form JSON) and produces sequenced plan files that build the - form incrementally — structure first, then workflows, then cross-cutting concerns. -type: strategy -license: Apache-2.0 -metadata: - author: Adobe - version: "0.1" ---- - -# Default Plan Generation Strategy - -Given a set of requirements, decompose them into an ordered set of plans that build the form incrementally. This strategy focuses on **workflow-based decomposition** — each plan targets a distinct functional workflow or concern rather than a technical layer. - -> This strategy balances incremental progress, testability, and manageable plan scope. - ---- - -## Inputs - -Any combination of the following: - -| Input | Description | -|-------|-------------| -| Requirements docs | Free-form requirements, user stories, acceptance criteria | -| Journey specs | `journeys/<journey>/journey.md` — structured journey specification | -| Screen.md | `journeys/<journey>/screens/<screen>/Screen.md` — detailed screen documentation | -| Screenshots | UI mockups or screenshots of existing forms | -| v1 form JSON | Existing `form.json` from a v1 form being migrated or extended | - -At minimum, one input source must be available. Richer inputs produce better plan decomposition. - ---- - -## Process - -### Step 1 — Analyze Requirements - -Use `analysis` domain skills to understand the form: - -- **`analyze-requirements`** — parse requirements docs, extract form specification, identify complexity -- **`create-screen-doc`** — generate Screen.md from screenshots or requirements (if not already available) -- **`analyze-v1-form`** — extract structure and logic from existing v1 form JSON (for migration scenarios) -- **`review-screen-doc`** — validate existing Screen.md against form JSON (quality gate) - -The goal is to produce a clear picture of what the form needs: its panels, fields, validation rules, conditional logic, API integrations, and workflows. - -### Step 2 — Identify Structure - -From the analysis output, identify: - -- **Panels and sections** — the form's top-level structure -- **Fields and field groups** — what data is collected -- **Workflows and branches** — conditional paths (e.g., user category → different field sets) -- **API integrations** — data loading, save/submit, external validations -- **Cross-cutting concerns** — error handling, session management, complex async flows - -### Step 3 — Decompose into Plans - -Create ordered plan files following the **recommended decomposition order** below. This order is a guideline, not a rigid mandate — adapt it to the specific form's needs. - -#### Recommended Plan Order - -| Order | Focus | Example Title | What It Covers | -|-------|-------|---------------|----------------| -| 1 | **Form structure & skeleton** | `01-form-structure.md` | All panels, initial fields, basic layout — the form's skeleton | -| 2–N | **Major workflows** (one per plan) | `02-workflow-branch-a.md`, `03-workflow-branch-b.md` | One plan per major conditional branch or workflow — visibility rules, workflow-specific fields, branch logic | -| Next | **Cross-cutting validations** | `04-field-validations.md` | Validation rules that span multiple panels or workflows — format checks, cross-field validations, error messages | -| Next | **API integrations** | `05-api-prefill.md`, `06-api-submit.md` | Data loading (prefill, lookups), save/submit handlers, API client generation | -| Next | **Complex async flows** | `07-async-verification.md` | If applicable — OTP verification, external checks, real-time validations, polling flows | -| Last | **Infrastructure / cross-cutting** | `08-error-handling.md` | Error handling, session management, analytics, accessibility — concerns that wrap the entire form | - -> **Adapt, don't force.** A simple form might need only 3 plans. A form with no APIs skips integration plans entirely. A form with heavy async flows might front-load those. The order above is a starting point. - -#### Decomposition Principles - -1. **One workflow per plan** — each plan should target a single user-facing workflow or concern. If a plan touches unrelated features, split it. -2. **Vertical slices** — a single plan can invoke build + logic + integration skills. Plans are scoped by *feature*, not by *skill domain*. -3. **Incremental testability** — after each plan completes, the form should be in a testable state. Avoid plans that leave the form in a broken intermediate state. -4. **Dependency clarity** — each plan explicitly declares which prior plans must be complete. The dependency graph should be simple (mostly linear with occasional parallel-safe pairs). -5. **Manageable scope** — if a plan has more than 8–10 steps, it's probably too large. Split it into two plans along a natural boundary. - -### Step 4 — Write Plan Files - -Write each plan to `plans/<journey>/NN-<title>.md` following the plan template at `assets/plan-template.md` (relative to the plans registry). Each plan file must include: - -- **Header block** — source references, skills needed, dependencies -- **Objective** — one paragraph describing what the plan achieves -- **Specification** — detailed design (field tables, rule tables, API mappings, etc.) -- **Steps to Execute** — ordered list of skill invocations -- **Acceptance Criteria** — testable conditions that define "done" - ---- - -## Output - -Plan files at `plans/<journey>/NN-<title>.md`, numbered sequentially, ready for execution. - -``` -plans/<journey>/ -├── 01-form-structure.md -├── 02-workflow-branch-a.md -├── 03-workflow-branch-b.md -├── 04-field-validations.md -├── 05-api-prefill.md -├── 06-api-submit.md -├── 07-async-verification.md -└── 08-error-handling.md -``` - -The exact number and naming of plans depends on the form's complexity and structure. - ---- - -## Example Decomposition - -A moderately complex form with conditional branches and API integrations might decompose into plans like this: - -| Plan | Focus | Skills Used | -|------|-------|-------------| -| 01 | Form structure & initial fields | `create-form` | -| 02 | Workflow branch A (e.g., conditional section) | `create-form`, `add-rules` | -| 03 | Workflow branch B (e.g., alternative path) | `create-form`, `add-rules`, `create-function` | -| 04 | Shared fields & common sections | `create-form`, `add-rules` | -| 05 | Cross-field business rule validations | `create-function`, `add-rules` | -| 06 | API integration — data loading & prefill | `manage-apis`, `create-function`, `add-rules` | -| 07 | API integration — save & submit | `manage-apis`, `create-function`, `add-rules` | -| 08 | Error handling & session management | `create-function`, `add-rules` | - -**Key principles illustrated:** -- Plans follow the recommended order (structure → workflows → validations → integrations → infrastructure) -- Every plan freely mixes skills (`create-form` + `add-rules` + `create-function` in the same plan) -- Each plan ends with validate + push, keeping the form in a deployable state -- The exact number of plans depends on the form's complexity — a simple form might need only 3 - ---- - -## Customization - -Users can override this default strategy entirely by placing a custom strategy file at: - -``` -plans/custom-strategy.md -``` - -in their workspace. When a custom strategy exists, the orchestrator uses it instead of this file. A custom strategy can define any decomposition approach — by screen, by feature, by user story, by priority, or any other scheme. - -See the Plan Registry (`../SKILL.md`) for strategy resolution rules. \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/references/infrastructure-plan.md b/skills/aem/forms/forms-orchestrator/references/planner/references/infrastructure-plan.md deleted file mode 100644 index 6c877c2d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/references/infrastructure-plan.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -name: infrastructure-plan -description: > - Reference for the Infrastructure plan type. Covers cross-cutting concerns - like error handling, session management, toast notifications, and data - sanitization. -type: plan-type ---- - -# Infrastructure Plan - -Cross-cutting concerns like error handling, session management, toast notifications, and data sanitization. - ---- - -## Overview - -| Attribute | Value | -|-----------|-------| -| **Primary skills** | `create-function`, `add-rules` | -| **Specification focus** | Error message catalogs, session management flows, utility function signatures, storage key inventories | -| **Typical steps** | Create utility functions (toast, error handler, sanitizers) → wire rules to fields → add UI elements (modal panels) → validate → push | -| **Example** | Plan 08: Error Handling & Session Management | - ---- - -## Characteristics - -- Provides shared infrastructure consumed by other plans -- Build order may differ from plan number (numbered last for logical grouping, but may execute earlier) -- Documents all error messages in a centralized catalog -- Manages storage keys (sessionStorage, localStorage) with clear ownership - ---- - -## Specification Sections - -An infrastructure plan's **Specification** section typically includes the following: - -### Error Message Catalog - -Centralized list of all error and success messages used across the form. - -| Code | Type | Message | Display As | -|------|------|---------|------------| -| `ERR_TIMEOUT` | error | "Session expired. Please log in again." | Modal | -| `ERR_API_FAIL` | error | "Something went wrong. Please try again." | Toast | -| `SUC_SAVE` | success | "Your progress has been saved." | Toast | - -### Session Management - -Define how the form handles session lifecycle — timeout detection, re-authentication, and cleanup. - -| Scenario | Detection | Action | -|----------|-----------|--------| -| Session timeout | API returns 401 / fault code 900901 | Show relogin modal, clear sensitive data | -| Tab close / navigate away | `beforeunload` event | Clear session storage | -| Successful completion | Form submitted successfully | Clear all storage keys | - -### Storage Key Inventory - -All sessionStorage and localStorage keys the form reads or writes, with ownership. - -| Key | Storage | Read By | Written By | Purpose | -|-----|---------|---------|------------|---------| -| `session_id` | sessionStorage | Integration plans | Data loading plan | Active session identifier | -| `entry_source` | localStorage | Data loading plan | External | Entry point detection signal | - -### Utility Functions - -Shared functions consumed by multiple plans. - -| Function Name | Purpose | Parameters | Returns | -|---------------|---------|------------|---------| -| `showSuccessToast` | Display success notification | `message` | void | -| `showErrorToast` | Display error notification | `message` | void | -| `handleApiResponse` | Central error router | `response`, `globals` | void | -| `handleSessionTimeout` | Relogin flow | `globals` | void | -| `clearSessionData` | Storage cleanup | — | void | - -### Data Sanitization Rules - -Field-level transforms applied on input (e.g., uppercase, trim, format enforcement). - -| Field(s) | Rule | Implementation | -|----------|------|----------------| -| `nameField1`, `nameField2` | Force uppercase | `toUpperCase` custom function on `fd:change` | -| `freeTextField` | Trim spaces, uppercase | `sanitizeText` custom function on `fd:change` | - ---- - -## Typical Steps to Execute - -1. **Create utility functions** using `create-function`: - - Toast notification helpers (success, error) - - Central API response handler - - Session timeout handler with relogin modal - - Data sanitization functions (uppercase, trim) - - Storage cleanup function - -2. **Add UI elements** using `create-form` (if needed): - - Relogin modal panel with message and button - - Any shared UI components for error display - -3. **Wire rules to fields** using `add-rules`: - - Sanitization rules on text input fields (`fd:change` triggers) - - Relogin button click handler - -4. **Validate:** - ``` - node tools/eds-form-validator/validate.js <path-to-form.json> - ``` - -5. **Push to AEM:** - ``` - form-sync push <aem-content-path> - ``` - ---- - -## Dependencies - -Infrastructure plans have a unique dependency pattern: - -- **Consumed BY other plans** — provides shared functions that integration and logic plans call -- **Depends ON structure plan** — needs the form skeleton to exist for wiring rules and adding UI elements -- **Numbering vs execution order** — often numbered last for logical grouping, but the dependency note should call out that it can (or should) be executed earlier if other plans depend on its outputs - -> **Tip:** If multiple integration/logic plans depend on infrastructure functions (e.g., `handleApiResponse`), consider executing the infrastructure plan before those plans, regardless of its number. - ---- - -## Acceptance Criteria Patterns - -Infrastructure plans typically verify: - -- [ ] Toast notifications display correctly for all error/success scenarios -- [ ] Session timeout is detected and relogin modal appears -- [ ] Storage keys are cleaned up on form completion -- [ ] Data sanitization rules fire on field input (uppercase, trim) -- [ ] No console errors from utility functions -- [ ] Form passes validation without errors -- [ ] Form renders on AEM without errors diff --git a/skills/aem/forms/forms-orchestrator/references/planner/references/integration-plan.md b/skills/aem/forms/forms-orchestrator/references/planner/references/integration-plan.md deleted file mode 100644 index ed8fb1f0..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/references/integration-plan.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -name: integration-plan -description: > - Reference for Integration plan type. Wires APIs and data flows — loading data - into the form, submitting data out, or calling external services. -type: plan-type ---- - -# Integration Plan - -Wires APIs and data flows — loading data into the form, submitting data out, or calling external services. - ---- - -## Overview - -| Attribute | Value | -|-----------|-------| -| **Primary skills** | `manage-apis`, `create-function`, `add-rules` | -| **Specification focus** | API endpoint definitions, request/response schemas, prefill mapping tables (API field → form field → transform), response handling matrices, state management | -| **Typical steps** | Register API definitions → create data-loading/submission functions → create prefill mapping functions → wire form triggers (load, button click) → validate → push | -| **Example** | Plan 06: API Integration — Data Loading, Plan 07: API Integration — Save & Submit | - ---- - -## Characteristics - -- Depends on structure + workflow plans (fields and panels must exist for prefill mapping) -- Documents every API field → form field mapping explicitly -- Handles multiple response scenarios (success, timeout, business exception) -- May manage session storage, global variables, and journey detection logic - ---- - -## Specification Sections - -An integration plan's **Specification** section typically includes the following: - -### API Definition - -One table per API endpoint consumed by the plan. - -| Property | Value | -|----------|-------| -| Endpoint | `/api/path/to/endpoint` | -| Method | POST | -| Content-Type | application/json | -| Trigger | On form load / On button click | - -### Request Body - -Document the full request body structure, noting which form fields or variables supply each value. - -```json -{ - "param": "<value source>" -} -``` - -For forms with multiple categories or conditional branches, provide one request body mapping table per branch — clearly label which condition applies. - -### Response Handling - -A matrix covering all expected response scenarios. - -| Response | Status | Action | -|----------|--------|--------| -| Success | 200 | Extract data → prefill form | -| Timeout | 401 | Clear session → show relogin | -| Business exception | 400 | Show error toast with message from response | -| Network error | — | Retry once, then show generic error toast | - -### Prefill Mapping - -One row per field that receives data from the API response. - -| API Field | Form Field | Transform | -|-----------|------------|-----------| -| `response.field_a` | fieldA | Direct | -| `response.date` | dateField | `convertDateApiToForm` | -| `response.category` | categoryField | Enum mapping (API value → form enum) | - -### Custom Functions - -| Function Name | Purpose | Parameters | Returns | -|---------------|---------|------------|---------| -| `loadFormData` | Entry point — orchestrates API calls and prefill | `globals` | void | -| `prefillFormFields` | Maps API response to form fields | `data`, `globals` | void | -| `assembleRequestBody` | Builds request payload from form fields | `globals` | object | - ---- - -## Typical Steps - -1. **Register API definitions** using `manage-apis`: - - Create OpenAPI spec or cURL-based definition - - Generate JS API client at `refs/apis/api-clients/` - -2. **Create orchestrator function** using `create-function`: - - Entry point function (e.g., `loadFormData`, `submitPersonalDetails`) - - Calls the API client, handles response routing - -3. **Create mapping functions** using `create-function`: - - Prefill mapping (API response → form fields) - - Request assembly (form fields → API request body) - - Data transformations (date conversion, enum mapping, etc.) - -4. **Wire form triggers** using `add-rules`: - - `fd:init` → data loading function - - Button `fd:click` → save/submit function - - Custom events for async flows - -5. **Validate:** - ``` - node tools/eds-form-validator/validate.js <path-to-form.json> - ``` - -6. **Push to AEM:** - ``` - form-sync push <aem-content-path> - ``` - ---- - -## Common Patterns - -### Data Loading (Prefill) - -- Triggered on form initialization (`fd:init` event) -- Reads identifiers from URL params, sessionStorage, or localStorage -- Calls one or more APIs to fetch existing data -- Maps response fields to form fields via a dedicated mapping function -- May set fields to read-only based on data source (e.g., pre-populated journeys) - -### Save (Partial) - -- Triggered by a "Save" button click -- Assembles request body from current form state (does not require all validations to pass) -- Calls save API — typically does not navigate away on success -- Shows success/error toast based on response - -### Submit (Full) - -- Triggered by a "Submit" / "Proceed" button click -- Runs full validation before assembling request body -- Enforces disclaimer checkboxes and mandatory fields -- Calls submit API — may trigger downstream flows (e.g., identity verification, next-step routing) -- Handles anti-forgery tokens (CSRF) if required - -### CSRF / Anti-Forgery Token - -- Read token from `globals.functions.getVariable('requestVerificationToken', globals.form)` -- Include in request headers as `RequestVerificationToken` -- May require a hidden form field to store the token - ---- - -## Dependencies - -Integration plans typically depend on: - -| Dependency | What It Provides | -|------------|-----------------| -| Structure plan | Panel skeleton and fields that will be prefilled or read from | -| Workflow plans | Conditional branches that affect which fields are in the request body | -| Logic plans (optional) | Validation functions and date conversion utilities reused in mapping | \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/references/logic-plan.md b/skills/aem/forms/forms-orchestrator/references/planner/references/logic-plan.md deleted file mode 100644 index f1156810..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/references/logic-plan.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -name: logic-plan -description: > - Plan type reference for logic plans. Adds cross-cutting validations and - business rules that span multiple fields or panels. -type: plan-type ---- - -# Logic Plan - -Adds cross-cutting validations and business rules that span multiple fields or panels. - ---- - -## Overview - -| Attribute | Value | -|-----------|-------| -| **Primary skills** | `add-rules`, `create-function` | -| **Specification focus** | Validation rule tables (trigger fields, condition, error message, display method), custom function signatures with parameters and return types, algorithm pseudocode | -| **Typical steps** | Create custom functions → wire validation rules to trigger fields → unit test edge cases → validate → push | -| **Example** | Plan 05: Cross-field Business Rule Validations | - ---- - -## Characteristics - -- Depends on multiple earlier plans (fields must exist before rules can reference them) -- Creates reusable custom functions (e.g., `validateDateRange`, `validateThreshold`) -- Documents edge cases and boundary conditions explicitly -- Often includes a unit test step for custom functions - ---- - -## Specification Patterns - -A logic plan's specification section typically includes the following subsections. - -### Validation Rules - -Define each validation as a row in a trigger/condition/action table: - -| Trigger Fields | Condition | Error Message | Display As | -|---------------|-----------|---------------|------------| -| fieldA OR fieldB | fieldA > fieldB | "A cannot exceed B" | Toast | -| dateOfBirth | age < 18 | "Must be 18 or older" | Inline | - -**Guidelines:** -- **Trigger fields** — list every field whose `fd:change` event should fire this validation -- **Condition** — express in plain logic (no code); use field names from the form.json -- **Error message** — exact string the user sees -- **Display as** — `Toast`, `Inline` (field-level), or `Modal` - -### Custom Functions - -Catalog every function this plan creates: - -| Function Name | Purpose | Parameters | Returns | -|---------------|---------|------------|---------| -| validateDateRange | Cross-field: end date must be after start date | `startDate`, `endDate`, `errorMsg` | void (shows toast on failure) | -| validateThreshold | Range check based on category | `value`, `category` | void (shows toast on failure) | -| validateRatio | Ratio cannot exceed configured limit | `numerator`, `denominator` | void (shows toast on failure) | - -**Guidelines:** -- Functions should be reusable across multiple trigger fields -- Sync wrappers with async `*Helper` pattern when `globals` access is needed -- Document all edge cases (null values, zero values, type coercion) - -### Algorithm Pseudocode - -For non-trivial logic, include pseudocode: - -``` -Input: startDate, endDate -Output: validation result - -Algorithm: - if endDate <= startDate: - showErrorToast("End date must be after start date") - return false - return true -``` - ---- - -## Typical Steps to Execute - -1. **Create custom functions** using `create-function`: - - Write each function in the fragment script - - Add sync exported wrapper + async helper (if using `globals`) - - Re-export from form-level script with JSDoc stubs - -2. **Wire validation rules** using `add-rules`: - - For each trigger field, create a rule that calls the custom function on `fd:change` - - Validate rule JSON with `rule_coder.validator` - - Save rule to store with `save-rule.js` - -3. **Test edge cases:** - - Null/empty field values - - Boundary conditions (exactly at threshold) - - Multiple triggers firing in sequence - -4. **Validate:** - ``` - node tools/eds-form-validator/validate.cjs <path-to-form.json> code/authoring/_form.json - ``` - -5. **Push to AEM:** - ``` - form-sync push <aem-content-path> - ``` - ---- - -## Dependencies - -Logic plans typically depend on: -- **Structure plan** — all panels and fields must exist -- **Workflow plans** — branch-specific fields must be in place before cross-field rules can reference them - -Logic plans are typically depended on by: -- **Integration plans** — API response handling may reuse validation functions -- **Infrastructure plans** — error handling may wrap validation error display \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/references/structure-plan.md b/skills/aem/forms/forms-orchestrator/references/planner/references/structure-plan.md deleted file mode 100644 index 3729505d..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/references/structure-plan.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -name: structure-plan -description: > - Plan type reference for structure plans. Builds the form skeleton: panels, - fields, and basic per-field validations. Usually the first plan in a journey. -type: plan-type ---- - -# Structure Plan - -Builds the form skeleton: panels, fields, and basic per-field validations. - -| Attribute | Value | -|-----------|-------| -| **Primary skills** | `create-form`, `scaffold-form` | -| **Specification focus** | Panel hierarchy tree, field property tables (name, type, required, min, max, pattern) | -| **Typical steps** | Create form on AEM → build form.json with panels and fields → validate → push | -| **Example** | Plan 01: Form Structure & Initial Fields | - ---- - -## Characteristics - -- Usually the first plan in a journey — establishes the form skeleton -- Creates placeholder panels for features built in later plans -- Hidden panels default to `visible: false` -- Field specs include `constraintMessages` for validation errors - ---- - -## Specification Sections - -A structure plan's specification typically includes: - -### Panel Structure - -A tree diagram showing the full panel hierarchy with field types: - -``` -rootPanel -├── panelA -│ ├── fieldA1 (text-input) -│ └── fieldA2 (drop-down) -└── panelB (initially hidden) - └── fieldB1 (number-input) -``` - -### Field Specifications - -A table defining every field's properties: - -| Field | Type | Required | Min | Max | Pattern | Notes | -|-------|------|----------|-----|-----|---------|-------| -| fieldA1 | text-input | Yes | 2 | 30 | `^[A-Za-z]+$` | Auto-uppercase | -| fieldA2 | drop-down | Yes | — | — | — | Enum from API | - ---- - -## Typical Steps - -1. **Create form on AEM** using `scaffold-form`: - - Bootstrap a new empty form via `form-sync create` - - Verify `metadata.json` is updated correctly - -2. **Build form.json** using `create-form`: - - Add all top-level panels (including empty placeholders for later plans) - - Add fields to panels with types, required flags, min/max, patterns - - Set `visible: false` on panels that are conditionally shown later - - Add `constraintMessages` for field-level validation errors - -3. **Validate:** - ``` - node tools/eds-form-validator/validate.cjs <form.json> code/authoring/_form.json - ``` - -4. **Push to AEM:** - ``` - form-sync push <aem-content-path> - ``` - ---- - -## Dependencies - -- **Depends on:** Nothing — this is typically the first plan -- **Depended on by:** All subsequent plans (workflow, logic, integration, infrastructure) \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/references/planner/references/workflow-plan.md b/skills/aem/forms/forms-orchestrator/references/planner/references/workflow-plan.md deleted file mode 100644 index a9df47b3..00000000 --- a/skills/aem/forms/forms-orchestrator/references/planner/references/workflow-plan.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -name: workflow-plan -description: > - Workflow plan type reference. Defines the pattern for plans that build a specific - user flow or conditional branch within the form. -type: plan-type ---- - -# Workflow Plan - -Builds a specific user flow or branch within the form. - ---- - -## Overview - -| Attribute | Value | -|-----------|-------| -| **Primary skills** | `create-form`, `add-rules`, `create-function` | -| **Specification focus** | Branching logic tables (trigger → condition → show/hide/set actions), enum mappings, conditional field requirements | -| **Typical steps** | Add fields to existing panels → implement visibility rules → implement value/property rules → validate → push | -| **Example** | Plan 02: Workflow Branch A, Plan 03: Workflow Branch B | - ---- - -## Characteristics - -- Depends on the structure plan (panel skeleton must exist) -- Heavy use of visibility rules and conditional required flags -- May introduce custom functions for dynamic behavior (e.g., switching validation patterns) -- One plan per major branch/flow — keeps scope manageable - ---- - -## Specification Pattern - -The specification section of a workflow plan should include: - -### Branching Logic Tables - -Show what triggers the branch, the conditions, and the resulting actions: - -| Component | Trigger | Condition | Actions | -|-----------|---------|-----------|---------| -| `<field>` | is changed | value EQUALS `"<value>"` | Show `<panel>`, Hide `<panel>`, Set `<field>` required = true | -| `<field>` | is changed | value EQUALS `"<value>"` | Hide `<panel>`, Show `<panel>`, Clear `<field>` | - -### New Fields (if adding fields to existing panels) - -| Field | Panel | Type | Required | Visible | Notes | -|-------|-------|------|----------|---------|-------| -| `<fieldName>` | `<panelName>` | text-input | Yes | true | Added for this workflow | - -### Enum Mappings (if applicable) - -| Enum Value | Display Label | Triggers | -|------------|--------------|----------| -| `"optionA"` | Option A | Show `panelA` | -| `"optionB"` | Option B | Show `panelB` | - -### Conditional Requirements - -| Field | Required When | Not Required When | -|-------|--------------|-------------------| -| `<field>` | `<trigger>` equals `"<value>"` | All other cases | - ---- - -## Typical Steps - -1. **Add fields to existing panels** using `create-form`: - - Add workflow-specific fields to the panels created by the structure plan - - Set initial visibility (`visible: false` for conditionally shown panels) - -2. **Implement visibility rules** using `add-rules`: - - Wire trigger fields to show/hide panels and fields based on user selection - - Ensure mutually exclusive branches hide each other - -3. **Implement value/property rules** using `add-rules`: - - Set conditional required flags - - Clear dependent fields when the branch changes - - Reset state when the user switches between branches - -4. **Create custom functions** (if needed) using `create-function`: - - Dynamic behavior like switching validation patterns - - Complex branching logic that can't be expressed in simple rules - -5. **Validate:** - ``` - node tools/eds-form-validator/validate.js <path-to-form.json> - ``` - -6. **Push to AEM:** - ``` - form-sync push <aem-content-path> - ``` - ---- - -## When to Use - -- The form has **conditional sections** that appear/disappear based on user input -- A **dropdown, radio, or checkbox** drives which fields are visible -- Multiple **mutually exclusive paths** exist (e.g., account types, document types) -- A **sub-flow** within the form has its own set of fields and rules - ---- - -## When NOT to Use - -- The form has no conditional branching → use a **structure plan** instead -- You're adding cross-field validations without new UI → use a **logic plan** instead -- You're wiring APIs without new branching → use an **integration plan** instead \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/scripts/_resolve-workspace b/skills/aem/forms/forms-orchestrator/scripts/_resolve-workspace deleted file mode 100755 index d61e6eb9..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/_resolve-workspace +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# ───────────────────────────────────────────────────────────────────────────── -# AEM Forms Skills — Workspace Resolver -# -# Shared helper sourced by all CLI tool entry points (scripts/* and skill scripts) -# to ensure every tool runs inside the user's AEM Forms workspace regardless -# of where the shell happens to be when the agent invokes the command. -# -# Resolution order (first match wins): -# 1. FORMS_WORKSPACE already in environment — e.g. exported by caller -# 2. FORMS_WORKSPACE found in cwd's .env — written during workspace setup -# 3. Fall back to cwd — backwards compatible default -# -# Usage (inside a script): -# source "$PLUGIN_ROOT/scripts/_resolve-workspace" -# cd "$FORMS_WORKSPACE" -# ───────────────────────────────────────────────────────────────────────────── - -if [ -n "${FORMS_WORKSPACE:-}" ] && [ -d "$FORMS_WORKSPACE" ]; then - # Priority 1: already in the environment - : -elif [ -f "$PWD/.env" ]; then - # Priority 2: read from .env in current working directory - _fw="$(grep -m1 '^FORMS_WORKSPACE=' "$PWD/.env" 2>/dev/null | cut -d= -f2-)" - if [ -n "$_fw" ] && [ -d "$_fw" ]; then - FORMS_WORKSPACE="$_fw" - else - FORMS_WORKSPACE="$PWD" - fi - unset _fw -else - # Priority 3: fall back to cwd - FORMS_WORKSPACE="$PWD" -fi - -export FORMS_WORKSPACE diff --git a/skills/aem/forms/forms-orchestrator/scripts/api-manager b/skills/aem/forms/forms-orchestrator/scripts/api-manager deleted file mode 100755 index 5725dc23..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api-manager +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" "$PLUGIN_ROOT/scripts/api_manager/cli.py" "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/__init__.py deleted file mode 100644 index 019305c4..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""API Manager - CLI tool for managing API integrations for AEM Forms.""" - -__version__ = "1.0.0" diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/aem_client.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/aem_client.py deleted file mode 100644 index 55937af6..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/aem_client.py +++ /dev/null @@ -1,360 +0,0 @@ -"""AEM FDM Client - Fetches API definitions from AEM Form Data Model.""" - -import json -from typing import Any, Optional -from urllib.parse import quote - -import requests - -from .config import Config -from .exceptions import AemConnectionError - - -class AemFdmClient: - """Client for fetching API definitions from AEM Form Data Model.""" - - def __init__(self, config: Config): - """Initialize AEM FDM client. - - Args: - config: Configuration with AEM host and auth - """ - self.host = config.aem_host.rstrip("/") - self.auth_header = config.auth_header - self.session = requests.Session() - self.session.headers.update({ - "Authorization": self.auth_header, - "Accept": "application/json", - }) - self.session.timeout = 30 - - def _request(self, path: str) -> Any: - """Make HTTP request to AEM. - - Args: - path: URL path - - Returns: - JSON response data - - Raises: - AemConnectionError: If request fails - """ - url = f"{self.host}{path}" - try: - response = self.session.get(url, timeout=30) - # Handle 200 OK and 300 Multiple Choices (returns array of URLs) - if response.status_code in (200, 300): - return response.json() - else: - raise AemConnectionError( - f"HTTP {response.status_code}: {response.reason}" - ) - except requests.exceptions.JSONDecodeError as e: - raise AemConnectionError(f"Invalid JSON response: {e}") - except requests.exceptions.RequestException as e: - raise AemConnectionError(f"Request failed: {e}") - - def fetch_all_apis(self) -> list[dict]: - """Fetch all APIs from FDM. - - Handles both response formats: - - Array of URLs (paginated) -> fetch each URL and combine - - Object with FDM data -> process directly - - Returns: - List of API definitions - """ - fdm_path = "/conf/forms/settings/cloudconfigs/fdm.infinity.json" - data = self._request(fdm_path) - - # Check response format - if isinstance(data, list): - # Paginated response - array of URLs to fetch - return self._fetch_from_paginated_urls(data) - - # Direct object response - check if it has full content or just shallow listing - return self._process_response(data) - - def _process_response(self, data: dict) -> list[dict]: - """Process response data - handles both full and shallow responses.""" - # Check if data has full content (jcr:content with inputJson) or just shallow listing - has_full_content = self._has_full_content(data) - - if has_full_content: - return self._extract_api_integrations(data) - else: - # Shallow listing - need to fetch each FDM individually - return self._fetch_individual_fdms(data) - - def _has_full_content(self, data: dict) -> bool: - """Check if response has full content (inputJson) or just shallow listing.""" - for key, value in data.items(): - if key.startswith(("jcr:", "sling:")): - continue - if ( - value - and isinstance(value, dict) - and value.get("jcr:primaryType") == "cq:Page" - ): - content = value.get("jcr:content") - # If jcr:content exists and has inputJson, it's full content - if content and content.get("inputJson"): - return True - # If jcr:content exists but no inputJson, it's shallow - if content and not content.get("inputJson"): - return False - # Default to trying full extraction - return True - - def _fetch_from_paginated_urls(self, urls: list[str]) -> list[dict]: - """Fetch APIs from paginated URLs. - - When we get paginated URLs, fetch .3.json depth to get type info, - then fetch individual FDMs for full content. - """ - # Use .3.json depth which includes jcr:content.type but not inputJson - list_url = "/conf/forms/settings/cloudconfigs/fdm.3.json" - try: - list_data = self._request(list_url) - # This will be shallow (no inputJson), so it will fetch individual FDMs - return self._process_response(list_data) - except AemConnectionError: - # Fallback: fetch each paginated URL and combine - all_data = {} - for url in urls: - try: - page_data = self._request(url) - all_data.update(page_data) - except AemConnectionError as e: - print(f" Warning: Failed to fetch {url}: {e}") - return self._process_response(all_data) - - def _fetch_individual_fdms(self, data: dict) -> list[dict]: - """Fetch individual FDMs when we only have shallow listing.""" - # First identify api-integration FDMs from shallow listing - api_integration_fdms = [] - for key, value in data.items(): - if key.startswith(("jcr:", "sling:")): - continue - if ( - value - and isinstance(value, dict) - and value.get("jcr:primaryType") == "cq:Page" - ): - content = value.get("jcr:content") - # Strict filter: only type === 'api-integration' - if content and content.get("type") == "api-integration": - api_integration_fdms.append(key) - - print(f" Found {len(api_integration_fdms)} api-integration FDMs, fetching details...") - - # Fetch each FDM individually to get inputJson - apis = [] - for fdm_name in api_integration_fdms: - try: - fdm_path = f"/conf/forms/settings/cloudconfigs/fdm/{quote(fdm_name)}.infinity.json" - fdm_data = self._request(fdm_path) - - content = fdm_data.get("jcr:content") - if not content or content.get("type") != "api-integration": - continue - - api_config = self._parse_input_json(content.get("inputJson"), content) - if api_config: - api_config["fdmName"] = fdm_name - apis.append(api_config) - except AemConnectionError as e: - print(f" Warning: Failed to fetch {fdm_name}: {e}") - - return apis - - def _extract_api_integrations(self, data: dict) -> list[dict]: - """Extract API integrations from FDM data with full content.""" - apis = [] - - for key, value in data.items(): - # Skip JCR metadata - if key.startswith(("jcr:", "sling:")): - continue - - # Check if this is a cq:Page - if ( - not value - or not isinstance(value, dict) - or value.get("jcr:primaryType") != "cq:Page" - ): - continue - - content = value.get("jcr:content") - if not content: - continue - - # Strict filter: only type === 'api-integration' - if content.get("type") != "api-integration": - continue - - # Parse inputJson to get API details - api_config = self._parse_input_json(content.get("inputJson"), content) - if api_config: - api_config["fdmName"] = key - apis.append(api_config) - - return apis - - def _parse_input_json( - self, input_json_str: Optional[str], content: dict - ) -> Optional[dict]: - """Parse inputJson string to extract API configuration.""" - if not input_json_str: - # Fallback to content fields if inputJson not available - if not content.get("name") and not content.get("jcr:title") and not content.get("serviceEndPoint"): - return None # Not enough info - return { - "name": content.get("name") or content.get("jcr:title") or "unknown", - "description": f"{content.get('name') or content.get('jcr:title')} API", - "endpoint": content.get("serviceEndPoint", ""), - "method": "POST", - "params": {}, - "response": {}, - "encryptionRequired": content.get("encryptionRequired", False), - "executeAtClient": content.get("executeAtClient", False), - } - - try: - input_json = json.loads(input_json_str) - - # Extract parameters from inputMapping - params = {} - input_mapping = input_json.get("inputMapping", []) - if isinstance(input_mapping, list): - for param in input_mapping: - param_name = param.get("apiKey") or param.get("name") - if param_name: - params[param_name] = { - "type": param.get("type", "string"), - "required": param.get("required", False), - "description": param.get("description") or f"{param.get('in', 'body')} parameter", - "default": param.get("defaultValue"), - "in": param.get("in", "body"), - } - - # Extract response fields from outputMapping - response = {} - output_mapping = input_json.get("outputMapping", []) - if isinstance(output_mapping, list): - for field in output_mapping: - field_name = field.get("apiKey") or field.get("name") - if field_name: - response[field_name] = { - "type": field.get("type", "string"), - "description": field.get("description", ""), - } - - # Enrich with swaggerSpec data (especially required fields) - swagger_spec = input_json.get("swaggerSpec") - if swagger_spec: - self._enrich_from_swagger(swagger_spec, params, response) - - return { - "name": input_json.get("displayName") or content.get("name") or "unknown", - "description": f"{input_json.get('operationName') or input_json.get('displayName') or content.get('name')} API", - "endpoint": input_json.get("url") or content.get("serviceEndPoint", ""), - "method": input_json.get("method", "POST"), - "params": params, - "response": response, - "contentType": input_json.get("contentType", "application/json"), - "authType": input_json.get("authType", "None"), - "encryptionRequired": input_json.get("encryptionRequired", False), - "executeAtClient": input_json.get("executeAtClient", False), - "isOutputAnArray": input_json.get("isOutputAnArray", False), - } - except json.JSONDecodeError as e: - print(f" Warning: Failed to parse inputJson: {e}") - return None - - def _enrich_from_swagger( - self, swagger_spec: dict, params: dict, response: dict - ) -> None: - """Enrich params and response from Swagger/OpenAPI spec. - - Updates required field from swagger spec. - """ - paths = swagger_spec.get("paths") - if not paths: - return - - # Find first path and method - for path, methods in paths.items(): - for method, spec in methods.items(): - if not isinstance(spec, dict): - continue - - # Extract/update parameters from swagger spec - parameters = spec.get("parameters", []) - if isinstance(parameters, list): - for param in parameters: - param_name = param.get("name") - if not param_name: - continue - - # Update existing param or create new one - if param_name in params: - # Update required field from swagger - params[param_name]["required"] = param.get("required", False) - if param.get("description"): - params[param_name]["description"] = param["description"] - else: - schema = param.get("schema", {}) - params[param_name] = { - "type": schema.get("type", "string"), - "required": param.get("required", False), - "description": param.get("description") or f"{param.get('in')} parameter", - "in": param.get("in"), - } - if schema.get("default") is not None: - params[param_name]["default"] = schema["default"] - - # Extract request body schema and required fields - req_body = spec.get("requestBody", {}) - req_body_content = req_body.get("content", {}) - req_body_json = req_body_content.get("application/json", {}) - req_body_schema = req_body_json.get("schema", {}) - - if req_body_schema: - required_fields = req_body_schema.get("required", []) - req_body_props = req_body_schema.get("properties", {}) - - for name, schema in req_body_props.items(): - is_required = name in required_fields - if name in params: - # Update required from schema.required array - params[name]["required"] = is_required - if schema.get("description"): - params[name]["description"] = schema["description"] - else: - params[name] = { - "type": schema.get("type", "string"), - "required": is_required, - "description": schema.get("description", ""), - } - - # Extract response schema - responses = spec.get("responses", {}) - success_response = responses.get("200") or responses.get("201") - if success_response: - res_content = success_response.get("content", {}) - res_json = res_content.get("application/json", {}) - res_schema = res_json.get("schema", {}) - res_body_props = res_schema.get("properties", {}) - - if isinstance(res_body_props, dict): - for name, schema in res_body_props.items(): - if name not in response: - response[name] = { - "type": schema.get("type", "string"), - "description": schema.get("description", ""), - } - - # Only process first method found - return diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/cli.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/cli.py deleted file mode 100644 index cd62a65a..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/cli.py +++ /dev/null @@ -1,1193 +0,0 @@ -"""CLI entry point for API Manager.""" - -import json -import sys -from pathlib import Path - -import click - -from . import __version__ -from .config import Config, get_project_paths -from .exceptions import ApiManagerError - -# Global verbose flag -_verbose = False - - -def log_verbose(message: str) -> None: - """Print message only if verbose mode is enabled.""" - if _verbose: - click.secho(f" [DEBUG] {message}", fg="cyan") - - -@click.group() -@click.version_option(version=__version__, prog_name="api-manager") -def cli(): - """API Manager - Manage API integrations for AEM Forms. - - \b - Directory Structure: - refs/apis/generated/ - ├── spec/ OpenAPI YAML files - ├── api-clients/ Generated JS clients (*.js + index.js) - └── registry.json API registry - - \b - Data Flow: - AEM FDM --[sync]--> refs/apis/generated/spec/*.yaml - --[build]--> refs/apis/generated/api-clients/ - --> refs/apis/generated/registry.json - - \b - Commands: - list - List all APIs from YAML specs - show - Show API details from YAML specs - build - Parse YAML -> generate api-clients + registry - add - Create new API YAML file (interactive) - sync - Fetch from AEM FDM -> create/update YAML files - test - Check for YAML spec changes - - \b - Examples: - api-manager list # List all APIs - api-manager show apiName # Show API details - api-manager sync --dry-run # Preview changes from AEM - api-manager sync # Sync from AEM (with confirmation) - api-manager build # Build registry + api-clients from YAML - api-manager test # Check for differences - """ - pass - - -@cli.command("list") -@click.option("--json", "as_json", is_flag=True, help="Output as JSON") -@click.option("-m", "--method", help="Filter by HTTP method") -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def list_apis(as_json: bool, method: str, verbose: bool): - """List all APIs from YAML specs. - - \b - Examples: - api-manager list - api-manager list --json - api-manager list --method POST - """ - global _verbose - _verbose = verbose - - from .openapi_parser import build_registry - - registry = build_registry() - - # Filter by method if specified - if method: - method = method.upper() - registry = { - name: config - for name, config in registry.items() - if config.get("method", "POST").upper() == method - } - - apis = list(registry.keys()) - - if as_json: - details = [] - for name in apis: - config = registry[name] - details.append( - { - "name": config.get("name", name), - "description": config.get("description", ""), - "endpoint": config.get("endpoint", ""), - "method": config.get("method", "POST"), - } - ) - click.echo(json.dumps(details, indent=2)) - else: - if not apis: - click.echo("No APIs found.") - return - - click.echo(f"\nFound {len(apis)} API(s):\n") - click.echo(f" {'Name':<28}{'Method':<10}Endpoint") - click.echo(" " + "-" * 70) - - for name in apis: - config = registry[name] - api_method = config.get("method", "POST") - endpoint = config.get("endpoint", "") - click.echo(f" {name:<28}{api_method:<10}{endpoint}") - - click.echo("") - - -@cli.command("show") -@click.argument("name") -@click.option("--json", "as_json", is_flag=True, help="Output as JSON") -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def show_api(name: str, as_json: bool, verbose: bool): - """Show API details from YAML spec. - - \b - NAME: API name (YAML filename without extension) - - \b - Examples: - api-manager show customerIdentification - api-manager show customerIdentification --json - """ - global _verbose - _verbose = verbose - - from .openapi_parser import build_registry - - registry = build_registry() - - if name not in registry: - click.secho(f"Error: API '{name}' not found.", fg="red", err=True) - click.echo("\nAvailable APIs:") - for api_name in sorted(registry.keys()): - click.echo(f" - {api_name}") - sys.exit(1) - - config = registry[name] - - if as_json: - click.echo(json.dumps(config, indent=2)) - else: - api_name = config.get("name", name) - click.echo(f"\n{api_name}") - click.echo("=" * len(api_name)) - click.echo(f"\n{config.get('description', '')}\n") - - click.echo("Endpoint") - click.echo("--------") - click.echo(f" {config.get('method', 'POST')} {config.get('endpoint', '')}\n") - - if config.get("bodyStructure"): - click.echo(f"Body Structure: {config['bodyStructure']}\n") - - params = config.get("params", {}) - if params: - # Find required params - required_params = [name for name, p in params.items() if p.get("required")] - - click.echo("Parameters") - click.echo("----------") - for param_name, param_config in params.items(): - required = " [required]" if param_name in required_params else "" - default = "" - if param_config.get("default") is not None: - default = f" (default: {param_config['default']})" - click.echo( - f" {param_name}: {param_config.get('type', 'string')}{required}{default}" - ) - click.echo(f" {param_config.get('description', '')}") - click.echo("") - - response = config.get("response", {}) - if response: - click.echo("Response Fields") - click.echo("---------------") - for field_name, field_config in response.items(): - click.echo(f" {field_name}: {field_config.get('type', 'string')}") - click.echo(f" {field_config.get('description', '')}") - click.echo("") - - if config.get("successCondition"): - click.echo("Success Condition") - click.echo("-----------------") - click.echo(f" {config['successCondition']}\n") - - if config.get("notes"): - click.echo("Notes") - click.echo("-----") - notes = config["notes"] - if isinstance(notes, list): - for note in notes: - click.echo(f" - {note}") - else: - click.echo(f" {notes}") - click.echo("") - - -@cli.command("build") -@click.option( - "--dry-run", is_flag=True, help="Preview what would be built (no files written)" -) -@click.option("--skip-clients", is_flag=True, help="Skip generating API client files") -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def build_registry(dry_run: bool, skip_clients: bool, verbose: bool): - """Parse OpenAPI YAML files and generate api-clients. - - \b - What it does: - 1. Reads all refs/apis/generated/spec/*.yaml files (OpenAPI 3.0 format) - 2. Generates refs/apis/generated/registry.json - 3. Generates refs/apis/generated/api-clients/*.js (client functions) - 4. Generates refs/apis/generated/api-clients/index.js (re-exports) - - \b - Examples: - api-manager build # Build registry + api-clients - api-manager build --dry-run # Preview what would be built - api-manager build --skip-clients # Build registry only - """ - global _verbose - _verbose = verbose - - from .generator import generate_all_clients - from .openapi_parser import build_registry as do_build - from .openapi_parser import save_registry - - spec_dir, api_clients_dir, generated_dir = get_project_paths() - - click.echo( - "Building registry from refs/apis/generated/spec/*.yaml (OpenAPI 3.0)...\n" - ) - - registry = do_build() - count = len(registry) - - if dry_run: - click.echo("\n[Dry Run] Would generate clients for:") - for name, config in list(registry.items())[:20]: - click.echo(f" - {name}: {config.get('endpoint', '')}") - if count > 20: - click.echo(f" ... and {count - 20} more") - click.echo(f"\nTotal: {count} API(s)") - return - - # Save registry.json at generated_dir level - registry_path = save_registry(registry) - click.secho(f"\nSaved registry.json with {count} API(s)", fg="green") - click.echo(f"Location: {registry_path}") - - # Generate API client files + index.js - if not skip_clients: - click.echo("\nGenerating API clients...") - gen_stats = generate_all_clients(registry, api_clients_dir) - click.secho( - f"Generated {gen_stats['files_generated']} API client files + index.js", - fg="green", - ) - click.echo(f"Location: {api_clients_dir}") - if gen_stats.get("errors"): - click.secho(f"Errors: {len(gen_stats['errors'])}", fg="yellow") - for err in gen_stats["errors"][:3]: - click.echo(f" • {err}") - - -def _prompt_for_params() -> dict: - """Interactively prompt for request parameters.""" - params = {} - click.echo("\n--- Request Parameters ---") - click.echo("(Press Enter with empty name to finish)") - - while True: - click.echo("") - param_name = click.prompt("Parameter name", default="", show_default=False) - if not param_name: - break - - param_type = click.prompt( - " Type", - type=click.Choice(["string", "number", "boolean", "object", "array"]), - default="string", - ) - param_required = click.confirm(" Required?", default=False) - param_location = click.prompt( - " Location", - type=click.Choice(["body", "header", "query", "path"]), - default="body", - ) - param_default = click.prompt( - " Default value (optional)", default="", show_default=False - ) - param_desc = click.prompt(" Description", default="", show_default=False) - - params[param_name] = { - "type": param_type, - "required": param_required, - "in": param_location, - "description": param_desc or f"{param_location} parameter", - } - if param_default: - params[param_name]["default"] = param_default - - click.secho(f" Added: {param_name}", fg="green") - - return params - - -def _prompt_for_response() -> dict: - """Interactively prompt for response fields.""" - response = {} - click.echo("\n--- Response Fields ---") - click.echo("(Press Enter with empty name to finish)") - - while True: - click.echo("") - field_name = click.prompt("Field name", default="", show_default=False) - if not field_name: - break - - field_type = click.prompt( - " Type", - type=click.Choice(["string", "number", "boolean", "object", "array"]), - default="string", - ) - field_desc = click.prompt(" Description", default="", show_default=False) - - response[field_name] = { - "type": field_type, - "description": field_desc, - } - - click.secho(f" Added: {field_name}", fg="green") - - return response - - -@cli.command("add") -@click.option("-f", "--file", "config_file", help="JSON file with API config") -@click.option("-n", "--name", "api_name", help="API name (skip interactive mode)") -@click.option("-e", "--endpoint", help="API endpoint") -@click.option("-d", "--description", help="API description") -@click.option("--no-build", is_flag=True, help="Skip rebuilding registry") -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def add_api( - config_file: str, - api_name: str, - endpoint: str, - description: str, - no_build: bool, - verbose: bool, -): - """Add a new API interactively or from file. - - \b - Without options: Interactive mode prompts for all details - With -f: Load from JSON file - With -n: Quick creation with minimal prompts - - \b - Examples: - api-manager add # Interactive mode - api-manager add -f api-config.json # From JSON file - api-manager add -n myNewApi -e /api/test # Quick mode - """ - global _verbose - _verbose = verbose - - from .openapi_parser import build_registry as do_build - from .openapi_writer import generate_filename, write_api_to_openapi - - spec_dir, api_clients_dir, generated_dir = get_project_paths() - - api_config = None - - if config_file: - # Load from JSON file - try: - with open(config_file, "r", encoding="utf-8") as f: - api_config = json.load(f) - except Exception as e: - click.secho(f"Error reading file: {e}", fg="red", err=True) - sys.exit(1) - elif api_name: - # Quick creation from options - api_config = { - "name": api_name, - "description": description or f"{api_name} API", - "endpoint": endpoint or f"/api/{api_name.lower()}", - "method": "POST", - "params": {}, - "response": {}, - } - else: - # Interactive mode - click.secho("\n=== Add New API Integration ===\n", fg="blue", bold=True) - - # Basic info - click.echo("--- Basic Information ---") - name = click.prompt("API Name") - desc = click.prompt("Description", default=f"{name} API") - endpoint_url = click.prompt("Endpoint URL") - method = click.prompt( - "HTTP Method", - type=click.Choice(["POST", "GET", "PUT", "DELETE", "PATCH"]), - default="POST", - ) - content_type = click.prompt("Content-Type", default="application/json") - - # Execution info - click.echo("\n--- Execution Info ---") - execute_at_client = click.confirm("Execute at Client?", default=True) - encryption_required = click.confirm("Encryption Required?", default=False) - auth_type = click.prompt( - "Authentication", - type=click.Choice(["None", "Basic", "Bearer", "OAuth"]), - default="None", - ) - is_array = click.confirm("Response is Array?", default=False) - - # Parameters - params = _prompt_for_params() - - # Response fields - response = _prompt_for_response() - - # Add default response fields if none provided - if not response: - if click.confirm( - "\nAdd default response fields (status.responseCode, status.errorCode)?", - default=True, - ): - response = { - "status.responseCode": { - "type": "string", - "description": "0 for success", - }, - "status.errorCode": { - "type": "string", - "description": "Error code if failed", - }, - "status.errorMsg": { - "type": "string", - "description": "Error message if failed", - }, - } - - # Success condition - click.echo("\n--- Success Condition ---") - success_condition = click.prompt( - "Success Condition (JS expression, Enter to skip — response.ok is used by default)", - default="", - show_default=False, - ) - - # Notes - click.echo("\n--- Notes (optional) ---") - notes = [] - while True: - note = click.prompt( - "Add note (Enter to skip)", default="", show_default=False - ) - if not note: - break - notes.append(note) - - # Build config - api_config = { - "name": name, - "description": desc, - "endpoint": endpoint_url, - "method": method, - "contentType": content_type, - "executeAtClient": execute_at_client, - "encryptionRequired": encryption_required, - "authType": auth_type, - "isOutputAnArray": is_array, - "params": params, - "response": response, - } - if success_condition: - api_config["successCondition"] = success_condition - if notes: - api_config["notes"] = notes - - # Show summary - click.echo("\n" + "=" * 50) - click.secho("API Configuration Summary:", fg="blue", bold=True) - click.echo(f" Name: {name}") - click.echo(f" Endpoint: {method} {endpoint_url}") - click.echo(f" Parameters: {len(params)}") - click.echo(f" Response Fields: {len(response)}") - click.echo("=" * 50) - - if not click.confirm("\nCreate this API?", default=True): - click.echo("Cancelled.") - return - - # Generate YAML - yaml_content = write_api_to_openapi(api_config) - filename = generate_filename(api_config["name"]) - filepath = spec_dir / filename - - # Check if file exists - if filepath.exists(): - click.secho(f"Error: File already exists: {filepath}", fg="red", err=True) - click.echo("Use a different name or delete the existing file first.") - sys.exit(1) - - # Write file - filepath.write_text(yaml_content, encoding="utf-8") - click.secho(f"\nCreated: {filepath}", fg="green") - - # Regenerate registry + API clients if requested - if not no_build: - from .generator import generate_all_clients - from .openapi_parser import save_registry - - click.echo("\nRebuilding...") - registry = do_build() - save_registry(registry) - gen_stats = generate_all_clients(registry, api_clients_dir) - click.echo( - f"Updated registry.json + {gen_stats['files_generated']} API clients + index.js" - ) - - -@cli.command("sync") -@click.option("--dry-run", is_flag=True, help="Preview changes without writing files") -@click.option("-y", "--yes", is_flag=True, help="Skip confirmation prompt") -@click.option("--host", help="AEM host URL (or set AEM_HOST env var)") -@click.option("--auth", help="Authorization header (or set AEM_AUTH_HEADER env var)") -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def sync_from_aem(dry_run: bool, yes: bool, host: str, auth: str, verbose: bool): - """Fetch APIs from AEM FDM and sync to OpenAPI YAML files. - - \b - What it does: - 1. Fetches all api-integration definitions from AEM FDM - 2. Writes to temporary folder (.sync-preview/) - 3. Compares with current YAML specs - 4. Shows what would change - 5. Asks for confirmation - 6. If confirmed: updates YAML files and generates api-clients - - \b - Examples: - api-manager sync --dry-run # Preview changes only - api-manager sync # Sync with confirmation - api-manager sync -y # Sync without confirmation - """ - global _verbose - _verbose = verbose - - import json - import os - import shutil - - from dotenv import load_dotenv - - from .aem_client import AemFdmClient - from .config import Config - from .exceptions import AemConnectionError, ConfigurationError - from .openapi_parser import load_registry - from .openapi_writer import generate_filename, write_api_to_openapi - - spec_dir, api_clients_dir, generated_dir = get_project_paths() - - # Load .env from user's current working directory - cwd_env_path = Path.cwd() / ".env" - if cwd_env_path.exists(): - load_dotenv(cwd_env_path) - else: - from dotenv import find_dotenv - - load_dotenv(dotenv_path=find_dotenv(usecwd=True)) - - # Override with CLI options - if host: - os.environ["AEM_HOST"] = host - if auth: - os.environ["AEM_AUTH_HEADER"] = auth - - # Initialize client - try: - config = Config.from_env() - client = AemFdmClient(config) - except ConfigurationError as e: - click.secho(f"Configuration error: {e}", fg="red", err=True) - click.echo("\nTo configure AEM connection:") - click.echo(" 1. Set environment variables in .env (project root):") - click.echo(" AEM_HOST=https://author.aem.example.com") - click.echo(" AEM_TOKEN=your-bearer-token") - click.echo(" 2. Or use --host and --auth options") - sys.exit(1) - - click.echo("Fetching APIs from AEM FDM...\n") - - try: - remote_apis = client.fetch_all_apis() - except AemConnectionError as e: - click.secho(f"Failed to fetch from AEM: {e}", fg="red", err=True) - sys.exit(1) - - click.echo(f"Found {len(remote_apis)} API(s) in AEM FDM") - - # Load current registry for comparison - current_registry = load_registry() - - # Create temp directory for preview - temp_dir = spec_dir / ".sync-preview" - - try: - # Clean up any previous preview - if temp_dir.exists(): - shutil.rmtree(temp_dir) - temp_dir.mkdir(parents=True) - - click.echo("Processing AEM APIs...") - - # Identify local-only markdown files (exist locally but not in AEM) - remote_names = set() - for api in remote_apis: - filename = generate_filename(api.get("name", "unknown")) - remote_names.add(filename.lower()) - - local_only_files = [] - for yaml_file in spec_dir.glob("*.yaml"): - if yaml_file.name.startswith("_"): - continue - if yaml_file.name.lower() not in remote_names: - local_only_files.append(yaml_file.name) - - # Step 1: Write YAML files to temp folder (mark as aem-api-integration source) - # Track filename collisions (case-insensitive) - filename_map = {} - collisions = [] - for api in remote_apis: - api["source"] = "aem-api-integration" # Mark as synced from AEM - name = api.get("name", "unknown") - filename = generate_filename(name) - - if filename in filename_map: - collisions.append( - f"{name} → {filename} (overwrites {filename_map[filename]})" - ) - filename_map[filename] = name - - yaml_content = write_api_to_openapi(api) - filepath = temp_dir / filename - filepath.write_text(yaml_content, encoding="utf-8") - - click.echo("Building registry...") - - # Step 2: Build registry.json by parsing temp YAML files - from .openapi_parser import parse_openapi_file - - temp_registry = {} - parse_failures = [] - for yaml_file in temp_dir.glob("*.yaml"): - if yaml_file.name.startswith("_"): - continue - api_config = parse_openapi_file(yaml_file) - if api_config: - key = yaml_file.stem - temp_registry[key] = api_config - else: - parse_failures.append(yaml_file.name) - - # Save temp registry.json - temp_registry_path = temp_dir / "registry.json" - with open(temp_registry_path, "w", encoding="utf-8") as f: - json.dump(temp_registry, f, indent=2) - - click.echo("Running tests...") - - # Step 3: Run 100% coverage tests comparing current vs temp registry - passed, failures = run_comparison_tests(current_registry, temp_registry) - - # Filter out local_only from failures (we show local separately) - actual_changes = [f for f in failures if f["type"] != "local_only"] - - # Find local APIs in current registry (source != "aem-api-integration") - local_apis = [ - key - for key, api in current_registry.items() - if api.get("source", "local") != "aem-api-integration" - ] - - # Show summary - click.secho("\n" + "=" * 60, fg="blue") - click.secho("SYNC PREVIEW", fg="blue", bold=True) - click.secho("=" * 60, fg="blue") - - # Show summary counts - aem_fetched = len(remote_apis) - aem_written = len(filename_map) # Unique files written - aem_parsed = len(temp_registry) - collision_count = len(collisions) - parse_fail_count = len(parse_failures) - local_api_count = len(local_apis) - local_file_count = len(local_only_files) - - click.echo( - f"\n From AEM: {aem_fetched} APIs → {aem_written} files → {aem_parsed} parsed" - ) - if collision_count > 0: - click.secho( - f" ⚠ AEM has {collision_count} case-variant duplicates (should be fixed in AEM):", - fg="yellow", - ) - for c in collisions[:3]: - click.echo(f" • {c}") - if collision_count > 3: - click.echo(f" ... and {collision_count - 3} more") - if parse_fail_count > 0: - click.secho(f" Parse failures: {parse_fail_count}", fg="red") - for f in parse_failures[:3]: - click.echo(f" • {f}") - if parse_fail_count > 3: - click.echo(f" ... and {parse_fail_count - 3} more") - if local_api_count > 0: - click.echo(f" Local APIs: {local_api_count} (manually added)") - if local_file_count > 0: - click.echo(f" Local files: {local_file_count} (not in AEM)") - - if not actual_changes: - click.secho( - "\n ✓ All tests passed. Local registry is up to date with AEM.", - fg="green", - ) - if local_apis: - click.secho( - f"\n Local APIs ({len(local_apis)}) - manually added, will be preserved:", - fg="cyan", - ) - for api in local_apis[:5]: - click.echo(f" • {api}") - if len(local_apis) > 5: - click.echo(f" ... and {len(local_apis) - 5} more") - if local_only_files: - click.secho( - f"\n Local files ({len(local_only_files)}) - not in AEM, will be preserved:", - fg="yellow", - ) - for f in local_only_files[:5]: - click.echo(f" • {f}") - if len(local_only_files) > 5: - click.echo(f" ... and {len(local_only_files) - 5} more") - - # Always regenerate clients for local-only YAMLs (template or spec may have changed) - click.echo( - f"\n Regenerating clients for {len(local_only_files)} local YAML file(s)..." - ) - merged_registry = dict(temp_registry) - for key, api in current_registry.items(): - if api.get("source", "local") != "aem-api-integration": - merged_registry[key] = api - for local_file in local_only_files: - local_path = spec_dir / local_file - local_key = local_path.stem - if local_key not in merged_registry: - local_config = parse_openapi_file(local_path) - if local_config: - local_config["source"] = "local" - merged_registry[local_key] = local_config - - # Save updated registry and regenerate all clients - registry_path = generated_dir / "registry.json" - generated_dir.mkdir(parents=True, exist_ok=True) - with open(registry_path, "w", encoding="utf-8") as f: - json.dump(merged_registry, f, indent=2) - - api_clients_dir.mkdir(parents=True, exist_ok=True) - from .generator import generate_all_clients - - gen_stats = generate_all_clients(merged_registry, api_clients_dir) - click.secho( - f" ✓ Regenerated {gen_stats['files_generated']} API clients", - fg="green", - ) - - return - - # Show changes from AEM - click.echo(f"\n{format_test_results(actual_changes)}") - - if local_apis: - click.secho( - f" Local APIs ({len(local_apis)}) - manually added, will be preserved:", - fg="cyan", - ) - for api in local_apis[:5]: - click.echo(f" • {api}") - if len(local_apis) > 5: - click.echo(f" ... and {len(local_apis) - 5} more") - click.echo("") - - if local_only_files: - click.secho( - f" Local files ({len(local_only_files)}) - not in AEM, will be preserved:", - fg="yellow", - ) - for f in local_only_files[:5]: - click.echo(f" • {f}") - if len(local_only_files) > 5: - click.echo(f" ... and {len(local_only_files) - 5} more") - click.echo("") - - click.secho("=" * 60, fg="blue") - click.echo(f"Total: {len(actual_changes)} change(s) from AEM") - - # Dry run - stop here - if dry_run: - click.secho("\n[Dry Run] No changes applied.", fg="cyan") - return - - # Ask for confirmation - if not yes: - click.echo("") - if not click.confirm( - click.style("Apply these changes?", fg="yellow", bold=True), - default=False, - ): - click.echo("Cancelled. No changes made.") - return - - # Apply changes - copy from temp folder to actual locations - click.echo("\nApplying changes...") - - # Delete YAML files that were removed from AEM (had source: aem-api-integration) - for failure in actual_changes: - if failure["type"] == "removed_from_aem": - api_key = failure["api"] - yaml_file = spec_dir / f"{api_key}.yaml" - if yaml_file.exists(): - yaml_file.unlink() - log_verbose(f"Deleted: {yaml_file.name}") - - # Copy YAML files from temp to refs/apis/ - for yaml_file in temp_dir.glob("*.yaml"): - dest = spec_dir / yaml_file.name - shutil.copy2(yaml_file, dest) - - # Merge registries: AEM APIs + local APIs (preserve manually added) - merged_registry = dict(temp_registry) # Start with AEM APIs - for key, api in current_registry.items(): - if api.get("source", "local") != "aem-api-integration": - # Preserve local APIs - merged_registry[key] = api - - # Parse local-only YAML files into registry (not from AEM, added manually) - for local_file in local_only_files: - local_path = spec_dir / local_file - local_key = local_path.stem - if local_key not in merged_registry: - local_config = parse_openapi_file(local_path) - if local_config: - local_config["source"] = "local" - merged_registry[local_key] = local_config - log_verbose(f"Parsed local YAML: {local_file}") - - # Save registry.json at generated_dir level - registry_path = generated_dir / "registry.json" - generated_dir.mkdir(parents=True, exist_ok=True) - with open(registry_path, "w", encoding="utf-8") as f: - json.dump(merged_registry, f, indent=2) - - # Generate API clients + index.js - click.echo("Generating API clients...") - api_clients_dir.mkdir(parents=True, exist_ok=True) - from .generator import generate_all_clients - - gen_stats = generate_all_clients(merged_registry, api_clients_dir) - - click.secho("\nSync complete!", fg="green") - click.echo( - f" - Updated {aem_written} API YAML files in refs/apis/generated/spec/" - ) - click.echo( - f" - Generated {gen_stats['files_generated']} API clients + index.js in refs/apis/generated/api-clients/" - ) - click.echo(f" - Saved registry.json in refs/apis/generated/") - - finally: - # Clean up temp directory - if temp_dir.exists(): - shutil.rmtree(temp_dir) - - -def run_comparison_tests( - current_registry: dict, new_registry: dict -) -> tuple[bool, list[dict]]: - """Run 100% coverage tests comparing two registries. - - Tests: - - API added/removed (distinguishes AEM vs local by source property) - - Endpoint URL changed - - HTTP method changed - - Parameters added/removed - - Required params changed - - Response fields added/removed - - Args: - current_registry: Existing registry (from registry.json) - new_registry: New registry (from parsed markdown or AEM) - - Returns: - Tuple of (all_passed, list of failures) - """ - failures = [] - - # Check for APIs in current but not in new - for api_key in current_registry: - if api_key not in new_registry: - current_api = current_registry[api_key] - source = current_api.get("source", "local") - if source == "aem-api-integration": - # Was synced from AEM but no longer exists there - failures.append( - { - "type": "removed_from_aem", - "api": api_key, - "message": f"'{api_key}' removed from AEM", - } - ) - else: - # Local-only API, not in AEM (this is informational, not a failure) - failures.append( - { - "type": "local_only", - "api": api_key, - "message": f"'{api_key}' (local only, not in AEM)", - } - ) - - # Check for new APIs in AEM - for api_key in new_registry: - if api_key not in current_registry: - failures.append( - { - "type": "new_in_aem", - "api": api_key, - "message": f"'{api_key}' new in AEM", - } - ) - - # Check for changes in existing APIs - for api_key in new_registry: - if api_key not in current_registry: - continue - - current = current_registry[api_key] - new = new_registry[api_key] - - # Check endpoint change - if current.get("endpoint") != new.get("endpoint"): - failures.append( - { - "type": "endpoint_changed", - "api": api_key, - "old": current.get("endpoint"), - "new": new.get("endpoint"), - "message": f"API '{api_key}' endpoint: {current.get('endpoint')} → {new.get('endpoint')}", - } - ) - - # Check method change - if current.get("method", "POST") != new.get("method", "POST"): - failures.append( - { - "type": "method_changed", - "api": api_key, - "old": current.get("method", "POST"), - "new": new.get("method", "POST"), - "message": f"API '{api_key}' method: {current.get('method', 'POST')} → {new.get('method', 'POST')}", - } - ) - - # Check param changes - current_params = set(current.get("params", {}).keys()) - new_params = set(new.get("params", {}).keys()) - - added_params = new_params - current_params - removed_params = current_params - new_params - - if added_params: - failures.append( - { - "type": "params_added", - "api": api_key, - "params": list(added_params), - "message": f"API '{api_key}' new params: {', '.join(sorted(added_params))}", - } - ) - - if removed_params: - failures.append( - { - "type": "params_removed", - "api": api_key, - "params": list(removed_params), - "message": f"API '{api_key}' removed params: {', '.join(sorted(removed_params))}", - } - ) - - # Check required params changes - current_required = { - name - for name, cfg in current.get("params", {}).items() - if cfg.get("required") - } - new_required = { - name for name, cfg in new.get("params", {}).items() if cfg.get("required") - } - - added_required = new_required - current_required - removed_required = current_required - new_required - - if added_required: - failures.append( - { - "type": "required_added", - "api": api_key, - "params": list(added_required), - "message": f"API '{api_key}' new required params: {', '.join(sorted(added_required))}", - } - ) - - if removed_required: - failures.append( - { - "type": "required_removed", - "api": api_key, - "params": list(removed_required), - "message": f"API '{api_key}' no longer required: {', '.join(sorted(removed_required))}", - } - ) - - # Check response field changes - current_response = set(current.get("response", {}).keys()) - new_response = set(new.get("response", {}).keys()) - - added_response = new_response - current_response - removed_response = current_response - new_response - - if added_response: - failures.append( - { - "type": "response_added", - "api": api_key, - "fields": list(added_response), - "message": f"API '{api_key}' new response fields: {', '.join(sorted(added_response))}", - } - ) - - if removed_response: - failures.append( - { - "type": "response_removed", - "api": api_key, - "fields": list(removed_response), - "message": f"API '{api_key}' removed response fields: {', '.join(sorted(removed_response))}", - } - ) - - all_passed = len(failures) == 0 - return all_passed, failures - - -def format_test_results(failures: list[dict]) -> str: - """Format test failures for display.""" - if not failures: - return "All tests passed. No changes detected." - - lines = [f"Found {len(failures)} change(s):\n"] - - # Group failures by type - by_type = {} - for f in failures: - t = f["type"] - if t not in by_type: - by_type[t] = [] - by_type[t].append(f) - - type_labels = { - "new_in_aem": "New in AEM", - "removed_from_aem": "Removed from AEM", - "local_only": "Local Only (will be preserved)", - "endpoint_changed": "Endpoint Changed", - "method_changed": "Method Changed", - "params_added": "New Parameters", - "params_removed": "Removed Parameters", - "required_added": "New Required Params", - "required_removed": "No Longer Required", - "response_added": "New Response Fields", - "response_removed": "Removed Response Fields", - } - - for change_type, items in by_type.items(): - label = type_labels.get(change_type, change_type) - lines.append(f" {label}:") - for item in items[:10]: - lines.append(f" - {item['message']}") - if len(items) > 10: - lines.append(f" ... and {len(items) - 10} more") - lines.append("") - - return "\n".join(lines) - - -@cli.command("test") -@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") -def run_api_tests(verbose: bool): - """Test for differences between markdown files and registry.json. - - \b - What it tests (100% coverage): - - API added/removed - - Endpoint URL changed - - HTTP method changed - - Parameters added/removed - - Required params changed - - Response fields added/removed - - \b - Compares: - - Builds temp registry from refs/apis/*.md - - Tests temp registry vs current registry.json - - \b - Use Cases: - - Check if markdown edits need a rebuild - - Verify registry.json is up to date - - CI/CD validation - - \b - Examples: - api-manager test # Check for differences - """ - global _verbose - _verbose = verbose - - from .parser import build_registry as do_build - from .parser import load_registry - - click.echo("Building registry from markdown...") - new_registry = do_build() - - click.echo("Loading current registry.json...") - current_registry = load_registry() - - if not current_registry: - click.secho( - "No registry.json found. Run 'api-manager build' first.", fg="yellow" - ) - sys.exit(1) - - click.echo("Running tests...") - - # Run tests - passed, failures = run_comparison_tests(current_registry, new_registry) - - if passed: - click.secho("\nAll tests passed. Registry is up to date.", fg="green") - return - - # Show failures - click.echo(f"\n{format_test_results(failures)}") - - click.secho("Tests failed.", fg="red") - click.echo("\nOptions:") - click.echo(" - Run 'api-manager build' to update registry.json") - click.echo(" - Or fix the markdown files if changes are unintended") - sys.exit(1) - - -if __name__ == "__main__": - cli() diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/config.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/config.py deleted file mode 100644 index 440ddc27..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/config.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Configuration management for API Manager.""" - -import os -from dataclasses import dataclass -from pathlib import Path -from typing import Optional - -from dotenv import find_dotenv, load_dotenv - -from .exceptions import ConfigurationError - - -@dataclass -class Config: - """API Manager configuration.""" - - aem_host: str - auth_header: str - refs_dir: Path - api_clients_dir: Path - - @classmethod - def from_env(cls, env_file: Optional[Path] = None) -> "Config": - """Load configuration from environment variables. - - Args: - env_file: Optional path to .env file - - Returns: - Config instance - - Raises: - ConfigurationError: If required variables are missing - """ - # Load .env file if it exists - if env_file: - load_dotenv(env_file) - else: - # Look for .env in the user's current working directory - cwd_env_path = Path.cwd() / ".env" - if cwd_env_path.exists(): - load_dotenv(cwd_env_path) - else: - # Fallback: let python-dotenv search upward from cwd - load_dotenv(dotenv_path=find_dotenv(usecwd=True)) - - # Get AEM host - aem_host = os.getenv("AEM_HOST") - if not aem_host: - raise ConfigurationError("AEM_HOST not configured") - - # Get auth header (support both AEM_TOKEN and AEM_AUTH_HEADER) - token = os.getenv("AEM_TOKEN") - auth_header = os.getenv("AEM_AUTH_HEADER") - - if token: - auth_header = f"Bearer {token}" - elif not auth_header: - raise ConfigurationError("AEM_TOKEN or AEM_AUTH_HEADER not configured") - - # Get paths relative to user's current working directory - project_root = Path.cwd() - refs_dir = project_root / "refs" / "apis" - api_clients_dir = refs_dir / "generated" / "api-clients" - - return cls( - aem_host=aem_host, - auth_header=auth_header, - refs_dir=refs_dir, - api_clients_dir=api_clients_dir, - ) - - -def get_project_paths() -> tuple[Path, Path, Path]: - """Get project paths without requiring AEM configuration. - - Returns: - Tuple of (spec_dir, api_clients_dir, generated_dir) - """ - project_root = Path.cwd() - generated_dir = project_root / "refs" / "apis" / "generated" - spec_dir = generated_dir / "spec" - api_clients_dir = generated_dir / "api-clients" - return spec_dir, api_clients_dir, generated_dir diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/exceptions.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/exceptions.py deleted file mode 100644 index 06d81d59..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/exceptions.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Custom exceptions for API Manager.""" - - -class ApiManagerError(Exception): - """Base exception for API Manager errors.""" - pass - - -class ConfigurationError(ApiManagerError): - """Configuration error.""" - pass - - -class AemConnectionError(ApiManagerError): - """AEM connection error.""" - pass - - -class ParseError(ApiManagerError): - """Parsing error.""" - pass diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/generator.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/generator.py deleted file mode 100644 index 87c1070b..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/generator.py +++ /dev/null @@ -1,247 +0,0 @@ -"""Generator - Generates JavaScript client files from registry using Jinja2. - -Generates AEM Forms-compatible async helper functions for API calls. -Uses globals.functions.request() for all HTTP requests. - -Features: -- Template-based code generation (Jinja2) -- Support for path, query, header, and body parameters -- Support for different HTTP methods (GET, POST, PUT, DELETE, PATCH) -- Configurable body structure (requestString wrapper) -""" - -import re -from pathlib import Path - -from jinja2 import Environment, FileSystemLoader - - -def _needs_quoting(key: str) -> bool: - """Check if a JS property key needs quoting (contains non-identifier chars).""" - return bool(re.search(r"[^a-zA-Z0-9_$]", key)) or (key and key[0].isdigit()) - - -def _js_key(key: str) -> str: - """Format a string as a JS object property key, quoting if needed.""" - return f"'{key}'" if _needs_quoting(key) else key - - -def _js_access(key: str) -> str: - """Format JS property access, using bracket notation if needed. - - Returns the full access pattern including the object reference style: - - 'name' -> '.name' (dot notation) - - 'special-name' -> "['special-name']" (bracket notation) - - Usage in template: params{{ p.name | js_access }} - """ - return f"['{key}']" if _needs_quoting(key) else f".{key}" - - -def to_js_identifier(name: str) -> str: - """Convert a string to a valid JavaScript identifier. - - Converts hyphens and other invalid characters to camelCase. - Examples: - 'aattri-test' -> 'aattriTest' - 'adobe-getssodata' -> 'adobeGetssodata' - 'INTEGRATION' -> 'INTEGRATION' - - Args: - name: The name to convert - - Returns: - Valid JavaScript identifier - """ - if not name: - return "unnamed" - - # Split by hyphens, underscores, or other non-alphanumeric - parts = re.split(r"[-_\s]+", name) - - # First part stays as-is - result = parts[0] - - # Subsequent parts get capitalized (camelCase) - for part in parts[1:]: - if part: - result += part[0].upper() + part[1:] - - # Ensure it doesn't start with a number - if result and result[0].isdigit(): - result = "_" + result - - # Remove any remaining invalid characters - result = re.sub(r"[^a-zA-Z0-9_$]", "", result) - - return result or "unnamed" - - -def _create_env() -> Environment: - """Create Jinja2 environment with templates and custom filters.""" - templates_dir = Path(__file__).parent / "templates" - - env = Environment( - loader=FileSystemLoader(templates_dir), - autoescape=False, # JS doesn't need HTML escaping - trim_blocks=True, - lstrip_blocks=True, - keep_trailing_newline=True, - ) - - # Add custom filters - env.filters["js_key"] = _js_key - env.filters["js_access"] = _js_access - - return env - - -def _prepare_params(params: dict) -> dict: - """Prepare params grouped by location. - - Args: - params: Raw params dict from API config - - Returns: - Dict with params grouped by location and other metadata - """ - all_params = [] - path_params = [] - query_params = [] - header_params = [] - body_params = [] - required_params = [] - - for name, config in params.items(): - # Use flat name (strip requestString. prefix) - leaf_name = name.split(".")[-1] if "." in name else name - location = config.get("in", "body") - - param = { - "name": leaf_name, - "type": config.get("type", "string"), - "description": config.get("description", ""), - "required": config.get("required", False), - "default": config.get("default"), - "location": location, - } - - all_params.append(param) - - if param["required"]: - required_params.append(param) - - if location == "path": - path_params.append(param) - elif location == "query": - query_params.append(param) - elif location == "header": - header_params.append(param) - else: - body_params.append(param) - - # Example params for JSDoc (first 2) - example_params = all_params[:2] if all_params else [] - - return { - "params": all_params, - "path_params": path_params, - "query_params": query_params, - "header_params": header_params, - "body_params": body_params, - "required_params": required_params, - "example_params": example_params, - } - - -def generate_client_file(api_key: str, api_config: dict, env: Environment = None) -> str: - """Generate JavaScript client file content for an API. - - Args: - api_key: API identifier (used as function name) - api_config: API configuration dict - env: Optional Jinja2 environment (created if not provided) - - Returns: - JavaScript file content - """ - if env is None: - env = _create_env() - - template = env.get_template("api-client.js.j2") - - param_groups = _prepare_params(api_config.get("params", {})) - - context = { - "api_key": api_key, - "function_name": to_js_identifier(api_key), - "name": api_config.get("name", api_key), - "description": api_config.get("description", f"{api_key} API"), - "endpoint": api_config.get("endpoint", ""), - "method": api_config.get("method", "POST").upper(), - "body_structure": api_config.get("bodyStructure", "requestString"), - "success_condition": api_config.get("successCondition"), - **param_groups, - } - - return template.render(**context) - - -def generate_index_file(api_keys: list[str], env: Environment = None) -> str: - """Generate index.js that re-exports all APIs. - - Args: - api_keys: List of API identifiers (file keys, may contain hyphens) - env: Optional Jinja2 environment (created if not provided) - - Returns: - JavaScript index file content - """ - if env is None: - env = _create_env() - - template = env.get_template("index.js.j2") - - apis = [ - {"key": key, "function_name": to_js_identifier(key)} - for key in sorted(api_keys) - ] - - return template.render(apis=apis) - - -def generate_all_clients(registry: dict, output_dir: Path) -> dict: - """Generate all client files from registry. - - Args: - registry: API registry dict - output_dir: Directory to write JS files to (api-clients/) - - Returns: - Stats dict with counts - """ - output_dir.mkdir(parents=True, exist_ok=True) - - env = _create_env() - api_keys = [] - errors = [] - - for api_key, api_config in registry.items(): - try: - content = generate_client_file(api_key, api_config, env) - filepath = output_dir / f"{api_key}.js" - filepath.write_text(content, encoding="utf-8") - api_keys.append(api_key) - except Exception as e: - errors.append(f"{api_key}: {e}") - - # Generate index.js in api-clients folder - index_content = generate_index_file(api_keys, env) - index_path = output_dir / "index.js" - index_path.write_text(index_content, encoding="utf-8") - - return { - "files_generated": len(api_keys), - "index_generated": True, - "errors": errors, - } diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/markdown_writer.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/markdown_writer.py deleted file mode 100644 index caa25b64..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/markdown_writer.py +++ /dev/null @@ -1,265 +0,0 @@ -"""Markdown Writer - Writes API config to markdown format.""" - -import re -from typing import Any - - -def write_api_to_markdown(api_config: dict) -> str: - """Convert API config to markdown string. - - Args: - api_config: API configuration object - - Returns: - Markdown content - """ - lines = [] - - # Title and description - lines.append(f"# {api_config.get('name', 'Unknown API')}") - lines.append("") - lines.append(api_config.get("description", "API description")) - lines.append("") - - # Endpoint section - lines.append("## Endpoint") - lines.append("") - lines.append("| Property | Value |") - lines.append("|----------|-------|") - lines.append(f"| URL | `{api_config.get('endpoint', '/api/endpoint')}` |") - lines.append(f"| Method | `{api_config.get('method', 'POST')}` |") - if api_config.get("contentType"): - lines.append(f"| Content-Type | `{api_config['contentType']}` |") - lines.append("") - - # Execution Info section (for API integrations) - lines.append("## Execution Info") - lines.append("") - lines.append("| Property | Value |") - lines.append("|----------|-------|") - # Source - distinguishes AEM-synced APIs from local ones - source = api_config.get("source", "local") - lines.append(f"| Source | {source} |") - if api_config.get("executeAtClient") is not None: - lines.append( - f"| Execute at Client | {'Yes' if api_config['executeAtClient'] else 'No'} |" - ) - if api_config.get("encryptionRequired") is not None: - lines.append( - f"| Encryption Required | {'Yes' if api_config['encryptionRequired'] else 'No'} |" - ) - if api_config.get("authType"): - lines.append(f"| Authentication | {api_config['authType']} |") - if api_config.get("isOutputAnArray") is not None: - lines.append( - f"| Response is Array | {'Yes' if api_config['isOutputAnArray'] else 'No'} |" - ) - lines.append("") - - # Request Parameters section - params = api_config.get("params", {}) - if params: - lines.append("## Request Parameters") - lines.append("") - lines.append( - "Parameters use flat names for SDK DX. The SDK wraps body params into `requestString` internally." - ) - lines.append("") - lines.append("| Parameter | Type | Required | Default | Location | Description |") - lines.append("|-----------|------|----------|---------|----------|-------------|") - - for name, config in params.items(): - # Strip requestString. prefix for flat SDK interface - flat_name = name.split(".")[-1] if "." in name else name - required = "Yes" if config.get("required") else "No" - default_val = config.get("default") if config.get("default") is not None else "-" - location = config.get("in", "body") - description = config.get("description", "") - lines.append( - f"| `{flat_name}` | {config.get('type', 'string')} | {required} | {default_val} | {location} | {description} |" - ) - lines.append("") - - # Response Fields section - response = api_config.get("response", {}) - if response: - lines.append("## Response Fields") - lines.append("") - lines.append("| Field | Type | Description |") - lines.append("|-------|------|-------------|") - - for name, config in response.items(): - lines.append( - f"| `{name}` | {config.get('type', 'string')} | {config.get('description', '')} |" - ) - lines.append("") - - # Success Condition section - if api_config.get("successCondition"): - lines.append("## Success Condition") - lines.append("") - lines.append(f"`{api_config['successCondition']}`") - lines.append("") - - # Notes section - if api_config.get("notes"): - lines.append("## Notes") - lines.append("") - notes = api_config["notes"] - if not isinstance(notes, list): - notes = [notes] - for note in notes: - lines.append(f"- {note}") - lines.append("") - - # FDM Source (if synced from AEM) - if api_config.get("fdmName"): - lines.append("<!-- ") - lines.append(f"FDM Source: {api_config['fdmName']}") - lines.append("Synced from AEM FDM") - lines.append("-->") - lines.append("") - - return "\n".join(lines) - - -def generate_filename(api_name: str) -> str: - """Generate filename from API name. - - Args: - api_name: API name - - Returns: - Filename (without path) - """ - # Lowercase for filesystem compatibility (macOS is case-insensitive) - # Replace spaces and special chars with hyphens - filename = re.sub(r"[^a-z0-9]+", "-", api_name.lower()) - filename = filename.strip("-") - return f"{filename}.md" - - -def generate_index(apis: list[dict], sync_stats: dict = None) -> str: - """Generate _index.md content with current API statistics. - - Args: - apis: List of API configurations - sync_stats: Optional sync statistics dict - - Returns: - Markdown content for _index.md - """ - from datetime import datetime - - total = len(apis) - post_count = sum(1 for a in apis if a.get("method", "POST").upper() == "POST") - get_count = sum(1 for a in apis if a.get("method", "").upper() == "GET") - encrypted_count = sum(1 for a in apis if a.get("encryptionRequired")) - client_side_count = sum(1 for a in apis if a.get("executeAtClient")) - - lines = [ - "# API Reference Documentation", - "", - f"This directory contains **{total} API definitions** auto-synced from AEM Form Data Model (FDM).", - "", - f"*Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M')}*", - "", - "## Source of Truth", - "", - "```", - "AEM FDM ──[sync]──> Markdown files ──[generate]──> api-clients/*.js", - "```", - "", - "- **Primary Source**: AEM Form Data Model (`/conf/forms/settings/cloudconfigs/fdm`)", - "- **Local Format**: Markdown files in this directory", - "- **Generated Clients**: `code/blocks/form/api-clients/*.js` (typed async functions)", - "", - "## Quick Start", - "", - "```bash", - "# List all APIs", - "api-manager list", - "", - "# Search for specific API", - "api-manager list | grep -i otp", - "", - "# Show API details", - "api-manager show customerIdentification", - "", - "# Show as JSON", - "api-manager show customerIdentification --json", - "```", - "", - "## Management Commands", - "", - "| Command | Description |", - "|---------|-------------|", - "| `api-manager sync` | Fetch latest from AEM FDM |", - "| `api-manager build` | Regenerate registry.json |", - "| `api-manager test` | Check for API changes |", - "| `api-manager add` | Add new API interactively |", - "", - "## API Statistics", - "", - "| Metric | Count |", - "|--------|-------|", - f"| Total APIs | {total} |", - f"| POST methods | {post_count} |", - f"| GET methods | {get_count} |", - f"| Encrypted APIs | {encrypted_count} |", - f"| Client-side APIs | {client_side_count} |", - "", - "## Using APIs in Custom Functions", - "", - "**Using generated api-clients (recommended):**", - "```javascript", - "import { customerIdentification } from './api-clients';", - "", - "// Pass flat params - SDK wraps into requestString internally", - "const response = await customerIdentification({", - " mobileNumber: '9876543210',", - " dateOfBirth: '01/01/1990'", - "}, globals);", - "", - "if (response.ok && response.body?.status?.responseCode === '0') {", - " console.log(response.body); // API response", - "} else {", - " console.error('Error:', response.status, response.body);", - "}", - "```", - "", - "**Using globals.functions.request() directly:**", - "```javascript", - "// For cases where you need direct control", - "const response = await globals.functions.request({", - " url: '/api/customerIdentification',", - " method: 'POST',", - " body: { requestString: { mobileNumber: '9876543210' } }", - "});", - "```", - "", - "## Sync Workflow", - "", - "```bash", - "# Check for changes", - "api-manager sync --dry-run", - "", - "# Apply changes", - "api-manager sync", - "", - "# Rebuild registry and run tests", - "api-manager build", - "", - "# If tests fail and changes are intentional", - "api-manager test --update", - "```", - "", - "## Notes", - "", - "- APIs are synced from AEM FDM type `api-integration`", - "- This file is auto-generated by `api-manager sync`", - "- Do not edit manually - changes will be overwritten", - "", - ] - - return "\n".join(lines) diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/openapi_parser.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/openapi_parser.py deleted file mode 100644 index 7d1227f4..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/openapi_parser.py +++ /dev/null @@ -1,256 +0,0 @@ -"""OpenAPI Parser - Parses OpenAPI 3.0 YAML files to build registry.""" - -import json -from pathlib import Path -from typing import Any, Optional - -import yaml - -from .config import get_project_paths - - -def parse_openapi_file(filepath: Path) -> Optional[dict]: - """Parse an OpenAPI 3.0 YAML file. - - Args: - filepath: Path to YAML file - - Returns: - API configuration dict or None if parsing fails - """ - try: - content = filepath.read_text(encoding="utf-8") - doc = yaml.safe_load(content) - except Exception as e: - print(f" Warning: Failed to parse YAML {filepath.name}: {e}") - return None - - if not doc or not isinstance(doc, dict): - return None - - # Extract info - info = doc.get("info", {}) - api_config: dict[str, Any] = { - "name": info.get("title", filepath.stem), - "description": info.get("description", ""), - "params": {}, - "response": {}, - } - - # Extract AEM config - aem_config = doc.get("x-aem-config", {}) - if aem_config: - api_config["source"] = aem_config.get("source", "local") - api_config["executeAtClient"] = aem_config.get("executeAtClient", True) - api_config["encryptionRequired"] = aem_config.get("encryptionRequired", False) - api_config["authType"] = aem_config.get("authType", "None") - api_config["isOutputAnArray"] = aem_config.get("isOutputAnArray", False) - api_config["bodyStructure"] = aem_config.get("bodyStructure", "requestString") - if aem_config.get("fdmName"): - api_config["fdmName"] = aem_config["fdmName"] - - # Extract path and method - paths = doc.get("paths", {}) - for endpoint, methods in paths.items(): - api_config["endpoint"] = endpoint - - for method, operation in methods.items(): - if method in ["get", "post", "put", "delete", "patch"]: - api_config["method"] = method.upper() - - # Extract success condition - if operation.get("x-success-condition"): - api_config["successCondition"] = operation["x-success-condition"] - - # Extract path/query/header parameters from parameters section - parameters = operation.get("parameters", []) - for param in parameters: - param_name = param.get("name") - if param_name: - param_schema = param.get("schema", {}) - api_config["params"][param_name] = { - "type": param_schema.get("type", "string"), - "description": param.get("description", ""), - "in": param.get("in", "query"), - "required": param.get("required", False), - } - if "default" in param_schema: - api_config["params"][param_name]["default"] = param_schema["default"] - - # Extract request body params - request_body = operation.get("requestBody", {}) - content = request_body.get("content", {}) - json_content = content.get("application/json", {}) - schema = json_content.get("schema", {}) - - # Handle $ref to components - if "$ref" in schema: - ref_path = schema["$ref"] - schema = _resolve_ref(doc, ref_path) - - # Extract params from requestString - if schema: - _extract_params_from_schema(schema, api_config) - - # Extract response fields - responses = operation.get("responses", {}) - success_response = responses.get("200", {}) - resp_content = success_response.get("content", {}) - resp_json = resp_content.get("application/json", {}) - resp_schema = resp_json.get("schema", {}) - - if "$ref" in resp_schema: - ref_path = resp_schema["$ref"] - resp_schema = _resolve_ref(doc, ref_path) - - if resp_schema: - _extract_response_from_schema(resp_schema, api_config) - - break # Only process first method - break # Only process first path - - return api_config - - -def _resolve_ref(doc: dict, ref: str) -> dict: - """Resolve a $ref pointer in the document.""" - if not ref.startswith("#/"): - return {} - - parts = ref[2:].split("/") - result = doc - for part in parts: - if isinstance(result, dict) and part in result: - result = result[part] - else: - return {} - - return result if isinstance(result, dict) else {} - - -def _extract_params_from_schema(schema: dict, api_config: dict) -> None: - """Extract parameters from request body schema.""" - properties = schema.get("properties", {}) - - # Check for requestString wrapper - if "requestString" in properties: - request_string = properties["requestString"] - inner_props = request_string.get("properties", {}) - # OpenAPI spec: required is at schema level, not on each property - required_fields = set(request_string.get("required", [])) - for param_name, param_schema in inner_props.items(): - api_config["params"][param_name] = { - "type": param_schema.get("type", "string"), - "description": param_schema.get("description", ""), - "in": "body", - } - if "default" in param_schema: - api_config["params"][param_name]["default"] = param_schema["default"] - # Check required array at schema level (OpenAPI standard) - if param_name in required_fields: - api_config["params"][param_name]["required"] = True - else: - # Direct properties without wrapper - required_fields = set(schema.get("required", [])) - for param_name, param_schema in properties.items(): - api_config["params"][param_name] = { - "type": param_schema.get("type", "string"), - "description": param_schema.get("description", ""), - "in": "body", - } - if "default" in param_schema: - api_config["params"][param_name]["default"] = param_schema["default"] - if param_name in required_fields: - api_config["params"][param_name]["required"] = True - - -def _extract_response_from_schema( - schema: dict, api_config: dict, prefix: str = "" -) -> None: - """Extract response fields from schema.""" - properties = schema.get("properties", {}) - - for field_name, field_schema in properties.items(): - full_name = f"{prefix}{field_name}" if prefix else field_name - - if field_schema.get("type") == "object" and "properties" in field_schema: - # Nested object - recurse - _extract_response_from_schema( - field_schema, api_config, prefix=f"{full_name}." - ) - else: - api_config["response"][full_name] = { - "type": field_schema.get("type", "string"), - "description": field_schema.get("description", ""), - } - - -def build_registry() -> dict[str, dict]: - """Build registry from all YAML files in refs/apis/generated/spec/. - - Returns: - Registry dict mapping API names to configurations - """ - spec_dir, api_clients_dir, generated_dir = get_project_paths() - - if not spec_dir.exists(): - print(f"Warning: spec directory not found: {spec_dir}") - return {} - - registry: dict[str, dict] = {} - - # Find all YAML files (excluding template and index) - yaml_files = sorted(list(spec_dir.glob("*.yaml")) + list(spec_dir.glob("*.yml"))) - - for yaml_file in yaml_files: - # Skip template and hidden files - if yaml_file.name.startswith("_") or yaml_file.name.startswith("."): - continue - - try: - api_config = parse_openapi_file(yaml_file) - if api_config and api_config.get("name"): - # Use filename (without extension) as registry key - key = yaml_file.stem - registry[key] = api_config - except Exception as e: - print(f" Warning: Failed to parse {yaml_file.name}: {e}") - - return registry - - -def load_registry() -> dict[str, dict]: - """Load registry from JSON file. - - Returns: - Registry dict - """ - spec_dir, api_clients_dir, generated_dir = get_project_paths() - registry_path = generated_dir / "registry.json" - - if not registry_path.exists(): - return {} - - with open(registry_path, "r", encoding="utf-8") as f: - return json.load(f) - - -def save_registry(registry: dict[str, dict]) -> Path: - """Save registry to JSON file. - - Args: - registry: Registry dict - - Returns: - Path to saved file - """ - spec_dir, api_clients_dir, generated_dir = get_project_paths() - registry_path = generated_dir / "registry.json" - - # Ensure directory exists - generated_dir.mkdir(parents=True, exist_ok=True) - - with open(registry_path, "w", encoding="utf-8") as f: - json.dump(registry, f, indent=2) - - return registry_path diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/openapi_writer.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/openapi_writer.py deleted file mode 100644 index 76d3907d..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/openapi_writer.py +++ /dev/null @@ -1,421 +0,0 @@ -"""OpenAPI Writer - Generates OpenAPI 3.0 specs using apispec. - -Uses the apispec library for standards-compliant OpenAPI generation. -Includes validation to ensure generated specs are valid OpenAPI 3.0. -""" - -import re -from typing import Any - -from apispec import APISpec -from openapi_spec_validator import validate - - -def create_spec_for_api(api_config: dict) -> APISpec: - """Create an APISpec for a single API. - - Args: - api_config: API configuration from AEM FDM - - Returns: - APISpec instance - """ - name = api_config.get("name", "Unknown API") - description = api_config.get("description", f"{name} API") - - spec = APISpec( - title=name, - version="1.0.0", - openapi_version="3.0.3", - info={"description": description}, - ) - - return spec - - -def _to_operation_id(name: str) -> str: - """Convert API name to valid operationId (camelCase).""" - words = re.split(r"[^a-zA-Z0-9]+", name) - if not words: - return "unnamed" - - result = words[0].lower() - for word in words[1:]: - if word: - result += word[0].upper() + word[1:].lower() - - return result - - -def _separate_params_by_location(params: dict) -> dict: - """Separate parameters by their location (path, query, header, body). - - Args: - params: Raw params dict from API config - - Returns: - Dict with params grouped by location - """ - path_params = [] - query_params = [] - header_params = [] - body_params = {} - - for param_name, param_config in params.items(): - # Use flat name (strip requestString. prefix) - flat_name = param_name.split(".")[-1] if "." in param_name else param_name - location = param_config.get("in", "body") - - if location == "path": - path_params.append( - { - "name": flat_name, - "in": "path", - "required": True, # Path params are always required - "schema": {"type": param_config.get("type", "string")}, - "description": param_config.get("description", ""), - } - ) - elif location == "query": - query_params.append( - { - "name": flat_name, - "in": "query", - "required": param_config.get("required", False), - "schema": {"type": param_config.get("type", "string")}, - "description": param_config.get("description", ""), - } - ) - elif location == "header": - header_params.append( - { - "name": flat_name, - "in": "header", - "required": param_config.get("required", False), - "schema": {"type": param_config.get("type", "string")}, - "description": param_config.get("description", ""), - } - ) - else: - # Body param - body_params[flat_name] = { - "type": param_config.get("type", "string"), - "description": param_config.get("description", ""), - } - if param_config.get("default") is not None: - body_params[flat_name]["default"] = param_config["default"] - - return { - "path_params": path_params, - "query_params": query_params, - "header_params": header_params, - "body_params": body_params, - } - - -def _build_response_properties(response: dict) -> dict: - """Build response properties handling nested fields like 'status.responseCode'.""" - properties = {} - - for field_name, field_config in response.items(): - parts = field_name.split(".") - - if len(parts) == 1: - # Simple field - properties[field_name] = { - "type": field_config.get("type", "string"), - } - if field_config.get("description"): - properties[field_name]["description"] = field_config["description"] - else: - # Nested field - create object structure - root = parts[0] - if root not in properties: - properties[root] = {"type": "object", "properties": {}} - elif "properties" not in properties[root]: - properties[root] = {"type": "object", "properties": {}} - - leaf = parts[-1] - properties[root]["properties"][leaf] = { - "type": field_config.get("type", "string"), - } - if field_config.get("description"): - properties[root]["properties"][leaf]["description"] = field_config[ - "description" - ] - - return properties - - -def write_api_to_openapi(api_config: dict, validate_output: bool = True) -> str: - """Convert API config to OpenAPI 3.0 YAML string. - - Uses apispec for standards-compliant generation and optionally validates - the output against OpenAPI 3.0 spec. - - Args: - api_config: API configuration object - validate_output: Whether to validate the generated spec (default: True) - - Returns: - OpenAPI YAML content - - Raises: - OpenAPIValidationError: If validation fails - """ - name = api_config.get("name", "Unknown API") - description = api_config.get("description", f"{name} API") - endpoint = api_config.get("endpoint", "/api/endpoint") - method = api_config.get("method", "POST").lower() - params = api_config.get("params", {}) - response = api_config.get("response", {}) - body_structure = api_config.get("bodyStructure", "requestString") - success_condition = api_config.get("successCondition") - - # Create spec - spec = APISpec( - title=name, - version="1.0.0", - openapi_version="3.0.3", - info={"description": description}, - ) - - # Separate params by location - param_groups = _separate_params_by_location(params) - path_params = param_groups["path_params"] - query_params = param_groups["query_params"] - header_params = param_groups["header_params"] - body_params = param_groups["body_params"] - - # Build operation object - operation: dict[str, Any] = { - "operationId": _to_operation_id(name), - "summary": name, - "description": description, - "responses": { - "200": { - "description": "Successful response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Response"} - } - }, - } - }, - } - if success_condition: - operation["x-success-condition"] = success_condition - - # Add parameters (path + query + header) - all_params = path_params + query_params + header_params - if all_params: - operation["parameters"] = all_params - - # Add request body (only for methods that support it and if there are body params) - if body_params and method in ["post", "put", "patch"]: - operation["requestBody"] = { - "required": True, - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/RequestBody"} - } - }, - } - - # Add path to spec - spec.path(path=endpoint, operations={method: operation}) - - # Add Response schema - response_properties = _build_response_properties(response) - spec.components.schema( - "Response", - { - "type": "object", - "properties": response_properties, - }, - ) - - # Add RequestBody schema (only if there are body params) - if body_params: - if body_structure and body_structure != "none": - # Wrap in body structure (e.g., requestString) - spec.components.schema( - "RequestBody", - { - "type": "object", - "properties": { - body_structure: { - "type": "object", - "description": "SDK wraps flat params into this structure", - "properties": body_params, - } - }, - }, - ) - else: - # Direct properties without wrapper - spec.components.schema( - "RequestBody", - { - "type": "object", - "properties": body_params, - }, - ) - - # Get the spec dict and add AEM-specific extensions - spec_dict = spec.to_dict() - - # Add x-aem-config at root level (after info) - aem_config = { - "source": api_config.get("source", "local"), - "executeAtClient": api_config.get("executeAtClient", True), - "encryptionRequired": api_config.get("encryptionRequired", False), - "authType": api_config.get("authType", "None"), - "isOutputAnArray": api_config.get("isOutputAnArray", False), - "bodyStructure": body_structure, - } - if api_config.get("fdmName"): - aem_config["fdmName"] = api_config["fdmName"] - - spec_dict["x-aem-config"] = aem_config - - # Validate if requested - if validate_output: - try: - validate(spec_dict) - except Exception as e: - # Log warning but don't fail - some AEM APIs may have edge cases - import sys - - print( - f" Warning: OpenAPI validation issue for {name}: {e}", file=sys.stderr - ) - - # Convert to YAML with proper ordering - import yaml - - # Custom representer to maintain key order - def represent_dict(dumper, data): - return dumper.represent_mapping("tag:yaml.org,2002:map", data.items()) - - yaml.add_representer(dict, represent_dict) - - # Reorder keys for better readability - ordered_spec = _reorder_spec_keys(spec_dict) - - return yaml.dump( - ordered_spec, - default_flow_style=False, - sort_keys=False, - allow_unicode=True, - width=120, - ) - - -def _reorder_spec_keys(spec_dict: dict) -> dict: - """Reorder spec keys for better readability. - - Puts keys in a logical order: openapi, info, x-aem-config, paths, components - """ - key_order = [ - "openapi", - "info", - "x-aem-config", - "servers", - "tags", - "paths", - "components", - ] - - ordered = {} - for key in key_order: - if key in spec_dict: - ordered[key] = spec_dict[key] - - # Add any remaining keys - for key, value in spec_dict.items(): - if key not in ordered: - ordered[key] = value - - return ordered - - -def generate_filename(api_name: str) -> str: - """Generate filename from API name. - - Args: - api_name: API name - - Returns: - Filename (without path) - """ - filename = re.sub(r"[^a-z0-9]+", "-", api_name.lower()) - filename = filename.strip("-") - return f"{filename}.yaml" - - -def generate_index(apis: list[dict], sync_stats: dict = None) -> str: - """Generate _index.yaml content with API statistics. - - Args: - apis: List of API configurations - sync_stats: Optional sync statistics dict - - Returns: - YAML content for _index.yaml - """ - from datetime import datetime - - import yaml - - total = len(apis) - post_count = sum(1 for a in apis if a.get("method", "POST").upper() == "POST") - get_count = sum(1 for a in apis if a.get("method", "").upper() == "GET") - encrypted_count = sum(1 for a in apis if a.get("encryptionRequired")) - client_side_count = sum(1 for a in apis if a.get("executeAtClient")) - - index_doc = { - "title": "API Reference Documentation", - "description": f"This directory contains {total} API definitions in OpenAPI 3.0 format", - "lastUpdated": datetime.now().strftime("%Y-%m-%d %H:%M"), - "sourceOfTruth": { - "primary": "AEM Form Data Model", - "local": "OpenAPI YAML files in this directory", - "generated": "code/blocks/form/api-clients/*.js", - }, - "commands": { - "list": "api-manager list", - "show": "api-manager show <apiName>", - "sync": "api-manager sync", - "build": "api-manager build", - }, - "statistics": { - "totalApis": total, - "postMethods": post_count, - "getMethods": get_count, - "encryptedApis": encrypted_count, - "clientSideApis": client_side_count, - }, - "usage": { - "example": """ -import { customerIdentification } from './api-clients'; - -var response = await customerIdentification({ - mobileNumber: '9876543210', - dateOfBirth: '01/01/1990' -}, globals); - -if (response.ok && response.body?.status?.responseCode === '0') { - // Success -} -""".strip(), - }, - } - - return yaml.dump( - index_doc, - default_flow_style=False, - sort_keys=False, - allow_unicode=True, - width=120, - ) diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/parser.py b/skills/aem/forms/forms-orchestrator/scripts/api_manager/parser.py deleted file mode 100644 index 22ca1b24..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/parser.py +++ /dev/null @@ -1,276 +0,0 @@ -"""Parser - Parses markdown API docs to build registry.""" - -import json -import re -from pathlib import Path -from typing import Any, Optional - -from .config import get_project_paths -from .exceptions import ParseError - - -def parse_markdown_file(filepath: Path) -> Optional[dict]: - """Parse a markdown API documentation file. - - Args: - filepath: Path to markdown file - - Returns: - API configuration dict or None if parsing fails - """ - content = filepath.read_text(encoding="utf-8") - lines = content.split("\n") - - api_config: dict[str, Any] = { - "params": {}, - "response": {}, - } - - current_section = None - table_headers: list[str] = [] - - for line in lines: - line = line.strip() - - # Parse title (# name) - if line.startswith("# "): - api_config["name"] = line[2:].strip() - continue - - # Parse section headers (## section) - if line.startswith("## "): - current_section = line[3:].strip().lower() - table_headers = [] - continue - - # Skip empty lines and horizontal rules - if not line or line.startswith("---"): - continue - - # Parse table rows - if line.startswith("|"): - cells = [c.strip() for c in line.split("|")[1:-1]] - - # Check if this is a header row - if all(set(c) <= set("-:") for c in cells): - continue # Skip separator row - - # Check if this might be a header row (first row of table) - if not table_headers: - table_headers = [c.lower() for c in cells] - continue - - # Parse data row based on section - if current_section == "endpoint": - _parse_endpoint_row(cells, api_config) - elif current_section == "execution info": - _parse_execution_info_row(cells, api_config) - elif current_section == "request parameters": - _parse_param_row(cells, table_headers, api_config) - elif current_section == "response fields": - _parse_response_row(cells, table_headers, api_config) - - # Parse success condition (code block or inline code) - if current_section == "success condition": - match = re.search(r"`([^`]+)`", line) - if match: - api_config["successCondition"] = match.group(1) - - # Parse notes (bullet points) - if current_section == "notes" and line.startswith("-"): - if "notes" not in api_config: - api_config["notes"] = [] - api_config["notes"].append(line[1:].strip()) - - # Validate required fields - if not api_config.get("name"): - return None - - return api_config - - -def _parse_endpoint_row(cells: list[str], api_config: dict) -> None: - """Parse endpoint table row.""" - if len(cells) < 2: - return - - prop = cells[0].lower() - value = _extract_code(cells[1]) - - if prop == "url": - api_config["endpoint"] = value - elif prop == "method": - api_config["method"] = value - elif prop == "content-type": - api_config["contentType"] = value - elif prop == "body structure": - api_config["bodyStructure"] = value - - -def _parse_execution_info_row(cells: list[str], api_config: dict) -> None: - """Parse execution info table row.""" - if len(cells) < 2: - return - - prop = cells[0].lower() - value = cells[1].strip() - - if prop == "source": - api_config["source"] = value - elif prop == "execute at client": - api_config["executeAtClient"] = value.lower() == "yes" - elif prop == "encryption required": - api_config["encryptionRequired"] = value.lower() == "yes" - elif prop == "authentication": - api_config["authType"] = value - elif prop == "response is array": - api_config["isOutputAnArray"] = value.lower() == "yes" - - -def _parse_param_row(cells: list[str], headers: list[str], api_config: dict) -> None: - """Parse parameter table row.""" - if len(cells) < 2: - return - - # Create mapping from header index to cell value - row_data = {} - for i, header in enumerate(headers): - if i < len(cells): - row_data[header] = cells[i] - - # Extract parameter name - param_name = _extract_code(row_data.get("parameter", "")) - if not param_name or param_name.lower() == "field": - return - - param_config: dict[str, Any] = {} - - # Type - if "type" in row_data: - param_config["type"] = row_data["type"].strip() - - # Required - if "required" in row_data: - param_config["required"] = row_data["required"].strip().lower() == "yes" - - # Default - if "default" in row_data: - default_val = row_data["default"].strip() - if default_val and default_val != "-": - param_config["default"] = default_val - - # Location (in) - if "location" in row_data: - param_config["in"] = row_data["location"].strip() - - # Description - if "description" in row_data: - param_config["description"] = row_data["description"].strip() - - api_config["params"][param_name] = param_config - - -def _parse_response_row(cells: list[str], headers: list[str], api_config: dict) -> None: - """Parse response field table row.""" - if len(cells) < 2: - return - - # Create mapping from header index to cell value - row_data = {} - for i, header in enumerate(headers): - if i < len(cells): - row_data[header] = cells[i] - - # Extract field name - field_name = _extract_code(row_data.get("field", "")) - if not field_name or field_name.lower() == "field": - return - - field_config: dict[str, Any] = {} - - # Type - if "type" in row_data: - field_config["type"] = row_data["type"].strip() - - # Description - if "description" in row_data: - field_config["description"] = row_data["description"].strip() - - api_config["response"][field_name] = field_config - - -def _extract_code(text: str) -> str: - """Extract text from inline code blocks.""" - match = re.search(r"`([^`]+)`", text) - return match.group(1) if match else text.strip() - - -def build_registry() -> dict[str, dict]: - """Build registry from all markdown files in refs/apis/. - - Returns: - Registry dict mapping API names to configurations - """ - refs_dir, api_stubs_dir = get_project_paths() - - if not refs_dir.exists(): - print(f"Warning: refs/apis directory not found: {refs_dir}") - return {} - - registry: dict[str, dict] = {} - - # Find all markdown files (excluding template) - md_files = sorted(refs_dir.glob("*.md")) - - for md_file in md_files: - # Skip template and hidden files - if md_file.name.startswith("_") or md_file.name.startswith("."): - continue - - try: - api_config = parse_markdown_file(md_file) - if api_config and api_config.get("name"): - # Use filename (without .md) as registry key - key = md_file.stem - registry[key] = api_config - except Exception as e: - print(f" Warning: Failed to parse {md_file.name}: {e}") - - return registry - - -def save_registry(registry: dict[str, dict]) -> Path: - """Save registry to JSON file. - - Args: - registry: Registry dict - - Returns: - Path to saved file - """ - refs_dir, api_stubs_dir = get_project_paths() - registry_path = api_stubs_dir / "registry.json" - - # Ensure directory exists - api_stubs_dir.mkdir(parents=True, exist_ok=True) - - with open(registry_path, "w", encoding="utf-8") as f: - json.dump(registry, f, indent=2) - - return registry_path - - -def load_registry() -> dict[str, dict]: - """Load registry from JSON file. - - Returns: - Registry dict - """ - refs_dir, api_stubs_dir = get_project_paths() - registry_path = api_stubs_dir / "registry.json" - - if not registry_path.exists(): - return {} - - with open(registry_path, "r", encoding="utf-8") as f: - return json.load(f) diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/templates/api-client.js.j2 b/skills/aem/forms/forms-orchestrator/scripts/api_manager/templates/api-client.js.j2 deleted file mode 100644 index 03698af3..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/templates/api-client.js.j2 +++ /dev/null @@ -1,96 +0,0 @@ -// api-clients/{{ api_key }}.js -// Auto-generated by api-manager - DO NOT EDIT -// Source: refs/apis/{{ api_key }}.yaml -// -// NOTE: This is an async helper function for use in custom functions. -// It will NOT appear in the visual rule editor (async functions are filtered). -// Use: var response = await {{ function_name }}(params, globals); - -/** - * {{ name }} - * - * {{ description }} - * - * @param {object} params - Request parameters -{% for p in params %} - * @param {{ '{' }}{{ p.type }}{{ '}' }} {% if not p.required %}[{% endif %}params.{{ p.name }}{% if not p.required %}]{% endif %} - {{ p.description }}{% if p.location != 'body' %} ({{ p.location }}){% endif %}{% if p.required %} (required){% endif %} - -{% endfor %} - * @param {scope} globals - Globals object - * @returns {Promise<{ok: boolean, status: number, body: object}>} - * - * @example - * async function myCustomFunction(globals) { - * var response = await {{ function_name }}({ -{% for p in example_params %} - * {{ p.name | js_key }}: 'value'{% if not loop.last %},{% endif %} - -{% endfor %} - * }, globals); - * if (response.ok) { - * // handle success - * } - * } -{% if success_condition %} * - * Success condition: {{ success_condition }} -{% endif %} */ -export async function {{ function_name }}(params, globals) { - // Defensive check for params - params = params || {}; - -{% for p in required_params %} - if (params{{ p.name | js_access }} === undefined || params{{ p.name | js_access }} === null) { - throw new Error('{{ function_name }}: {{ p.name }} is required'); - } -{% endfor %} - var url = '{{ endpoint }}'; -{% for p in path_params %} - url = url.replace('{' + '{{ p.name }}' + '}', encodeURIComponent(params{{ p.name | js_access }} || '')); -{% endfor %} -{% if query_params %} - - // Build query string - var queryParams = { -{% for p in query_params %} - {{ p.name | js_key }}: params{{ p.name | js_access }}{% if p.default is not none %} ?? {{ p.default | tojson }}{% endif %}, -{% endfor %} - }; - var queryString = Object.entries(queryParams) - .filter(function(entry) { return entry[1] !== undefined && entry[1] !== null; }) - .map(function(entry) { return encodeURIComponent(entry[0]) + '=' + encodeURIComponent(entry[1]); }) - .join('&'); - if (queryString) { - url += (url.includes('?') ? '&' : '?') + queryString; - } -{% endif %} -{% if body_params and method in ['POST', 'PUT', 'PATCH'] %} - - var body = { -{% if body_structure and body_structure != 'none' %} - {{ body_structure }}: { -{% for p in body_params %} - {{ p.name | js_key }}: params{{ p.name | js_access }}{% if p.default is not none %} ?? {{ p.default | tojson }}{% endif %}, -{% endfor %} - } -{% else %} -{% for p in body_params %} - {{ p.name | js_key }}: params{{ p.name | js_access }}{% if p.default is not none %} ?? {{ p.default | tojson }}{% endif %}, -{% endfor %} -{% endif %} - }; -{% endif %} - - return globals.functions.request({ - url: url, - method: '{{ method }}', - headers: { - 'Content-Type': 'application/json', -{% for p in header_params %} - '{{ p.name }}': params{{ p.name | js_access }}{% if p.default is not none %} ?? {{ p.default | tojson }}{% endif %}, -{% endfor %} - }, -{% if body_params and method in ['POST', 'PUT', 'PATCH'] %} - body: body, -{% endif %} - }); -} diff --git a/skills/aem/forms/forms-orchestrator/scripts/api_manager/templates/index.js.j2 b/skills/aem/forms/forms-orchestrator/scripts/api_manager/templates/index.js.j2 deleted file mode 100644 index dab45959..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/api_manager/templates/index.js.j2 +++ /dev/null @@ -1,11 +0,0 @@ -// api-clients/index.js -// Auto-generated by api-manager - DO NOT EDIT -// -// Usage: -// import { apiName } from './api-clients'; -// var response = await apiName(params, globals); -// - -{% for api in apis %} -export { {{ api.function_name }} } from './{{ api.key }}.js'; -{% endfor %} diff --git a/skills/aem/forms/forms-orchestrator/scripts/eds-code-sync b/skills/aem/forms/forms-orchestrator/scripts/eds-code-sync deleted file mode 100755 index 31685a04..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/eds-code-sync +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m eds_code_sync.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/form-sync b/skills/aem/forms/forms-orchestrator/scripts/form-sync deleted file mode 100755 index 8ca76281..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/form-sync +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m form_sync.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/git-sandbox b/skills/aem/forms/forms-orchestrator/scripts/git-sandbox deleted file mode 100755 index 206eff58..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/git-sandbox +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m git_sandbox.cli "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/parse-functions b/skills/aem/forms/forms-orchestrator/scripts/parse-functions deleted file mode 100755 index e8258cd7..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/parse-functions +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec node "$PLUGIN_ROOT/scripts/rule_coder/bridge/cli/parse-functions.js" "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/python3 b/skills/aem/forms/forms-orchestrator/scripts/python3 deleted file mode 100755 index a9530a1b..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/python3 +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bash -# ───────────────────────────────────────────────────────────────────────────── -# AEM Forms Skills — Python wrapper with lazy venv bootstrap -# -# Thin wrapper that ensures the plugin's virtual environment exists before -# running any Python command. On first invocation it silently runs setup.sh -# to create .venv and install all dependencies. Subsequent calls go straight -# through with no overhead. -# -# Also sets PYTHONPATH for all Python package directories so every script -# and module is importable without callers needing to manage paths. -# -# PLUGIN_ROOT = forms-orchestrator/ (parent of scripts/) -# PROJECT_ROOT = forms/ (parent of forms-orchestrator/) -# where .venv lives (outside the plugin package) -# ───────────────────────────────────────────────────────────────────────────── -set -e - -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -PROJECT_ROOT="$(cd "$PLUGIN_ROOT/.." && pwd)" -VENV_PYTHON="$PROJECT_ROOT/.venv/bin/python3" - -# Bootstrap the venv if it doesn't exist yet -if [ ! -x "$VENV_PYTHON" ]; then - echo "⏳ First run — setting up AEM Forms Skills environment…" >&2 - "$PLUGIN_ROOT/scripts/setup.sh" >&2 - echo "" >&2 - - # Verify setup succeeded - if [ ! -x "$VENV_PYTHON" ]; then - echo "❌ Setup failed — .venv/bin/python3 not found after running setup.sh" >&2 - exit 1 - fi -fi - -# ── Set PYTHONPATH for all plugin Python packages ──────────────────────────── -# Shared scripts (rule_coder, api_manager) -# Skill-embedded scripts (form_sync, eds_code_sync, git_sandbox, cct, eds_form_validator, scaffold_form, api_skill) -DR="$PLUGIN_ROOT/references/domain-registry/references" -PLUGIN_PYTHONPATH="$PLUGIN_ROOT/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/infra/references/sync-forms/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/infra/references/sync-eds-code/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/infra/references/git-sandbox/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/build/references/create-component/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/build/references/create-form/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/build/references/scaffold-form/scripts" -PLUGIN_PYTHONPATH="$PLUGIN_PYTHONPATH:$DR/integration/references/manage-apis/scripts" -export PYTHONPATH="$PLUGIN_PYTHONPATH${PYTHONPATH:+:$PYTHONPATH}" - -exec "$VENV_PYTHON" "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule-grammar b/skills/aem/forms/forms-orchestrator/scripts/rule-grammar deleted file mode 100755 index 68ac00aa..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule-grammar +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -exec cat "$PLUGIN_ROOT/scripts/rule_coder/grammar/annotated_subset_grammar.json" diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule-save b/skills/aem/forms/forms-orchestrator/scripts/rule-save deleted file mode 100755 index 831becb5..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule-save +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec node "$PLUGIN_ROOT/scripts/rule_coder/bridge/cli/save-rule.js" "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule-transform b/skills/aem/forms/forms-orchestrator/scripts/rule-transform deleted file mode 100755 index 54970324..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule-transform +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec node "$PLUGIN_ROOT/scripts/rule_coder/bridge/cli/transform-form.js" "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule-validate b/skills/aem/forms/forms-orchestrator/scripts/rule-validate deleted file mode 100755 index f8e5338d..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule-validate +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -set -e -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -source "$PLUGIN_ROOT/scripts/_resolve-workspace" -cd "$FORMS_WORKSPACE" -exec "$PLUGIN_ROOT/scripts/python3" -m rule_coder.validator "$@" diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/__init__.py deleted file mode 100644 index b55537a1..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -""" -Rule Coder - AEM Forms Business Logic Tools - -This package provides tools for generating, validating, and transforming -AEM Forms rules and custom functions. - -Modules: - context: Form context and component lookup - validator: Rule JSON validation against grammar - functions: OOTB and custom function management - debug: Rule diff and diagnostic tools - bridge: Node.js CLI tools for rule transformation - -Usage: - from rule_coder.context import FormContext, ComponentLookup - from rule_coder.validator import validate_rule, RuleValidator - from rule_coder.functions import load_ootb_functions, parse_custom_functions - from rule_coder.debug import diff_rules, diagnose_rule -""" - -__version__ = '1.0.0' - -# Exports are available when imported as a package -# Individual submodules can still be imported directly: -# from context import FormContext -# from validator import validate_rule - -__all__ = [ - 'context', - 'validator', - 'functions', - 'debug', -] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/generate-formula.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/generate-formula.js deleted file mode 100644 index 9568ec65..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/generate-formula.js +++ /dev/null @@ -1,251 +0,0 @@ -#!/usr/bin/env node -/** - * Generate JSON Formula from rule JSON using AFJSONFormulaTransformer - * - * This CLI transforms a rule JSON into executable JSON Formula format - * using Adobe's actual AFJSONFormulaTransformer with visitor pattern. - * This ensures identical output to the rule editor. - * - * Usage: - * node generate-formula.js <rule.json> - * node generate-formula.js <rule.json> --context <context.json> - * node generate-formula.js --stdin - * - * Options: - * --context <file> Load FormContext for component validation - * - * Output: - * { - * "success": true, - * "field": "$form.firstName", - * "event": "Value Commit", - * "formula": "if(...)", - * "fdProperty": "change", - * "validationEnabled": true - * } - */ - -'use strict'; - -const fs = require('fs'); -const path = require('path'); - -// Load globals and transformers -require('../setup/globals'); -require('../setup/loader').loadForRuleTransform(); - -// Load ContextLoader directly (not via vm) -const ContextLoader = require('../setup/ContextLoader'); - -// Event name to fd:events property mapping -const EVENT_TO_FD_PROPERTY = { - "Value Commit": "change", - "Click": "click", - "Initialize": "initialize", - "Calculate": "calc", - "Visibility": "visible", - "Enabled": "enabled", - "Validate": "validate" -}; - -// Trigger event value to event name mapping -const TRIGGER_EVENT_TO_NAME = { - "is clicked": "Click", - "is changed": "Value Commit", - "is initialised": "Initialize", - "is initialized": "Initialize" -}; - -/** - * Extract trigger field and event from rule JSON - */ -function extractTriggerInfo(ruleJson) { - if (!ruleJson || ruleJson.nodeName !== 'ROOT') { - throw new Error('Invalid rule: must have ROOT node'); - } - - if (!ruleJson.items || ruleJson.items.length === 0) { - throw new Error('Invalid rule: ROOT must have items'); - } - - const statement = ruleJson.items[0]; - if (!statement.choice || statement.choice.nodeName !== 'TRIGGER_SCRIPTS') { - throw new Error('Only TRIGGER_SCRIPTS rules are supported'); - } - - const singleTriggerScripts = statement.choice.items[0]; - if (!singleTriggerScripts || !singleTriggerScripts.items) { - throw new Error('Invalid TRIGGER_SCRIPTS structure'); - } - - const items = singleTriggerScripts.items; - const triggerComponent = items[0]; - const triggerEvent = items[1]; - - // Get field ID - const fieldValue = triggerComponent?.value; - const fieldId = fieldValue?.id || fieldValue?.name || '$field'; - - // Get event name - const eventValue = triggerEvent?.value || 'is changed'; - const eventName = TRIGGER_EVENT_TO_NAME[eventValue] || eventValue; - - return { fieldId, eventName, eventValue }; -} - -/** - * Generate JSON Formula from rule JSON using AFJSONFormulaTransformer - * - * @param {Object} ruleJson - Rule JSON to transform - * @param {Object} contextData - Optional FormContext data (treeJson + functions) - */ -function generateFormula(ruleJson, contextData) { - // Extract trigger info first - const { fieldId, eventName, eventValue } = extractTriggerInfo(ruleJson); - - // Create SimpleContext for model creation - let ctx; - let validationEnabled = false; - - if (contextData && contextData.treeJson) { - // Use validated context with real component data - ctx = ContextLoader.createValidatedContext(contextData.treeJson, contextData.functions); - validationEnabled = true; - } else { - // Use synthetic context (default) - ctx = new expeditor.SimpleContext(); - } - - // Create model hierarchy from rule JSON - let model; - try { - model = expeditor.Utils.ModelFactory.fromJson(ruleJson, ctx); - } catch (e) { - throw new Error(`Failed to create model from JSON: ${e.message}`); - } - - // Create AFJSONFormulaTransformer - if (!guidelib.author.AFJSONFormulaTransformer) { - throw new Error('AFJSONFormulaTransformer not loaded'); - } - - const transformer = new guidelib.author.AFJSONFormulaTransformer(); - - // Set event context - this is required for the transformer to work correctly - transformer.setEvent({ - field: fieldId, - name: eventName, - model: null, - otherEvents: null - }); - - // Transform via visitor pattern - try { - model.accept(transformer); - } catch (e) { - throw new Error(`Transform failed: ${e.message}`); - } - - // Get result - const result = transformer.getScript(); - - // Determine fd:events property name - const fdProperty = EVENT_TO_FD_PROPERTY[eventName] || 'change'; - - // Format formula - result.content can be string or array - let formula; - if (Array.isArray(result.content)) { - formula = result.content.length === 1 ? result.content[0] : result.content; - } else { - formula = result.content; - } - - return { - success: true, - field: fieldId, - event: eventName, - eventProperty: `fd:events.${fdProperty}`, - fdProperty: fdProperty, - formula: formula, - validationEnabled: validationEnabled, - // Include raw result for debugging - _raw: { - field: result.field, - event: result.event, - model: result.model, - content: result.content - } - }; -} - -/** - * Parse command line arguments - */ -function parseArgs(args) { - const result = { - ruleFile: null, - contextFile: null, - useStdin: false - }; - - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - - if (arg === '--stdin') { - result.useStdin = true; - } else if (arg === '--context' && args[i + 1]) { - result.contextFile = args[++i]; - } else if (!arg.startsWith('--') && !result.ruleFile) { - result.ruleFile = arg; - } - } - - return result; -} - -/** - * Main CLI entry point - */ -function main() { - const args = process.argv.slice(2); - const parsedArgs = parseArgs(args); - - let ruleJson; - let contextData = null; - - try { - // Load rule JSON - if (parsedArgs.useStdin) { - const input = fs.readFileSync(0, 'utf-8'); - ruleJson = JSON.parse(input); - } else if (parsedArgs.ruleFile) { - if (!fs.existsSync(parsedArgs.ruleFile)) { - throw new Error(`File not found: ${parsedArgs.ruleFile}`); - } - const content = fs.readFileSync(parsedArgs.ruleFile, 'utf-8'); - ruleJson = JSON.parse(content); - } else { - console.error('Usage: node generate-formula.js <rule.json> [--context <context.json>]'); - console.error(' node generate-formula.js --stdin [--context <context.json>]'); - process.exit(1); - } - - // Load context if provided - if (parsedArgs.contextFile) { - contextData = ContextLoader.loadFromFile(parsedArgs.contextFile); - } - - const result = generateFormula(ruleJson, contextData); - console.log(JSON.stringify(result, null, 2)); - - } catch (error) { - console.log(JSON.stringify({ - success: false, - error: error.message, - stack: process.env.DEBUG === 'true' ? error.stack : undefined - }, null, 2)); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/jcr-to-crispr.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/jcr-to-crispr.py deleted file mode 100644 index 660ac5e0..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/jcr-to-crispr.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python3 -""" -Convert JCR form JSON to CRISPR (CoreComponent) format. - -Usage: - python jcr-to-crispr.py <form.json> - python jcr-to-crispr.py --stdin - -Output: - JSON object with the converted CRISPR form structure to stdout -""" - -import json -import sys -from pathlib import Path - -# Add vendored packages to Python path -_vendor_dir = str(Path(__file__).resolve().parent.parent / "vendor") -if _vendor_dir not in sys.path: - sys.path.insert(0, _vendor_dir) - -from formsgenailib.core.form import ( - InfinityJsonForm, - jcr_to_core_component, -) - - -def convert_jcr_to_crispr(jcr_json: dict) -> dict: - """ - Convert JCR form JSON to CRISPR (CoreComponent) format. - - Args: - jcr_json: JCR form JSON (Infinity format) - - Returns: - CRISPR form JSON (CoreComponent format) - """ - # Use InfinityJsonForm to parse the JCR JSON - infinity_form = InfinityJsonForm(jcr_json) - - # Convert to CoreComponent format - core_form = jcr_to_core_component(infinity_form) - - # Export as JSON dict - return core_form.model_dump(by_alias=True, exclude_none=True) - - -def main(): - args = sys.argv[1:] - - if len(args) == 0: - print( - json.dumps( - { - "success": False, - "error": "Usage: python jcr-to-crispr.py <form.json> or --stdin", - } - ), - file=sys.stderr, - ) - sys.exit(1) - - jcr_json = None - - if args[0] == "--stdin": - # Read from stdin - try: - stdin_content = sys.stdin.read() - jcr_json = json.loads(stdin_content) - except json.JSONDecodeError as e: - print( - json.dumps({"success": False, "error": f"Invalid JSON input: {e}"}), - file=sys.stderr, - ) - sys.exit(1) - else: - # Read from file - file_path = Path(args[0]).resolve() - if not file_path.exists(): - print( - json.dumps({"success": False, "error": f"File not found: {file_path}"}), - file=sys.stderr, - ) - sys.exit(1) - - try: - jcr_json = json.loads(file_path.read_text()) - except json.JSONDecodeError as e: - print( - json.dumps({"success": False, "error": f"Error parsing file: {e}"}), - file=sys.stderr, - ) - sys.exit(1) - - # Check if this is actually JCR format - if "jcr:primaryType" not in jcr_json and "sling:resourceType" not in jcr_json: - # Already in CRISPR format or unknown format, pass through - print( - json.dumps( - { - "success": True, - "crispr": jcr_json, - "converted": False, - "note": "Input does not appear to be JCR format, passing through unchanged", - } - ) - ) - return - - try: - crispr_json = convert_jcr_to_crispr(jcr_json) - print(json.dumps({"success": True, "crispr": crispr_json, "converted": True})) - except Exception as e: - print( - json.dumps({"success": False, "error": f"Conversion error: {e}"}), - file=sys.stderr, - ) - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/merge.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/merge.js deleted file mode 100644 index 4d9e5faa..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/merge.js +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env node -/** - * Merge rules by field and event - * - * This CLI merges multiple rules, grouping them by field and event type. - * Rules for the same field/event are combined appropriately. - * - * Usage: - * node merge.js <rules.json> - * node merge.js --stdin - * - * Input format (array of transformed rules): - * [ - * { "field": "$form.field1", "event": "Click", "actions": [...] }, - * { "field": "$form.field1", "event": "Click", "actions": [...] }, - * { "field": "$form.field2", "event": "Value Commit", "actions": [...] } - * ] - * - * Output: - * { - * "success": true, - * "merged": { - * "$form.field1": { - * "Click": { "rules": [...], "count": 2 } - * }, - * "$form.field2": { - * "Value Commit": { "rules": [...], "count": 1 } - * } - * }, - * "summary": { - * "totalRules": 3, - * "totalFields": 2, - * "totalEvents": 2 - * } - * } - */ - -'use strict'; - -const fs = require('fs'); -const path = require('path'); - -// Load globals -require('../setup/globals'); - -// Events that can have multiple rules merged -const MERGEABLE_EVENTS = [ - "Value Commit", - "Click", - "Initialize" -]; - -// Event property mapping for fd:* properties -const EVENT_PROPERTY_MAPPING = { - "Calculate": "fd:calc", - "Visibility": "fd:visible", - "Initialize": "fd:init", - "Click": "fd:click", - "Value Commit": "fd:valueCommit", - "Enabled": "fd:enabled", - "Validate": "fd:validate" -}; - -/** - * Check if an event can have multiple rules - */ -function isEventMergeable(eventName) { - return MERGEABLE_EVENTS.includes(eventName) || - (eventName && eventName.startsWith('custom:')); -} - -/** - * Merge an array of rules by field and event - */ -function mergeRules(rules) { - if (!Array.isArray(rules)) { - throw new Error('Input must be an array of rules'); - } - - const merged = {}; - let totalRules = 0; - const fieldsSet = new Set(); - const eventsSet = new Set(); - - rules.forEach((rule, index) => { - if (!rule.field) { - console.error(`Warning: Rule at index ${index} has no field`); - return; - } - - const field = rule.field; - const event = rule.event || "Value Commit"; - - fieldsSet.add(field); - eventsSet.add(event); - - // Initialize field entry - if (!merged[field]) { - merged[field] = {}; - } - - // Initialize event entry - if (!merged[field][event]) { - merged[field][event] = { - rules: [], - count: 0, - eventProperty: EVENT_PROPERTY_MAPPING[event] || event, - isMergeable: isEventMergeable(event) - }; - } - - // Add rule - merged[field][event].rules.push({ - index: totalRules, - actions: rule.actions || [], - elseActions: rule.elseActions || [], - hasCondition: rule.hasCondition || false, - hasElse: rule.hasElse || false, - isValid: rule.isValid !== false, - enabled: rule.enabled !== false, - description: rule.description || "" - }); - merged[field][event].count++; - totalRules++; - }); - - return { - success: true, - merged: merged, - summary: { - totalRules: totalRules, - totalFields: fieldsSet.size, - totalEvents: eventsSet.size, - fields: Array.from(fieldsSet), - events: Array.from(eventsSet) - } - }; -} - -/** - * Merge rules from raw rule JSON array - * This transforms each rule first, then merges - */ -function mergeRawRules(rawRules) { - if (!Array.isArray(rawRules)) { - throw new Error('Input must be an array of rule JSONs'); - } - - // Import transform function - const transformedRules = rawRules.map((ruleJson, index) => { - try { - return transformRuleForMerge(ruleJson); - } catch (e) { - console.error(`Warning: Could not transform rule at index ${index}: ${e.message}`); - return null; - } - }).filter(r => r !== null); - - return mergeRules(transformedRules); -} - -/** - * Simple transform for merge (extracts field/event info) - */ -function transformRuleForMerge(ruleJson) { - if (!ruleJson || ruleJson.nodeName !== 'ROOT') { - throw new Error('Invalid rule: must have ROOT node'); - } - - const statement = ruleJson.items?.[0]; - if (!statement?.choice || statement.choice.nodeName !== 'TRIGGER_SCRIPTS') { - throw new Error('Only TRIGGER_SCRIPTS rules supported'); - } - - const singleTriggerScripts = statement.choice.items?.[0]; - if (!singleTriggerScripts?.items || singleTriggerScripts.items.length < 4) { - throw new Error('Invalid TRIGGER_SCRIPTS structure'); - } - - const componentNode = singleTriggerScripts.items[0]; - const triggerEventNode = singleTriggerScripts.items[1]; - const triggerEventScripts = singleTriggerScripts.items[3]; - - // Extract field ID - const field = componentNode?.value?.id || null; - - // Extract event name - const eventValue = triggerEventNode?.value || "is changed"; - const eventMap = { - "is clicked": "Click", - "is changed": "Value Commit", - "is initialized": "Initialize", - "is initialised": "Initialize" - }; - const event = eventMap[eventValue] || (eventValue.startsWith('custom:') ? eventValue : `custom:${eventValue}`); - - // Extract actions - const items = triggerEventScripts?.items || []; - const conditionNode = items.find(item => item.nodeName === 'CONDITION'); - const hasCondition = conditionNode?.choice !== null && conditionNode?.choice !== undefined; - - const thenIndex = items.findIndex(item => item.nodeName === 'Then'); - const actions = []; - if (thenIndex !== -1 && items[thenIndex + 1]?.items) { - items[thenIndex + 1].items.forEach(item => { - if (item.nodeName === 'BLOCK_STATEMENT' && item.choice) { - actions.push(item.choice.nodeName); - } - }); - } - - const elseIndex = items.findIndex(item => item.nodeName === 'Else'); - const elseActions = []; - const hasElse = elseIndex !== -1; - if (hasElse && items[elseIndex + 1]?.items) { - items[elseIndex + 1].items.forEach(item => { - if (item.nodeName === 'BLOCK_STATEMENT' && item.choice) { - elseActions.push(item.choice.nodeName); - } - }); - } - - return { - field, - event, - actions, - elseActions, - hasCondition, - hasElse, - isValid: ruleJson.isValid !== false, - enabled: ruleJson.enabled !== false, - description: ruleJson.description || "" - }; -} - -/** - * Main CLI entry point - */ -function main() { - const args = process.argv.slice(2); - let input; - - try { - if (args.includes('--stdin')) { - input = JSON.parse(fs.readFileSync(0, 'utf-8')); - } else if (args.length > 0 && !args[0].startsWith('--')) { - const filePath = args[0]; - if (!fs.existsSync(filePath)) { - throw new Error(`File not found: ${filePath}`); - } - input = JSON.parse(fs.readFileSync(filePath, 'utf-8')); - } else { - console.error('Usage: node merge.js <rules.json> or node merge.js --stdin'); - process.exit(1); - } - - // Check if input is raw rules or transformed rules - let result; - if (Array.isArray(input) && input.length > 0) { - if (input[0].nodeName === 'ROOT') { - // Raw rule JSONs - need to transform first - result = mergeRawRules(input); - } else if (input[0].field) { - // Already transformed rules - result = mergeRules(input); - } else { - throw new Error('Invalid input format: expected array of rule JSONs or transformed rules'); - } - } else { - throw new Error('Input must be a non-empty array'); - } - - console.log(JSON.stringify(result, null, 2)); - - } catch (error) { - console.log(JSON.stringify({ - success: false, - error: error.message - }, null, 2)); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/parse-functions.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/parse-functions.js deleted file mode 100644 index 5e4164ea..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/parse-functions.js +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env node -/** - * Parse custom function scripts to extract function metadata - * - * Usage: - * node parse-functions.js <function-script.js> - * node parse-functions.js --stdin (read from stdin) - * - * Output: - * JSON object with parsed function metadata and static imports - * { - * success: boolean, - * customFunction: [...], // Array of function definitions - * imports: [...] // Array of import paths (for EDS forms) - * } - */ - -'use strict'; - -const fs = require('fs'); -const path = require('path'); - -// Load globals first -require('../setup/globals'); - -// Load the custom function parser -require('../setup/loader').loadCustomFunctionParser(); - -/** - * Parse a custom function script - * @param {string} scriptContent - The JavaScript source code - * @returns {object} Parsed result with customFunction array and imports - */ -function parseCustomFunctionScript(scriptContent) { - if (!expeditor.rb.customFunctionParser) { - throw new Error('Custom function parser not loaded. Check that the JS file exists.'); - } - - const parser = expeditor.rb.customFunctionParser; - - // Parse the script to extract function definitions - const parsed = parser.parse(scriptContent); - - // Extract static imports for EDS forms - let imports = []; - if (typeof parser.extractStaticImports === 'function') { - imports = parser.extractStaticImports(scriptContent) || []; - } - - return { - customFunction: parsed.customFunction || [], - imports: imports - }; -} - -/** - * Main function - */ -function main() { - const args = process.argv.slice(2); - - if (args.length === 0) { - console.error('Usage: node parse-functions.js <function-script.js>'); - console.error(' node parse-functions.js --stdin'); - process.exit(1); - } - - let scriptContent; - - if (args[0] === '--stdin') { - // Read from stdin - scriptContent = fs.readFileSync(0, 'utf-8'); - } else { - // Read from file - const filePath = path.resolve(args[0]); - if (!fs.existsSync(filePath)) { - console.error(JSON.stringify({ - success: false, - error: 'File not found: ' + filePath - })); - process.exit(1); - } - - try { - scriptContent = fs.readFileSync(filePath, 'utf-8'); - } catch (e) { - console.error(JSON.stringify({ - success: false, - error: 'Error reading file: ' + e.message - })); - process.exit(1); - } - } - - // Parse the script - try { - const result = parseCustomFunctionScript(scriptContent); - - console.log(JSON.stringify({ - success: true, - customFunction: result.customFunction, - imports: result.imports - }, null, 2)); - } catch (e) { - console.error(JSON.stringify({ - success: false, - error: 'Parse error: ' + e.message, - stack: e.stack - })); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/rule-metadata.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/rule-metadata.js deleted file mode 100644 index 66a59ccf..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/rule-metadata.js +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env node -/** - * Extract metadata from rule JSON - * - * This CLI analyzes a rule JSON and extracts metadata about its structure. - * Useful for validation, debugging, and understanding rule contents - * without generating the actual formula. - * - * Usage: - * node rule-metadata.js <rule.json> - * node rule-metadata.js --stdin - * - * Output: - * { - * "success": true, - * "field": "$form.fieldName", - * "event": "Click", - * "eventProperty": "fd:click", - * "ruleType": "TRIGGER_SCRIPTS", - * "actions": ["SHOW_STATEMENT", "SET_VALUE_STATEMENT"], - * "hasCondition": true, - * "hasElse": false - * } - */ - -'use strict'; - -const fs = require('fs'); -const path = require('path'); - -// Load globals and setup -require('../setup/globals'); - -// Event name to property mapping -const EVENT_PROPERTY_MAPPING = { - "Calculate": "fd:calc", - "Visibility": "fd:visible", - "Initialize": "fd:init", - "Click": "fd:click", - "Value Commit": "fd:valueCommit", - "Enabled": "fd:enabled", - "Validate": "fd:validate" -}; - -// Trigger event to event name mapping -const TRIGGER_EVENT_TO_NAME = { - "is clicked": "Click", - "is changed": "Value Commit", - "is initialized": "Initialize", - "is initialised": "Initialize" -}; - -/** - * Extract field ID from COMPONENT node - */ -function extractFieldId(componentNode) { - if (!componentNode || !componentNode.value) { - return null; - } - return componentNode.value.id || null; -} - -/** - * Extract event name from TRIGGER_EVENT node - */ -function extractEventName(triggerEventNode) { - if (!triggerEventNode || !triggerEventNode.value) { - return "Value Commit"; // default - } - - const eventValue = triggerEventNode.value; - - // Check if it's a known standard event - if (TRIGGER_EVENT_TO_NAME[eventValue]) { - return TRIGGER_EVENT_TO_NAME[eventValue]; - } - - // Custom event - prefix with "custom:" - if (typeof eventValue === 'string') { - return eventValue.startsWith('custom:') ? eventValue : `custom:${eventValue}`; - } - - return "Value Commit"; -} - -/** - * Extract actions from BLOCK_STATEMENTS node - */ -function extractActions(blockStatementsNode) { - if (!blockStatementsNode || !blockStatementsNode.items) { - return []; - } - - return blockStatementsNode.items - .filter(item => item.nodeName === 'BLOCK_STATEMENT' && item.choice) - .map(item => item.choice.nodeName); -} - -/** - * Check if condition has actual content (not empty/null) - */ -function hasCondition(conditionNode) { - if (!conditionNode) { - return false; - } - // Empty condition has choice: null - return conditionNode.choice !== null && conditionNode.choice !== undefined; -} - -/** - * Transform rule JSON to execution info - */ -function transformRule(ruleJson) { - // Validate root structure - if (!ruleJson || ruleJson.nodeName !== 'ROOT') { - throw new Error('Invalid rule: must have ROOT node'); - } - - if (!ruleJson.items || ruleJson.items.length === 0) { - throw new Error('Invalid rule: ROOT must have items'); - } - - const statement = ruleJson.items[0]; - if (!statement || statement.nodeName !== 'STATEMENT') { - throw new Error('Invalid rule: first item must be STATEMENT'); - } - - if (!statement.choice || statement.choice.nodeName !== 'TRIGGER_SCRIPTS') { - throw new Error('Invalid rule: STATEMENT choice must be TRIGGER_SCRIPTS'); - } - - const triggerScripts = statement.choice; - if (!triggerScripts.items || triggerScripts.items.length === 0) { - throw new Error('Invalid rule: TRIGGER_SCRIPTS must have items'); - } - - const singleTriggerScripts = triggerScripts.items[0]; - if (!singleTriggerScripts || singleTriggerScripts.nodeName !== 'SINGLE_TRIGGER_SCRIPTS') { - throw new Error('Invalid rule: expected SINGLE_TRIGGER_SCRIPTS'); - } - - if (!singleTriggerScripts.items || singleTriggerScripts.items.length < 4) { - throw new Error('Invalid rule: SINGLE_TRIGGER_SCRIPTS must have at least 4 items'); - } - - // Extract components - const componentNode = singleTriggerScripts.items[0]; - const triggerEventNode = singleTriggerScripts.items[1]; - const triggerEventScripts = singleTriggerScripts.items[3]; - - if (!triggerEventScripts || triggerEventScripts.nodeName !== 'TRIGGER_EVENT_SCRIPTS') { - throw new Error('Invalid rule: fourth item must be TRIGGER_EVENT_SCRIPTS'); - } - - // Extract field and event info - const fieldId = extractFieldId(componentNode); - const eventName = extractEventName(triggerEventNode); - const eventProperty = EVENT_PROPERTY_MAPPING[eventName] || eventName; - - // Extract condition and actions from TRIGGER_EVENT_SCRIPTS - const items = triggerEventScripts.items || []; - - // Items structure: [CONDITION, "Then", BLOCK_STATEMENTS, ("Else", BLOCK_STATEMENTS)?] - const conditionNode = items.find(item => item.nodeName === 'CONDITION'); - const hasConditionValue = hasCondition(conditionNode); - - // Find BLOCK_STATEMENTS (then actions) - const thenBlockIndex = items.findIndex(item => item.nodeName === 'Then'); - let thenActions = []; - if (thenBlockIndex !== -1 && items[thenBlockIndex + 1]) { - thenActions = extractActions(items[thenBlockIndex + 1]); - } - - // Check for else block - const elseIndex = items.findIndex(item => item.nodeName === 'Else'); - let elseActions = []; - const hasElse = elseIndex !== -1; - if (hasElse && items[elseIndex + 1]) { - elseActions = extractActions(items[elseIndex + 1]); - } - - return { - success: true, - field: fieldId, - event: eventName, - eventProperty: eventProperty, - ruleType: "TRIGGER_SCRIPTS", - isValid: ruleJson.isValid !== false, - enabled: ruleJson.enabled !== false, - hasCondition: hasConditionValue, - hasElse: hasElse, - actions: thenActions, - elseActions: elseActions, - description: ruleJson.description || "" - }; -} - -/** - * Main CLI entry point - */ -function main() { - const args = process.argv.slice(2); - let ruleJson; - - try { - if (args.includes('--stdin')) { - // Read from stdin - const input = fs.readFileSync(0, 'utf-8'); - ruleJson = JSON.parse(input); - } else if (args.length > 0 && !args[0].startsWith('--')) { - // Read from file - const filePath = args[0]; - if (!fs.existsSync(filePath)) { - throw new Error(`File not found: ${filePath}`); - } - const content = fs.readFileSync(filePath, 'utf-8'); - ruleJson = JSON.parse(content); - } else { - console.error('Usage: node rule-metadata.js <rule.json> or node rule-metadata.js --stdin'); - process.exit(1); - } - - const result = transformRule(ruleJson); - console.log(JSON.stringify(result, null, 2)); - - } catch (error) { - console.log(JSON.stringify({ - success: false, - error: error.message - }, null, 2)); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/save-rule.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/save-rule.js deleted file mode 100644 index a1510fc2..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/save-rule.js +++ /dev/null @@ -1,1176 +0,0 @@ -#!/usr/bin/env node -/** - * Save rule to form JSON or rule store using AFJSONFormulaTransformer and AFJSONFormulaMerger - * - * Two modes: - * - * 1. FORM MODE (legacy): Save directly to form.json - * node save-rule.js <rule.json> <form.json> - * - * 2. RULE STORE MODE: Save to separate rule store file (form-sync compatible) - * node save-rule.js <rule.json> --rule-store <store.rule.json> --form <form.json> - * - * Options: - * --rule-store <file> Save to rule store file (form-sync format) - * --form <file> Form JSON file (required for component lookup) - * --dry-run Don't actually save, just show what would be saved - * --context <file> Load FormContext for component validation - * - * Rule Store Format (form-sync compatible): - * { - * "<uuid>": { - * "componentPath": "text_input", - * "componentName": "firstName", - * "fd:rules": { - * "jcr:primaryType": "nt:unstructured", - * "fd:change": [{ ...rule JSON... }] - * }, - * "fd:events": { - * "jcr:primaryType": "nt:unstructured", - * "change": ["formula string"] - * } - * } - * } - */ - -"use strict"; - -const fs = require("fs"); -const path = require("path"); -const crypto = require("crypto"); - -// Load globals and transformers -require("../setup/globals"); -require("../setup/loader").loadForRuleTransform(); - -// Load ContextLoader directly (not via vm) -const ContextLoader = require("../setup/ContextLoader"); - -// Trigger event value to event name mapping -const TRIGGER_EVENT_TO_NAME = { - "is clicked": "Click", - "is changed": "Value Commit", - "is initialised": "Initialize", - "is initialized": "Initialize", -}; - -// Event name to fd:events property mapping -const EVENT_NAME_TO_FD_PROPERTY = { - "Value Commit": "change", - Click: "click", - Initialize: "initialize", - Calculate: "calc", - Visibility: "visible", - Enabled: "enabled", - Validate: "validate", -}; - -// Event name to fd:rules property mapping (fd: prefix) -const EVENT_NAME_TO_FD_RULES_PROPERTY = { - "Value Commit": "fd:change", - Click: "fd:click", - Initialize: "fd:initialize", - Calculate: "fd:calc", - Visibility: "fd:visible", - Enabled: "fd:enabled", - Validate: "fd:validate", -}; - -// Primitive types that indicate a value (not an object reference) -const PRIMITIVE_TYPES = [ - "STRING", - "NUMBER", - "DATE", - "BOOLEAN", - "STRING[]", - "NUMBER[]", - "BOOLEAN[]", -]; - -/** - * Check if a type string contains OBJECT or AFCOMPONENT (indicating object reference expected) - */ -function isObjectTypeExpected(typeStr) { - if (!typeStr) return false; - const parts = typeStr.split("|").map((t) => t.trim().toUpperCase()); - return parts.includes("OBJECT") || parts.includes("AFCOMPONENT"); -} - -/** - * Check if a type string expects a primitive value - */ -function isPrimitiveTypeExpected(typeStr) { - if (!typeStr) return false; - const parts = typeStr.split("|").map((t) => t.trim().toUpperCase()); - // Expects primitive if it contains a primitive type AND does not expect object - return ( - parts.some((t) => PRIMITIVE_TYPES.includes(t)) && - !isObjectTypeExpected(typeStr) - ); -} - -/** - * Preprocess FUNCTION_CALL nodes to filter component types for primitive args. - * - * When a function arg expects a primitive type (STRING, NUMBER, etc.) and the - * param is a COMPONENT, the component's type should be filtered to just the - * primitive portion. This matches AEM's filterPrimitiveTypes() behavior. - * - * @param {object} node - Rule JSON node to process - * @throws {Error} If rule JSON is malformed - */ -function preprocessFunctionCallTypes(node) { - if (!node || typeof node !== "object") return; - - // If this is a FUNCTION_CALL node, process it - if (node.nodeName === "FUNCTION_CALL") { - const functionName = node.functionName; - const params = node.params; - const funcId = (functionName && functionName.id) || "<unknown>"; - - // ── Validate functionName object ──────────────────────────────── - if (!functionName) { - throw new Error( - `FUNCTION_CALL missing "functionName" object.\n` + - ` Hint: Every FUNCTION_CALL node needs a "functionName" object with at least: id, displayName, type, args, impl.\n` + - ` Got: ${JSON.stringify(node, null, 2).substring(0, 300)}`, - ); - } - - if (!functionName.args) { - throw new Error( - `FUNCTION_CALL "${funcId}" missing "functionName.args" array.\n` + - ` Hint: "args" defines the function signature. Even for zero-param functions, use "args": [].\n` + - ` Got functionName: ${JSON.stringify(functionName, null, 2).substring(0, 300)}`, - ); - } - - // Validate required functionName fields - const requiredFnFields = ["id", "displayName", "type", "impl"]; - const missingFnFields = requiredFnFields.filter( - (f) => functionName[f] === undefined || functionName[f] === null, - ); - if (missingFnFields.length > 0) { - throw new Error( - `FUNCTION_CALL "${funcId}" functionName missing required fields: ${missingFnFields.join(", ")}.\n` + - ` Required: { id, displayName, type, isDuplicate, displayPath, args, impl }\n` + - ` Hint: "impl" uses positional placeholders, e.g. "$0($1, $2)" for a 2-param function.`, - ); - } - - // Validate displayPath exists (can be empty string but must be present) - if ( - functionName.displayPath === undefined || - functionName.displayPath === null - ) { - throw new Error( - `FUNCTION_CALL "${funcId}" functionName missing "displayPath".\n` + - ` Hint: For custom/OOTB functions, set displayPath to "" (empty string).`, - ); - } - - // ── Validate each arg in the function signature ───────────────── - const args = functionName.args; - if (!Array.isArray(args)) { - throw new Error( - `FUNCTION_CALL "${funcId}": "functionName.args" must be an array.\n` + - ` Got: ${typeof args}`, - ); - } - - const requiredArgFields = ["type", "name", "description", "isMandatory"]; - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - if (!arg || typeof arg !== "object") { - throw new Error( - `FUNCTION_CALL "${funcId}": args[${i}] is not an object.\n` + - ` Expected: { "type": "STRING", "name": "paramName", "description": "What it does", "isMandatory": true }`, - ); - } - const missingArgFields = requiredArgFields.filter( - (f) => arg[f] === undefined || arg[f] === null, - ); - if (missingArgFields.length > 0) { - throw new Error( - `FUNCTION_CALL "${funcId}": args[${i}] ("${arg.name || "?"}") missing required fields: ${missingArgFields.join(", ")}.\n` + - ` Required: { type, name, description, isMandatory }\n` + - ` Got: ${JSON.stringify(arg)}\n` + - ` Fix: Add the missing fields. Example:\n` + - ` { "type": "STRING", "name": "${arg.name || "param"}", "description": "Description here", "isMandatory": true }`, - ); - } - } - - // ── Validate impl pattern matches arg count ───────────────────── - if (functionName.impl) { - const implPlaceholders = functionName.impl.match(/\$(\d+)/g) || []; - const maxPlaceholder = implPlaceholders.reduce( - (max, p) => Math.max(max, parseInt(p.substring(1))), - 0, - ); - if (args.length > 0 && maxPlaceholder !== args.length) { - console.error( - `Warning: FUNCTION_CALL "${funcId}": impl "${functionName.impl}" references up to $${maxPlaceholder} ` + - `but args has ${args.length} entries. Expected impl like "$0(${args.map((_, i) => "$" + (i + 1)).join(", ")})".`, - ); - } - } - - // ── Validate params array ─────────────────────────────────────── - if (!params || !Array.isArray(params)) { - throw new Error( - `FUNCTION_CALL "${funcId}" missing "params" array.\n` + - ` Hint: "params" is the list of actual parameter values passed to the function.\n` + - ` Even for zero-param functions, use "params": [].`, - ); - } - - // Validate: params count must match args count - if (params.length !== args.length) { - throw new Error( - `FUNCTION_CALL "${funcId}": param count (${params.length}) != arg count (${args.length}).\n` + - ` The "params" array must have exactly one entry per "args" entry.\n` + - ` Args: [${args.map((a) => a.name || "?").join(", ")}]`, - ); - } - - // ── Validate each param structure ─────────────────────────────── - for (let i = 0; i < params.length; i++) { - const param = params[i]; - const arg = args[i]; - const argLabel = `param[${i}] ("${arg.name || "?"}")`; - - if (!param || typeof param !== "object") { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} is not an object.\n` + - ` Expected: { "nodeName": "EXPRESSION", "choice": { "nodeName": "...", ... } }`, - ); - } - - // Validate param has nodeName - if (!param.nodeName) { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} missing "nodeName".\n` + - ` Expected: { "nodeName": "EXPRESSION", "choice": { ... } }\n` + - ` Got: ${JSON.stringify(param, null, 2).substring(0, 200)}`, - ); - } - - // Validate param has choice wrapper (this is the critical check that prevents - // the "getChoiceModel is not a function" crash in AFJSONFormulaTransformer) - if (!param.hasOwnProperty("choice")) { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} missing "choice" wrapper.\n` + - ` Every param must be: { "nodeName": "EXPRESSION", "choice": { "nodeName": "...", "value": ... } }\n` + - ` Got: ${JSON.stringify(param, null, 2).substring(0, 200)}\n` + - ` Fix: Wrap the param value in a "choice" object. For example:\n` + - ` COMPONENT param: { "nodeName": "EXPRESSION", "choice": { "nodeName": "COMPONENT", "value": { "id": "...", ... } } }\n` + - ` Literal param: { "nodeName": "EXPRESSION", "choice": { "nodeName": "STRING_LITERAL", "value": "..." } }`, - ); - } - - // If choice is present, validate its structure - if (param.choice !== null) { - if (typeof param.choice !== "object") { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} "choice" must be an object or null.\n` + - ` Got: ${typeof param.choice}`, - ); - } - - if (!param.choice.nodeName) { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} "choice" missing "nodeName".\n` + - ` Expected choice.nodeName to be one of: COMPONENT, STRING_LITERAL, NUMBER_LITERAL, BOOLEAN_LITERAL, FUNCTION_CALL, etc.\n` + - ` Got: ${JSON.stringify(param.choice, null, 2).substring(0, 200)}`, - ); - } - - // Validate COMPONENT params have required value fields - if (param.choice.nodeName === "COMPONENT") { - const comp = param.choice.value; - if (!comp || typeof comp !== "object") { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} COMPONENT choice missing "value" object.\n` + - ` Expected: { "nodeName": "COMPONENT", "value": { "id": "...", "displayName": "...", "type": "...", "name": "...", "parent": "..." } }`, - ); - } - const requiredCompFields = [ - "id", - "displayName", - "type", - "name", - "parent", - ]; - const missingCompFields = requiredCompFields.filter( - (f) => comp[f] === undefined || comp[f] === null, - ); - if (missingCompFields.length > 0) { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} COMPONENT value missing fields: ${missingCompFields.join(", ")}.\n` + - ` Required: { id, displayName, type, isDuplicate, displayPath, name, parent, metadata }\n` + - ` Got: ${JSON.stringify(comp, null, 2).substring(0, 300)}\n` + - ` Hint: "id" format is "$form.panelName.fieldName", "displayPath" is "FORM/panelName/", "parent" is "$form.panelName".`, - ); - } - - // Validate displayPath format for COMPONENT - if (comp.displayPath === undefined || comp.displayPath === null) { - throw new Error( - `FUNCTION_CALL "${funcId}": ${argLabel} COMPONENT missing "displayPath".\n` + - ` Hint: displayPath format is "FORM/panelName/" — it traces the path from form root to the component's parent panel.\n` + - ` Example: For field "$form.personalInfo.firstName", displayPath is "FORM/personalInfo/".`, - ); - } - } - - // Recursively process nested structures (e.g., nested FUNCTION_CALLs) - preprocessFunctionCallTypes(param.choice); - } - - // Only filter types if: - // 1. Param has a non-null choice - // 2. Param choice is a COMPONENT - // 3. Arg expects a primitive type (not OBJECT/AFCOMPONENT) - if ( - param.choice && - param.choice.nodeName === "COMPONENT" && - isPrimitiveTypeExpected(arg.type) - ) { - const component = param.choice.value; - if (component && component.type) { - // Use expeditor.Utils.filterPrimitiveTypes to filter the type - const filteredType = expeditor.Utils.filterPrimitiveTypes( - component.type, - ); - - if (!filteredType) { - throw new Error( - `FUNCTION_CALL "${funcId}": param "${arg.name}" expects primitive type "${arg.type}" ` + - `but component "${component.id}" has type "${component.type}" with no primitive portion.\n` + - ` Hint: The component's type must include a primitive type (STRING, NUMBER, BOOLEAN, DATE) ` + - `that matches what the function arg expects.`, - ); - } - - // Update the component type to the filtered value - component.type = filteredType; - } - } - } - } - - // Recursively process all child nodes - if (Array.isArray(node.items)) { - for (const item of node.items) { - preprocessFunctionCallTypes(item); - } - } - if (node.choice) { - preprocessFunctionCallTypes(node.choice); - } - if (node.params && Array.isArray(node.params)) { - for (const param of node.params) { - preprocessFunctionCallTypes(param); - } - } -} - -/** - * Generate a UUID v4 - */ -function generateUUID() { - return crypto.randomUUID(); -} - -/** - * Auto-generate context from form.json - * Runs transform-form and parse-functions internally - */ -function generateContextFromForm(formJsonPath) { - const { execSync } = require("child_process"); - const cliDir = __dirname; - - // Read form.json to get customFunctionsPath - const formJson = JSON.parse(fs.readFileSync(formJsonPath, "utf-8")); - const customFunctionsPath = formJson.customFunctionsPath; - - // Generate treeJson using transform-form - let treeJson = null; - try { - const transformResult = execSync( - `node "${path.join(cliDir, "transform-form.js")}" "${formJsonPath}"`, - { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }, - ); - const parsed = JSON.parse(transformResult); - if (parsed.success) { - treeJson = parsed.treeJson; - } - } catch (e) { - // Fall back to no treeJson if transform fails - } - - // Parse custom functions if path exists - let functions = []; - if (customFunctionsPath) { - // Resolve path relative to code directory - const jsFilePath = path.resolve( - "code", - customFunctionsPath.replace(/^\//, ""), - ); - - if (fs.existsSync(jsFilePath)) { - try { - const parseResult = execSync( - `node "${path.join(cliDir, "parse-functions.js")}" "${jsFilePath}"`, - { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }, - ); - const parsed = JSON.parse(parseResult); - if (parsed.success && parsed.customFunction) { - functions = parsed.customFunction; - } - } catch (e) { - // Fall back to empty functions if parse fails - } - } - } - - if (!treeJson) { - return null; - } - - return { treeJson, functions }; -} - -/** - * Extract trigger field and event from rule JSON - */ -function extractTriggerInfo(ruleJson) { - if (!ruleJson || ruleJson.nodeName !== "ROOT") { - throw new Error("Invalid rule JSON"); - } - - const statement = ruleJson.items[0]; - if (!statement.choice || statement.choice.nodeName !== "TRIGGER_SCRIPTS") { - throw new Error("Only TRIGGER_SCRIPTS rules are supported"); - } - - const singleTriggerScripts = statement.choice.items[0]; - const items = singleTriggerScripts.items; - const triggerComponent = items[0]; - const triggerEvent = items[1]; - - const fieldValue = triggerComponent?.value; - const fieldId = fieldValue?.id || fieldValue?.name || "$field"; - const fieldName = fieldValue?.name || fieldId.split(".").pop(); - - const eventValue = triggerEvent?.value || "is changed"; - const eventName = TRIGGER_EVENT_TO_NAME[eventValue] || eventValue; - - return { fieldId, fieldName, eventName, eventValue }; -} - -/** - * Transform a single rule JSON to script object using AFJSONFormulaTransformer - * Returns: { field, event, model, content } - */ -function transformRuleToScript(ruleJson, contextData) { - const { fieldId, fieldName, eventName } = extractTriggerInfo(ruleJson); - - // Create SimpleContext for model creation - let ctx; - if (contextData && contextData.treeJson) { - // Use validated context with real component data - ctx = ContextLoader.createValidatedContext( - contextData.treeJson, - contextData.functions, - ); - } else { - // Use synthetic context (default) - ctx = new expeditor.SimpleContext(); - } - - // Create model hierarchy from rule JSON - const model = expeditor.Utils.ModelFactory.fromJson(ruleJson, ctx); - - // Create AFJSONFormulaTransformer - const transformer = new guidelib.author.AFJSONFormulaTransformer(); - - // Set event context - transformer.setEvent({ - field: fieldId, - name: eventName, - model: null, - otherEvents: null, - }); - - // Transform via visitor pattern - model.accept(transformer); - - // Get result - returns { field, event, model, content } - return transformer.getScript(); -} - -/** - * Find a field in the form JSON by name (deep recursive search) - * Returns: { key, component, componentPath } - */ -function findFieldInForm(formJson, fieldName) { - // Special case: $form or FORM refers to the form root itself - // Rule JSON uses "name": "FORM" which matches treeJson convention - if (fieldName === "$form" || fieldName === "FORM") { - return { key: "", component: formJson, componentPath: "" }; - } - - // Deep recursive search - function searchDeep(obj, path) { - if (!obj || typeof obj !== "object") return null; - - // Check if this object has the target name - if (obj.name === fieldName) { - const key = path.split("/").filter(Boolean).pop() || fieldName; - return { key, component: obj, componentPath: path }; - } - - // Search in object properties (panel structure - keys like panelcontainer_123) - for (const key of Object.keys(obj)) { - // Skip metadata keys - if ( - key.startsWith("fd:") || - key.startsWith("jcr:") || - key === "items" || - key === "name" || - key === "fieldType" - ) - continue; - - const child = obj[key]; - if (child && typeof child === "object" && !Array.isArray(child)) { - const result = searchDeep(child, path ? `${path}/${key}` : key); - if (result) return result; - } - } - - // Search in items array - if (Array.isArray(obj.items)) { - for (const item of obj.items) { - if (item && typeof item === "object") { - const result = searchDeep(item, path); - if (result) return result; - } - } - } - - return null; - } - - return searchDeep(formJson, ""); -} - -/** - * Convert merged scripts to fd:events format - * Input: { fieldId: { eventName: { content: [...] or "..." } } } - * Output: { change: [...], click: [...], ... } - */ -function convertToFdEvents(mergedScripts, fieldId) { - const fdEvents = {}; - const fieldScripts = mergedScripts[fieldId]; - - if (!fieldScripts) { - return fdEvents; - } - - for (const [eventName, scriptObj] of Object.entries(fieldScripts)) { - const fdProperty = - EVENT_NAME_TO_FD_PROPERTY[eventName] || eventName.replace("custom:", ""); - fdEvents[fdProperty] = scriptObj.content; - } - - return fdEvents; -} - -/** - * Find component entry in rule store by component name - * Returns: { uuid, entry } or null - */ -function findComponentInRuleStore(ruleStore, componentName) { - for (const [uuid, entry] of Object.entries(ruleStore)) { - if (entry.componentName === componentName) { - return { uuid, entry }; - } - } - return null; -} - -/** - * Update form.json with refs to the rule store entry - * This ensures form-sync push can restore rules from the rule store - */ -function updateFormWithRefs(formJson, formJsonPath, fieldInfo, uuid, dryRun) { - const component = fieldInfo.component; - - // Check if refs already exist and match - const existingRulesRef = component["fd:rules"]?.ref; - const existingEventsRef = component["fd:events"]?.ref; - - if (existingRulesRef === uuid && existingEventsRef === uuid) { - // Refs already correct, no update needed - return false; - } - - // Set fd:rules and fd:events to ref objects - component["fd:rules"] = { ref: uuid }; - component["fd:events"] = { ref: uuid }; - - // Save the form JSON (unless dry-run) - if (!dryRun) { - fs.writeFileSync(formJsonPath, JSON.stringify(formJson, null, 2)); - } - - return true; -} - -/** - * Save rule to rule store (form-sync format) - */ -function saveToRuleStore( - ruleJsonPath, - ruleStorePath, - formJsonPath, - options = {}, -) { - // Read new rule JSON - if (!fs.existsSync(ruleJsonPath)) { - throw new Error(`Rule file not found: ${ruleJsonPath}`); - } - const newRuleJson = JSON.parse(fs.readFileSync(ruleJsonPath, "utf-8")); - - // Read form JSON for component lookup - if (!fs.existsSync(formJsonPath)) { - throw new Error(`Form file not found: ${formJsonPath}`); - } - const formJson = JSON.parse(fs.readFileSync(formJsonPath, "utf-8")); - - // Read existing rule store (or create empty) - let ruleStore = {}; - if (fs.existsSync(ruleStorePath)) { - ruleStore = JSON.parse(fs.readFileSync(ruleStorePath, "utf-8")); - } - - // Extract trigger info from new rule - const { fieldId, fieldName, eventName } = extractTriggerInfo(newRuleJson); - - // Find the field in the form - const fieldInfo = findFieldInForm(formJson, fieldName); - if (!fieldInfo) { - throw new Error(`Field '${fieldName}' not found in form`); - } - - // Find or create component entry in rule store - let componentEntry = findComponentInRuleStore(ruleStore, fieldName); - let uuid; - - if (componentEntry) { - uuid = componentEntry.uuid; - } else { - // Create new entry - uuid = generateUUID(); - ruleStore[uuid] = { - componentPath: fieldInfo.componentPath, - componentName: fieldName, - "fd:rules": { - "jcr:primaryType": "nt:unstructured", - }, - "fd:events": { - "jcr:primaryType": "nt:unstructured", - }, - }; - } - - const entry = ruleStore[uuid]; - - // Get the fd:rules property key for this event - // For custom events like "custom:enableContinueButton", generate "fd:custom_enableContinueButton" - // This matches the behavior in af-exp-editor RuleSaveHandler.js line 213-214 - let fdRulesKey, fdEventsKey; - if (eventName.startsWith("custom:")) { - const customEventName = eventName.substring("custom:".length); - fdRulesKey = `fd:custom_${customEventName}`; - fdEventsKey = customEventName; - } else { - fdRulesKey = - EVENT_NAME_TO_FD_RULES_PROPERTY[eventName] || - `fd:${eventName.toLowerCase()}`; - fdEventsKey = - EVENT_NAME_TO_FD_PROPERTY[eventName] || eventName.toLowerCase(); - } - - // Get existing rules for this event - const existingRules = entry["fd:rules"][fdRulesKey] || []; - - // Check if a rule with the same eventName already exists (replace vs append) - const newEventName = newRuleJson.eventName; - const existingIndex = newEventName - ? existingRules.findIndex((r) => r.eventName === newEventName) - : -1; - - let allRules; - let mode; - if (existingIndex >= 0) { - // Replace existing rule with same eventName - allRules = [...existingRules]; - allRules[existingIndex] = newRuleJson; - mode = "replaced"; - } else { - // Append new rule - allRules = [...existingRules, newRuleJson]; - mode = "added"; - } - - // Transform ALL rules for this component to scripts - // Use the deduplicated allRules for the current event, plus rules from other events - const scriptArray = []; - - for (const [key, rules] of Object.entries(entry["fd:rules"])) { - if (!key.startsWith("fd:") || !Array.isArray(rules)) continue; - - // For the current event key, use allRules (deduplicated); for others, use as-is - const rulesToTransform = key === fdRulesKey ? allRules : rules; - - for (const rule of rulesToTransform) { - try { - // Deep clone before preprocessing to preserve original rule JSON - const ruleClone = JSON.parse(JSON.stringify(rule)); - // Preprocess to filter component types for primitive args - preprocessFunctionCallTypes(ruleClone); - const script = transformRuleToScript(ruleClone, options.contextData); - scriptArray.push(script); - } catch (e) { - console.error( - `Warning: Failed to transform existing rule: ${e.message}`, - ); - } - } - } - - // If this is a NEW event key (not yet in fd:rules), transform the new rule separately - if (!entry["fd:rules"][fdRulesKey]) { - try { - const newRuleClone = JSON.parse(JSON.stringify(newRuleJson)); - preprocessFunctionCallTypes(newRuleClone); - const newScript = transformRuleToScript( - newRuleClone, - options.contextData, - ); - scriptArray.push(newScript); - } catch (e) { - throw new Error(`Failed to transform new rule: ${e.message}`); - } - } - - // Use AFJSONFormulaMerger to merge all scripts - const mergedScripts = - guidelib.author.AFJSONFormulaMerger.mergeScript(scriptArray); - - // Convert merged scripts to fd:events format - const fdEvents = convertToFdEvents(mergedScripts, fieldId); - - // Update entry with new rule - entry["fd:rules"][fdRulesKey] = allRules; - entry["fd:rules"]["validationStatus"] = "valid"; - - // Update fd:events with all merged formulas - for (const [eventKey, formulas] of Object.entries(fdEvents)) { - entry["fd:events"][eventKey] = formulas; - } - - // Save the rule store (unless dry-run) - if (!options.dryRun) { - fs.writeFileSync(ruleStorePath, JSON.stringify(ruleStore, null, 2)); - } - - // Update form.json with refs to the rule store entry - const formUpdated = updateFormWithRefs( - formJson, - formJsonPath, - fieldInfo, - uuid, - options.dryRun, - ); - - console.log( - ` Rule ${mode} for event "${fdRulesKey}" (${allRules.length} rules for this event, ${scriptArray.length} total scripts for component)`, - ); - - return { - success: true, - mode: "rule-store", - saveMode: mode, // "replaced" or "added" - ruleStoreFile: ruleStorePath, - formFile: formJsonPath, - formUpdated: formUpdated, - componentPath: fieldInfo.componentPath, - componentName: fieldName, - uuid: uuid, - event: fdEventsKey, - rulesCount: allRules.length, - totalRulesForComponent: scriptArray.length, - dryRun: options.dryRun || false, - validationEnabled: !!(options.contextData && options.contextData.treeJson), - fdEvents: entry["fd:events"], - }; -} - -/** - * Save rule to form JSON (legacy mode) - */ -function saveToForm(ruleJsonPath, formJsonPath, options = {}) { - // Read new rule JSON - if (!fs.existsSync(ruleJsonPath)) { - throw new Error(`Rule file not found: ${ruleJsonPath}`); - } - const newRuleJson = JSON.parse(fs.readFileSync(ruleJsonPath, "utf-8")); - - // Read form JSON - if (!fs.existsSync(formJsonPath)) { - throw new Error(`Form file not found: ${formJsonPath}`); - } - const formJson = JSON.parse(fs.readFileSync(formJsonPath, "utf-8")); - - // Extract trigger info from new rule - const { fieldId, fieldName, eventName } = extractTriggerInfo(newRuleJson); - - // Find the field in the form - const fieldInfo = findFieldInForm(formJson, fieldName); - if (!fieldInfo) { - throw new Error(`Field '${fieldName}' not found in form`); - } - - // Get existing rules from fd:rules - const existingFdRules = fieldInfo.component["fd:rules"] || {}; - const existingRules = existingFdRules.rules || []; - - // Add new rule to the list - const allRules = [...existingRules, newRuleJson]; - - // Transform ALL rules to scripts - const scriptArray = []; - for (const ruleJson of allRules) { - try { - // Deep clone before preprocessing to preserve original rule JSON - const ruleClone = JSON.parse(JSON.stringify(ruleJson)); - // Preprocess to filter component types for primitive args - preprocessFunctionCallTypes(ruleClone); - const script = transformRuleToScript(ruleClone, options.contextData); - scriptArray.push(script); - } catch (e) { - console.error(`Warning: Failed to transform rule: ${e.message}`); - } - } - - // Use AFJSONFormulaMerger to merge all scripts - const mergedScripts = - guidelib.author.AFJSONFormulaMerger.mergeScript(scriptArray); - - // Convert merged scripts to fd:events format - const fdEvents = convertToFdEvents(mergedScripts, fieldId); - - // Prepare fd:rules (store rule JSONs for re-editing) - const fdRules = { rules: allRules }; - - // Update the field with fd:rules and fd:events - fieldInfo.component["fd:rules"] = fdRules; - fieldInfo.component["fd:events"] = fdEvents; - - // Save the form JSON (unless dry-run) - if (!options.dryRun) { - fs.writeFileSync(formJsonPath, JSON.stringify(formJson, null, 2)); - } - - return { - success: true, - mode: "form", - field: fieldName, - fieldPath: fieldId, - rulesCount: allRules.length, - formPath: formJsonPath, - events: Object.keys(fdEvents), - dryRun: options.dryRun || false, - validationEnabled: !!(options.contextData && options.contextData.treeJson), - fdEvents: fdEvents, - }; -} - -/** - * Resave all rules in a rule store to regenerate fd:events - */ -function resaveRuleStore(ruleStorePath, formJsonPath, options = {}) { - // Read existing rule store - if (!fs.existsSync(ruleStorePath)) { - throw new Error(`Rule store not found: ${ruleStorePath}`); - } - const ruleStore = JSON.parse(fs.readFileSync(ruleStorePath, "utf-8")); - - // Auto-generate context from form.json - const contextData = - options.contextData || generateContextFromForm(formJsonPath); - if (!contextData) { - throw new Error("Failed to generate context from form.json"); - } - - const results = { - success: true, - mode: "resave", - ruleStoreFile: ruleStorePath, - formFile: formJsonPath, - components: [], - totalRules: 0, - errors: [], - dryRun: options.dryRun || false, - }; - - // Process each component in the rule store - for (const [uuid, entry] of Object.entries(ruleStore)) { - const componentName = entry.componentName; - const fdRules = entry["fd:rules"] || {}; - const componentResult = { - uuid, - componentName, - rulesProcessed: 0, - events: [], - }; - - // Collect all rules for this component and transform them - const scriptArray = []; - let fieldId = null; - - for (const [fdKey, rules] of Object.entries(fdRules)) { - if (!fdKey.startsWith("fd:") || !Array.isArray(rules)) continue; - - for (const rule of rules) { - try { - // Deep clone before preprocessing to preserve original rule JSON - const ruleClone = JSON.parse(JSON.stringify(rule)); - // Preprocess to filter component types for primitive args - preprocessFunctionCallTypes(ruleClone); - const script = transformRuleToScript(ruleClone, contextData); - scriptArray.push(script); - if (!fieldId && script.field) { - fieldId = script.field; - } - componentResult.rulesProcessed++; - results.totalRules++; - } catch (e) { - const errorMsg = `${componentName}/${fdKey}: ${e.message}`; - results.errors.push(errorMsg); - results.success = false; - } - } - } - - // If we have scripts, merge and update fd:events - if (scriptArray.length > 0 && fieldId) { - const mergedScripts = - guidelib.author.AFJSONFormulaMerger.mergeScript(scriptArray); - const fdEvents = convertToFdEvents(mergedScripts, fieldId); - - // Preserve jcr:primaryType if it exists - const existingPrimaryType = entry["fd:events"]?.["jcr:primaryType"]; - entry["fd:events"] = { - ...(existingPrimaryType - ? { "jcr:primaryType": existingPrimaryType } - : {}), - ...fdEvents, - }; - - componentResult.events = Object.keys(fdEvents); - } - - results.components.push(componentResult); - } - - // Save the updated rule store (unless dry-run or errors) - if (!options.dryRun && results.success) { - fs.writeFileSync(ruleStorePath, JSON.stringify(ruleStore, null, 2)); - } - - return results; -} - -/** - * Parse command line arguments - */ -function parseArgs(args) { - const result = { - command: "save", // 'save' or 'resave' - ruleFile: null, - formFile: null, - ruleStoreFile: null, - contextFile: null, - dryRun: false, - }; - - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - - if (arg === "resave") { - result.command = "resave"; - } else if (arg === "--dry-run") { - result.dryRun = true; - } else if (arg === "--context" && args[i + 1]) { - result.contextFile = args[++i]; - } else if (arg === "--rule-store" && args[i + 1]) { - result.ruleStoreFile = args[++i]; - } else if (arg === "--form" && args[i + 1]) { - result.formFile = args[++i]; - } else if (!arg.startsWith("--")) { - if (!result.ruleFile) { - result.ruleFile = arg; - } else if (!result.formFile) { - // Legacy mode: second positional arg is form file - result.formFile = arg; - } - } - } - - return result; -} - -/** - * Print usage information - */ -function printUsage() { - console.error(`Usage: - Save rule (form-sync compatible): - node save-rule.js <rule.json> --rule-store <store.rule.json> --form <form.json> [--dry-run] - - Resave all rules (regenerate fd:events for entire rule store): - node save-rule.js resave --rule-store <store.rule.json> --form <form.json> [--dry-run] - - Form mode (legacy): - node save-rule.js <rule.json> <form.json> [--dry-run] - -Options: - --rule-store <file> Rule store file (form-sync format) - --form <file> Form JSON file (auto-generates context) - --dry-run Don't actually save, just show what would be saved - --context <file> Override auto-generated context (advanced) -`); -} - -/** - * Main CLI entry point - */ -function main() { - const args = process.argv.slice(2); - const parsedArgs = parseArgs(args); - - // Handle resave command - if (parsedArgs.command === "resave") { - if (!parsedArgs.ruleStoreFile || !parsedArgs.formFile) { - console.error("Error: resave requires --rule-store and --form"); - printUsage(); - process.exit(1); - } - - try { - let contextData = null; - if (parsedArgs.contextFile) { - contextData = ContextLoader.loadFromFile(parsedArgs.contextFile); - } - - const result = resaveRuleStore( - parsedArgs.ruleStoreFile, - parsedArgs.formFile, - { - dryRun: parsedArgs.dryRun, - contextData: contextData, - }, - ); - console.log(JSON.stringify(result, null, 2)); - if (!result.success) { - process.exit(1); - } - } catch (error) { - console.log( - JSON.stringify( - { - success: false, - error: error.message, - stack: process.env.DEBUG === "true" ? error.stack : undefined, - }, - null, - 2, - ), - ); - process.exit(1); - } - return; - } - - // Save command - validate arguments - if (!parsedArgs.ruleFile) { - printUsage(); - process.exit(1); - } - - const isRuleStoreMode = !!parsedArgs.ruleStoreFile; - - if (isRuleStoreMode) { - if (!parsedArgs.formFile) { - console.error("Error: --form is required when using --rule-store"); - printUsage(); - process.exit(1); - } - } else { - if (!parsedArgs.formFile) { - printUsage(); - process.exit(1); - } - } - - try { - // Load context if provided, otherwise auto-generate from form.json - let contextData = null; - if (parsedArgs.contextFile) { - contextData = ContextLoader.loadFromFile(parsedArgs.contextFile); - } else if (parsedArgs.formFile) { - contextData = generateContextFromForm(parsedArgs.formFile); - } - - let result; - if (isRuleStoreMode) { - result = saveToRuleStore( - parsedArgs.ruleFile, - parsedArgs.ruleStoreFile, - parsedArgs.formFile, - { - dryRun: parsedArgs.dryRun, - contextData: contextData, - }, - ); - } else { - result = saveToForm(parsedArgs.ruleFile, parsedArgs.formFile, { - dryRun: parsedArgs.dryRun, - contextData: contextData, - }); - } - - console.log(JSON.stringify(result, null, 2)); - } catch (error) { - console.log( - JSON.stringify( - { - success: false, - error: error.message, - stack: process.env.DEBUG === "true" ? error.stack : undefined, - }, - null, - 2, - ), - ); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/summary.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/summary.js deleted file mode 100644 index 4f645258..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/summary.js +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/env node -/** - * Generate human-readable summary from rule JSON using ToSummaryTransformer - * - * This CLI uses the ACTUAL ToSummaryTransformer from the rule editor - * to ensure summaries match exactly what the UI would display. - * - * Usage: - * node summary.js <rule.json> - * node summary.js <rule.json> --context <context.json> - * node summary.js --stdin - * - * Options: - * --context <file> Load FormContext for component validation and rich display names - * - * Output: - * { - * "success": true, - * "title": "firstName - is changed", - * "content": "WHEN firstName is changed THEN Show fullName", - * "eventName": "is changed", - * "field": "$form.firstName", - * "validationEnabled": true - * } - */ - -'use strict'; - -const fs = require('fs'); -const path = require('path'); - -// Load globals and transformers -require('../setup/globals'); -const loader = require('../setup/loader'); -loader.loadForRuleTransform(); - -// Load ContextLoader directly (not via vm) -const ContextLoader = require('../setup/ContextLoader'); - -// Trigger event value to event name mapping -const TRIGGER_EVENT_TO_NAME = { - "is clicked": "Click", - "is changed": "Value Commit", - "is initialised": "Initialize", - "is initialized": "Initialize" -}; - -/** - * Extract trigger field and event from rule JSON - */ -function extractTriggerInfo(ruleJson) { - if (!ruleJson || ruleJson.nodeName !== 'ROOT') { - throw new Error('Invalid rule JSON'); - } - - const statement = ruleJson.items[0]; - if (!statement.choice || statement.choice.nodeName !== 'TRIGGER_SCRIPTS') { - throw new Error('Only TRIGGER_SCRIPTS rules are supported'); - } - - const singleTriggerScripts = statement.choice.items[0]; - const items = singleTriggerScripts.items; - const triggerComponent = items[0]; - const triggerEvent = items[1]; - - const fieldValue = triggerComponent?.value; - const fieldId = fieldValue?.id || fieldValue?.name || '$field'; - const fieldName = fieldValue?.name || fieldId.split('.').pop(); - - const eventValue = triggerEvent?.value || 'is changed'; - const eventName = TRIGGER_EVENT_TO_NAME[eventValue] || eventValue; - - return { fieldId, fieldName, eventName, eventValue }; -} - -/** - * Generate summary using actual ToSummaryTransformer - * - * @param {Object} ruleJson - Rule JSON to summarize - * @param {Object} contextData - Optional FormContext data (treeJson + functions) - */ -function generateSummary(ruleJson, contextData) { - const { fieldId, fieldName, eventName, eventValue } = extractTriggerInfo(ruleJson); - - // Create SimpleContext for model creation - let ctx; - let validationEnabled = false; - - if (contextData && contextData.treeJson) { - // Use validated context with real component data - ctx = ContextLoader.createValidatedContext(contextData.treeJson, contextData.functions); - validationEnabled = true; - } else { - // Use synthetic context (default) - ctx = new expeditor.SimpleContext(); - } - - // Set the currentFieldId for the context (used by transformer) - ctx.currentFieldId = fieldId; - - // Create model hierarchy from rule JSON - const model = expeditor.Utils.ModelFactory.fromJson(ruleJson, ctx); - - // Create ToSummaryTransformer - // Use guidelib.author.ToSummaryTransformer which handles TRIGGER_SCRIPTS - const transformer = new guidelib.author.ToSummaryTransformer(ctx); - - // Set to plain text mode (no HTML tags) - transformer.setMode(transformer.PLAIN_TEXT_MODE); - - // Transform via visitor pattern - model.accept(transformer); - - // Get result - const result = transformer.getScript(); - - return { - success: true, - title: result.title || `${fieldName} - ${eventValue}`, - tooltipTitle: result.tooltipTitle, - content: result.content, - eventName: result.eventName || eventName, - field: fieldId, - isValid: result.isvalid !== false, - enabled: result.enabled !== false, - validationEnabled: validationEnabled, - isBroken: result.isBroken || false - }; -} - -/** - * Parse command line arguments - */ -function parseArgs(args) { - const result = { - ruleFile: null, - contextFile: null, - useStdin: false - }; - - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - - if (arg === '--stdin') { - result.useStdin = true; - } else if (arg === '--context' && args[i + 1]) { - result.contextFile = args[++i]; - } else if (!arg.startsWith('--') && !result.ruleFile) { - result.ruleFile = arg; - } - } - - return result; -} - -/** - * Main CLI entry point - */ -function main() { - const args = process.argv.slice(2); - const parsedArgs = parseArgs(args); - - let ruleJson; - let contextData = null; - - try { - // Load rule JSON - if (parsedArgs.useStdin) { - const input = fs.readFileSync(0, 'utf-8'); - ruleJson = JSON.parse(input); - } else if (parsedArgs.ruleFile) { - if (!fs.existsSync(parsedArgs.ruleFile)) { - throw new Error(`File not found: ${parsedArgs.ruleFile}`); - } - const content = fs.readFileSync(parsedArgs.ruleFile, 'utf-8'); - ruleJson = JSON.parse(content); - } else { - console.error('Usage: node summary.js <rule.json> [--context <context.json>]'); - console.error(' node summary.js --stdin [--context <context.json>]'); - process.exit(1); - } - - // Load context if provided - if (parsedArgs.contextFile) { - contextData = ContextLoader.loadFromFile(parsedArgs.contextFile); - } - - const result = generateSummary(ruleJson, contextData); - console.log(JSON.stringify(result, null, 2)); - - } catch (error) { - console.log(JSON.stringify({ - success: false, - error: error.message, - stack: process.env.DEBUG === 'true' ? error.stack : undefined - }, null, 2)); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/transform-form.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/transform-form.js deleted file mode 100644 index 2dac1d48..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/cli/transform-form.js +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env node -/** - * Transform form definition JSON to treeJson - * - * Usage: - * node transform-form.js <form-definition.json> - * node transform-form.js --stdin (read from stdin) - * - * Output: - * JSON object with the transformed treeJson structure to stdout - * - * The treeJson structure is used for component lookup when generating rules. - * Each component has: id, name, displayName, type, fieldType, path, etc. - * - * Supports both JCR format (from AEM) and CRISPR/CoreComponent format. - * JCR format is automatically detected and converted to CRISPR before transformation. - */ - -"use strict"; - -const fs = require("fs"); -const path = require("path"); -const { execSync } = require("child_process"); - -// Load globals first -require("../setup/globals"); - -// Load the ExpressionEditorTree -require("../setup/loader").loadExpressionEditorTree(); - -/** - * Check if the form JSON is in JCR format (has JCR/Sling properties) - * @param {object} formJson - The form JSON to check - * @returns {boolean} True if JCR format - */ -function isJcrFormat(formJson) { - return ( - formJson["jcr:primaryType"] !== undefined || - formJson["sling:resourceType"] !== undefined - ); -} - -/** - * Get the Python executable path - * Checks multiple locations to find Python with formsgenailib installed - * @returns {string} Python executable path - */ -function getPythonPath() { - const candidates = []; - - // Check for plugin's own scripts/python3 (handles venv bootstrap) - const pluginRoot = path.resolve(__dirname, "../../../../"); - const pluginPython = path.join(pluginRoot, "scripts", "python3"); - if (fs.existsSync(pluginPython)) { - candidates.push(pluginPython); - } - - // Check for .venv at project root (one level above plugin root) - const projectRoot = path.resolve(pluginRoot, ".."); - candidates.push(path.join(projectRoot, ".venv", "bin", "python")); - - // Check for active virtualenv - if (process.env.VIRTUAL_ENV) { - candidates.push(path.join(process.env.VIRTUAL_ENV, "bin", "python")); - } - - // Try each candidate — just check it exists and runs - for (const candidate of candidates) { - if (fs.existsSync(candidate)) { - return candidate; - } - } - - // Fallback to system python3 - return "python3"; -} - -/** - * Convert JCR form JSON to CRISPR format using Python script - * @param {object} jcrJson - The JCR form JSON - * @returns {object} The CRISPR form JSON - */ -function convertJcrToCrispr(jcrJson) { - const scriptPath = path.join(__dirname, "jcr-to-crispr.py"); - const pythonPath = getPythonPath(); - - try { - // Run Python script with JSON input via stdin - const result = execSync(`"${pythonPath}" "${scriptPath}" --stdin`, { - input: JSON.stringify(jcrJson), - encoding: "utf-8", - maxBuffer: 10 * 1024 * 1024, // 10MB buffer for large forms - }); - - const parsed = JSON.parse(result); - - if (!parsed.success) { - throw new Error(parsed.error || "Unknown conversion error"); - } - - return parsed.crispr; - } catch (e) { - if (e.stdout) { - try { - const parsed = JSON.parse(e.stdout); - if (parsed.success) { - return parsed.crispr; - } - } catch (parseErr) { - // Ignore parse error, use original error - } - } - throw new Error(`JCR to CRISPR conversion failed: ${e.message}`); - } -} - -/** - * Transform form JSON to treeJson - * @param {object} formJson - The form definition JSON (JCR or CRISPR format) - * @returns {{treeJson: object, converted: boolean}} The transformed treeJson and conversion flag - */ -function transformFormJson(formJson) { - if (!af.expeditor.author.ExpressionEditorTree) { - throw new Error( - "ExpressionEditorTree not loaded. Check that the JS file exists.", - ); - } - - let inputJson = formJson; - let converted = false; - - // Detect fragment from original JCR before conversion (fd:type is lost during conversion) - const isFragment = formJson["fd:type"] === "fragment"; - - // Auto-detect and convert JCR format to CRISPR - if (isJcrFormat(formJson)) { - inputJson = convertJcrToCrispr(formJson); - converted = true; - } - - const treeJson = - af.expeditor.author.ExpressionEditorTree.transformJson(inputJson); - - // Set isFragment flag on treeJson if detected from original JCR - // This is needed because fd:type is lost during JCR->CRISPR conversion - // SimpleContext.js uses this to set $form name/displayName to 'FRAGMENT' - if (isFragment) { - treeJson.isFragment = true; - } - - return { treeJson, converted }; -} - -/** - * Main function - */ -function main() { - const args = process.argv.slice(2); - - if (args.length === 0) { - console.error("Usage: node transform-form.js <form-definition.json>"); - console.error(" node transform-form.js --stdin"); - process.exit(1); - } - - let formJson; - - if (args[0] === "--stdin") { - // Read from stdin - let input = ""; - const stdin = fs.readFileSync(0, "utf-8"); - try { - formJson = JSON.parse(stdin); - } catch (e) { - console.error( - JSON.stringify({ - success: false, - error: "Invalid JSON input: " + e.message, - }), - ); - process.exit(1); - } - } else { - // Read from file - const filePath = path.resolve(args[0]); - if (!fs.existsSync(filePath)) { - console.error( - JSON.stringify({ - success: false, - error: "File not found: " + filePath, - }), - ); - process.exit(1); - } - - try { - const content = fs.readFileSync(filePath, "utf-8"); - formJson = JSON.parse(content); - } catch (e) { - console.error( - JSON.stringify({ - success: false, - error: "Error reading/parsing file: " + e.message, - }), - ); - process.exit(1); - } - } - - // Transform the form JSON - try { - const { treeJson, converted } = transformFormJson(formJson); - - console.log( - JSON.stringify( - { - success: true, - treeJson: treeJson, - jcrConverted: converted, - }, - null, - 2, - ), - ); - } catch (e) { - console.error( - JSON.stringify({ - success: false, - error: "Transform error: " + e.message, - stack: e.stack, - }), - ); - process.exit(1); - } -} - -main(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/package-lock.json b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/package-lock.json deleted file mode 100644 index b25ba758..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/package-lock.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "rule_coder_bridge", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "rule_coder_bridge", - "version": "1.0.0", - "dependencies": { - "lodash": "^4.17.21" - } - }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "license": "MIT" - } - } -} diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/package.json b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/package.json deleted file mode 100644 index b01dcf2e..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "rule_coder_bridge", - "version": "1.0.0", - "description": "Node.js CLI bridge for AEM Forms rule generation", - "private": true, - "scripts": { - "transform-form": "node cli/transform-form.js", - "parse-functions": "node cli/parse-functions.js", - "transform": "node cli/transform.js", - "summary": "node cli/summary.js", - "merge": "node cli/merge.js" - }, - "dependencies": { - "lodash": "^4.17.21" - } -} diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/ContextLoader.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/ContextLoader.js deleted file mode 100644 index 72c2bc4d..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/ContextLoader.js +++ /dev/null @@ -1,237 +0,0 @@ -/** - * ContextLoader - Load and cache FormContext for CLI tools - * - * This module provides utilities to load FormContext data (treeJson + functions) - * and configure SimpleContext/SimpleScope for validation mode. - * - * Usage: - * // Load from file - * const ctx = ContextLoader.loadFromFile('context.json'); - * - * // Load from JSON object - * const ctx = ContextLoader.loadFromJson({ treeJson: {...}, functions: [...] }); - * - * // Create context with validation enabled - * const simpleCtx = ContextLoader.createValidatedContext(treeJson, functions); - */ -'use strict'; - -// Use global require/fs/path if available (Node.js context) -var fs = typeof require !== 'undefined' ? require('fs') : null; -var path = typeof require !== 'undefined' ? require('path') : null; - -// In-memory cache for loaded contexts -const contextCache = {}; - -// Cached grammar (loaded once) -var cachedGrammar = null; - -/** - * ContextLoader - manages loading and caching of FormContext data - */ -const ContextLoader = { - /** - * Load context from a JSON file - * - * @param {string} filePath - Path to context JSON file - * @param {boolean} useCache - Whether to use cached version (default: true) - * @returns {Object} Context data with treeJson and functions - */ - loadFromFile: function (filePath, useCache = true) { - const absPath = path.resolve(filePath); - - // Check cache - if (useCache && contextCache[absPath]) { - const cached = contextCache[absPath]; - const currentMtime = fs.statSync(absPath).mtimeMs; - - if (currentMtime === cached.mtime) { - return cached.data; - } - } - - // Load fresh - if (!fs.existsSync(absPath)) { - throw new Error(`Context file not found: ${absPath}`); - } - - const content = fs.readFileSync(absPath, 'utf-8'); - const data = JSON.parse(content); - - // Validate structure - if (!data.treeJson) { - throw new Error('Invalid context: missing treeJson'); - } - - // Cache it - contextCache[absPath] = { - data: data, - mtime: fs.statSync(absPath).mtimeMs - }; - - return data; - }, - - /** - * Load context from JSON object - * - * @param {Object} json - Context object with treeJson and optional functions - * @returns {Object} Context data - */ - loadFromJson: function (json) { - if (!json || !json.treeJson) { - throw new Error('Invalid context: missing treeJson'); - } - - return { - treeJson: json.treeJson, - functions: json.functions || [] - }; - }, - - /** - * Load context from stdin (for piped input) - * - * @returns {Promise<Object>} Context data - */ - loadFromStdin: function () { - return new Promise((resolve, reject) => { - let input = ''; - - process.stdin.setEncoding('utf-8'); - process.stdin.on('data', chunk => { input += chunk; }); - process.stdin.on('end', () => { - try { - const data = JSON.parse(input); - resolve(this.loadFromJson(data)); - } catch (e) { - reject(new Error(`Failed to parse context from stdin: ${e.message}`)); - } - }); - process.stdin.on('error', reject); - }); - }, - - /** - * Load the annotated grammar for model class resolution - * Caches the grammar after first load - * - * @returns {Object|null} Grammar object or null if not found - */ - loadGrammar: function () { - if (cachedGrammar) { - return cachedGrammar; - } - - // Try to load from global if already loaded by loader.js - if (typeof global !== 'undefined' && global.AnnotatedGrammar) { - cachedGrammar = global.AnnotatedGrammar; - return cachedGrammar; - } - - // Load from file - const grammarPath = path.resolve(__dirname, '../../grammar/annotated_subset_grammar.json'); - - if (!fs.existsSync(grammarPath)) { - return null; - } - - try { - const content = fs.readFileSync(grammarPath, 'utf-8'); - cachedGrammar = JSON.parse(content); - return cachedGrammar; - } catch (e) { - console.error('Error loading grammar:', e.message); - return null; - } - }, - - /** - * Create a SimpleContext with validation enabled - * Also sets the grammar for proper model class resolution - * - * @param {Object} treeJson - Form tree JSON - * @param {Array} functions - Array of function definitions - * @returns {expeditor.SimpleContext} Configured context - */ - createValidatedContext: function (treeJson, functions) { - const ctx = new expeditor.SimpleContext(); - - // Load and set grammar for model class resolution - const grammar = this.loadGrammar(); - if (grammar) { - ctx.setGrammar(grammar); - } - - ctx.getScope().loadFromTreeJson(treeJson, functions); - return ctx; - }, - - /** - * Create SimpleContext from context file - * - * @param {string} filePath - Path to context JSON file - * @returns {expeditor.SimpleContext} Configured context with validation - */ - createContextFromFile: function (filePath) { - const data = this.loadFromFile(filePath); - return this.createValidatedContext(data.treeJson, data.functions); - }, - - /** - * Invalidate cached context - * - * @param {string} filePath - Path to context file to invalidate - */ - invalidateCache: function (filePath) { - const absPath = path.resolve(filePath); - delete contextCache[absPath]; - }, - - /** - * Clear all cached contexts - */ - clearCache: function () { - Object.keys(contextCache).forEach(key => delete contextCache[key]); - }, - - /** - * Get cache info for debugging - * - * @returns {Object} Cache statistics - */ - getCacheInfo: function () { - const entries = Object.keys(contextCache).map(key => ({ - path: key, - mtime: contextCache[key].mtime, - componentsCount: Object.keys(contextCache[key].data.treeJson.items || {}).length, - functionsCount: (contextCache[key].data.functions || []).length - })); - - return { - entriesCount: entries.length, - entries: entries - }; - }, - - /** - * Export context to file (for sharing between processes) - * - * @param {Object} contextData - Context data to export - * @param {string} filePath - Output file path - */ - exportToFile: function (contextData, filePath) { - const output = JSON.stringify(contextData, null, 2); - fs.writeFileSync(filePath, output, 'utf-8'); - } -}; - -// Export for Node.js -if (typeof module !== 'undefined' && module.exports) { - module.exports = ContextLoader; -} - -// Also attach to global for use in loaded scripts -if (typeof global !== 'undefined') { - global.ContextLoader = ContextLoader; -} diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/SimpleContext.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/SimpleContext.js deleted file mode 100644 index 4f01fb1e..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/SimpleContext.js +++ /dev/null @@ -1,486 +0,0 @@ -/** - * SimpleContext - A minimal ExpEditorContext for CLI transformation - * - * This context allows creating models from rule JSON using: - * 1. Grammar's node_type field (from annotated_subset_grammar.json) - * 2. JSON structure fallback (choice/items/value properties) - * - * Model type determination: - * - node_type: "CHOICE" → ChoiceModel - * - node_type: "SEQUENCE" → SequenceModel - * - node_type: "ARRAY" → ListModel - * - node_type: "TERMINAL" or "LITERAL_TOKEN" → TerminalModel - * - * Special models (handled explicitly): - * - ROOT → RootModel (extends SequenceModel) - * - CONDITION → ConditionModel (extends ChoiceModel) - * - SCRIPTMODEL → ScriptModel - * - RULES → ListModel (meta-structure, not in grammar) - */ -'use strict'; - -(function (expeditor) { - - /** - * Map grammar node_type to model classes - * This is the core of Option C - using grammar's explicit node_type - */ - var NODE_TYPE_TO_MODEL = { - 'SEQUENCE': 'SequenceModel', - 'CHOICE': 'ChoiceModel', - 'TERMINAL': 'TerminalModel', - 'ARRAY': 'ListModel', - 'LITERAL_TOKEN': 'TerminalModel' - }; - - /** - * Special node names that need specific model classes - * These can't be determined from node_type alone because they extend base models - */ - var SPECIAL_MODELS = { - 'ROOT': 'RootModel', // extends SequenceModel - 'CONDITION': 'ConditionModel', // extends ChoiceModel (has nested property) - 'SCRIPTMODEL': 'ScriptModel', // code editor model - 'RULES': 'ListModel', // meta-structure for rule list - 'FUNCTION_CALL': 'FunctionModel' // function calls have special JSON structure (functionName, params) - }; - - /** - * SimpleScope - a scope implementation for CLI use - * - * Can operate in two modes: - * 1. Synthetic mode (default) - returns synthetic data from ID - * 2. Validated mode - uses treeJson to validate components exist - * - * Usage: - * var scope = new expeditor.SimpleScope(); - * scope.loadFromTreeJson(treeJson, functions); // Enable validation - */ - var SimpleScope = expeditor.SimpleScope = expeditor.Class.extend({ - init: function () { - this.variables = {}; - this.functions = {}; - this.varsByType = {}; // Index variables by type for findVarByType - this.validationEnabled = false; - }, - - /** - * Load components and functions from treeJson - * This enables validation mode - * - * @param {Object} treeJson - Form tree JSON from transform-form.js - * @param {Array} functions - Array of function definitions (optional) - */ - loadFromTreeJson: function (treeJson, functions) { - var self = this; - this.variables = {}; - this.functions = {}; - this.varsByType = {}; - - // Track displayNames for isDuplicate detection (mirrors TreeProcessor.js) - var displayNameMap = {}; - - // Traverse treeJson to extract all components - function traverse(node, displayPath, parent) { - if (!node) return; - - var nodeId = node.id || ''; - var nodeName = node.name || ''; - var displayName = node.displayName || nodeName; - - if (nodeId) { - // Check for duplicate displayNames (mirrors TreeProcessor.js) - var isDuplicate = false; - if (displayNameMap[displayName]) { - isDuplicate = true; - // Mark the original as duplicate too - var originalId = displayNameMap[displayName]; - if (self.variables[originalId]) { - self.variables[originalId].element.isDuplicate = true; - } - } else { - displayNameMap[displayName] = nodeId; - } - - // Build metadata object (mirrors TreeProcessor.js behavior) - var metadata = {}; - if (node.isAncestorRepeatable !== undefined) { - metadata.isAncestorRepeatable = node.isAncestorRepeatable; - } - if (node.isFragment !== undefined) { - metadata.isFragment = node.isFragment; - } - if (node.qualifiedName !== undefined) { - metadata.qualifiedName = node.qualifiedName; - } - if (node.fieldType !== undefined) { - metadata.fieldType = node.fieldType; - } - - // Build props object (mirrors VariableDefinition structure) - var props = {}; - if (node.options) { - props.options = node.options; - } - - var element = { - id: nodeId, - name: nodeName, - displayName: displayName, - type: node.type || 'STRING', - displayPath: displayPath, - parent: parent ? parent.id : '', - fieldType: node.fieldType || '', - isDuplicate: isDuplicate, - metadata: metadata, - props: props - }; - - var varEntry = { element: element, foundId: nodeId, props: props }; - self.variables[nodeId] = varEntry; - - // Index by type for findVarByType (mirrors RBScope behavior) - var types = (node.type || 'STRING').split('|'); - types.forEach(function (t) { - var trimmedType = t.trim(); - if (!self.varsByType[trimmedType]) { - self.varsByType[trimmedType] = []; - } - self.varsByType[trimmedType].push(varEntry); - }); - - // Also index by name for easier lookup - if (nodeName && nodeName !== nodeId) { - self.variables[nodeName] = varEntry; - } - } - - // Traverse children - var items = node.items || []; - if (Array.isArray(items)) { - items.forEach(function (item) { - var childDisplayPath = displayPath + (item.displayName || item.name || '') + '/'; - traverse(item, childDisplayPath, node); - }); - } - } - - traverse(treeJson, 'FORM/', null); - - // For fragments, add $globalForm variable to allow referencing parent form - // This mirrors the behavior in RBScope.addVars and ExpressionEditorUtil.js - // isFragment can be at root level (from ExpressionEditorTree) or in metadata (from AEM authoring) - var isFragment = treeJson.isFragment || (treeJson.metadata && treeJson.metadata.isFragment); - if (isFragment) { - // Update $form to have FRAGMENT name/displayName (matches AEM behavior) - if (self.variables['$form']) { - self.variables['$form'].element.name = 'FRAGMENT'; - self.variables['$form'].element.displayName = 'FRAGMENT'; - self.variables['$form'].element.metadata = self.variables['$form'].element.metadata || {}; - self.variables['$form'].element.metadata.isFragment = true; - } - - // Add $globalForm to reference the actual parent form - var globalFormEntry = { - element: { - id: '$globalForm', - name: 'FORM', - displayName: 'FORM', - type: 'FORM', - displayPath: 'FORM/', - fieldType: 'form', - metadata: {}, - props: {} - }, - foundId: '$globalForm', - props: {} - }; - self.variables['$globalForm'] = globalFormEntry; - - // Also add to varsByType for FORM - if (!self.varsByType['FORM']) { - self.varsByType['FORM'] = []; - } - self.varsByType['FORM'].push(globalFormEntry); - } - - // Load functions - if (functions && Array.isArray(functions)) { - functions.forEach(function (func) { - var funcId = func.id || ''; - if (funcId) { - self.functions[funcId] = { element: func }; - // Also index by displayName - var displayName = func.displayName || ''; - if (displayName) { - self.functions[displayName.toLowerCase()] = { element: func }; - } - } - }); - } - - this.validationEnabled = true; - return this; - }, - - /** - * Register a variable by ID (manual registration) - */ - registerVar: function (id, element) { - this.variables[id] = { element: element, foundId: id }; - }, - - /** - * Register a function by ID (manual registration) - */ - registerFunction: function (id, element) { - this.functions[id] = { element: element }; - }, - - /** - * Find variables by type - * Returns array of { element, foundId, props } entries - * Mirrors RBScope.findVarByType - */ - findVarByType: function (types) { - if (!types || types.length === 0) { - return []; - } - - var typesArray = types.split('|'); - if (typesArray.indexOf('ANY') > -1) { - // Return all variables - return Object.values(this.variables); - } - - var result = []; - var idsAdded = {}; - var self = this; - - typesArray.forEach(function (type) { - var trimmedType = type.trim(); - var vars = self.varsByType[trimmedType] || []; - vars.forEach(function (varEntry) { - var id = varEntry.foundId; - if (!idsAdded[id]) { - idsAdded[id] = true; - result.push(varEntry); - } - }); - }); - - return result; - }, - - /** - * Find a variable by ID - * Returns { element, foundId } or null - * - * In validation mode: returns null if component not found - * In synthetic mode: returns synthetic element from ID - */ - findVarById: function (id) { - // First check registered variables - if (this.variables[id]) { - return this.variables[id]; - } - - // In validation mode, return null for missing components - if (this.validationEnabled) { - return null; - } - - // Synthetic mode: return synthetic element from ID - var name = id.split('.').pop(); - return { - element: { id: id, name: name, displayName: name }, - foundId: id - }; - }, - - /** - * Find a function by ID - * Returns { element } or null - */ - findFunctionById: function (id) { - // Check registered functions - if (this.functions[id]) { - return this.functions[id]; - } - - // Try lowercase lookup - var lowerKey = (id || '').toLowerCase(); - if (this.functions[lowerKey]) { - return this.functions[lowerKey]; - } - - // In validation mode, return null for missing functions - if (this.validationEnabled) { - return null; - } - - // Synthetic mode: return synthetic function definition - return { - element: { id: id, displayName: id } - }; - }, - - /** - * Check if a component exists - */ - hasVariable: function (id) { - return this.variables.hasOwnProperty(id); - }, - - /** - * Check if a function exists - */ - hasFunction: function (id) { - return this.functions.hasOwnProperty(id) || - this.functions.hasOwnProperty((id || '').toLowerCase()); - }, - - /** - * Get all registered variable IDs - */ - getAllVariableIds: function () { - return Object.keys(this.variables); - }, - - /** - * Get all registered function IDs - */ - getAllFunctionIds: function () { - return Object.keys(this.functions); - }, - - /** - * Check if validation mode is enabled - */ - isValidationEnabled: function () { - return this.validationEnabled; - } - }); - - /** - * SimpleContext - creates models from JSON using grammar configuration - * - * Uses grammar's node_type field to determine model classes, with - * JSON structure detection as fallback for backward compatibility. - */ - var SimpleContext = expeditor.SimpleContext = expeditor.Class.extend({ - init: function () { - this.config = {}; - this.scope = new SimpleScope(); - this.grammar = null; // Will hold the grammar config (annotated_subset_grammar.json) - }, - - /** - * Set the grammar configuration - * @param {Object} grammar - Grammar object (e.g., annotated_subset_grammar.json) - */ - setGrammar: function (grammar) { - this.grammar = grammar; - return this; - }, - - /** - * Get the grammar configuration - */ - getGrammar: function () { - return this.grammar; - }, - - setScope: function (scope) { - this.scope = scope; - }, - - getScope: function () { - return this.scope; - }, - - getConfig: function (nodeName) { - // Return minimal config - the model type is determined by _getModelClass - return { - impl: { - model: 'expeditor.model.SequenceModel' // default - } - }; - }, - - /** - * Resolve model class name to actual class - * @param {string} modelName - Model name (e.g., 'ChoiceModel') - * @returns {Function} Model class constructor - */ - _resolveModelClass: function (modelName) { - var modelClass = expeditor.model[modelName]; - if (!modelClass) { - // Fallback to TerminalModel if class not found - return expeditor.model.TerminalModel; - } - return modelClass; - }, - - /** - * Determine the model class to use based on nodeName and JSON structure - * - * Resolution order: - * 1. Special models (ROOT, CONDITION, SCRIPTMODEL, RULES) - * 2. Grammar's node_type field - * 3. JSON structure fallback (choice/items/value) - * 4. Default to TerminalModel - */ - _getModelClass: function (nodeName, jsonObj) { - // 1. Check special models first (these extend base models) - if (SPECIAL_MODELS.hasOwnProperty(nodeName)) { - return this._resolveModelClass(SPECIAL_MODELS[nodeName]); - } - - // 2. Use grammar's node_type if available - if (this.grammar && this.grammar[nodeName]) { - var entry = this.grammar[nodeName]; - if (entry.node_type && NODE_TYPE_TO_MODEL[entry.node_type]) { - return this._resolveModelClass(NODE_TYPE_TO_MODEL[entry.node_type]); - } - } - - // 3. Fallback: Determine from JSON structure - if (jsonObj) { - if (jsonObj.hasOwnProperty('choice')) { - return expeditor.model.ChoiceModel; - } - if (jsonObj.hasOwnProperty('items')) { - return expeditor.model.SequenceModel; - } - if (jsonObj.hasOwnProperty('value')) { - return expeditor.model.TerminalModel; - } - } - - // 4. Default to TerminalModel for unknown nodes - return expeditor.model.TerminalModel; - }, - - /** - * Create a model for the given nodeName - * This is called by ModelFactory.fromJson - */ - createModel: function (nodeName, componentConfig, jsonObj) { - var ModelClass = this._getModelClass(nodeName, jsonObj); - return new ModelClass(nodeName, this); - } - }); - - // Override ModelFactory.fromJson to pass jsonObj to context - var originalFromJson = expeditor.Utils.ModelFactory.fromJson; - expeditor.Utils.ModelFactory.fromJson = function (json, ctx) { - if (ctx instanceof SimpleContext) { - // For SimpleContext, pass the json to help determine model type - var model = ctx.createModel(json.nodeName, null, json).fromJson(json); - return model; - } - return originalFromJson.call(this, json, ctx); - }; - -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/globals.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/globals.js deleted file mode 100644 index 38ef3f79..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/globals.js +++ /dev/null @@ -1,286 +0,0 @@ -/** - * Mock browser globals required by exp-editor and af-exp-editor JS files - * - * This file sets up the global namespace and mocks that allow the AEM Forms - * JavaScript code to run in a Node.js environment. - */ - -'use strict'; - -// Create global window object -global.window = global; -global.self = global; - -// Mock document (minimal) -global.document = { - createElement: () => ({}), - createTextNode: () => ({}), - querySelector: () => null, - querySelectorAll: () => [], - getElementById: () => null, - body: {} -}; - -// Known feature toggles - all enabled for full functionality -// Extracted from vendor JS files via: grep -r "Granite.Toggles.isEnabled\|FT_FORMS" vendor/ -const ENABLED_FEATURE_TOGGLES = [ - // ExpressionEditorTree.js - 'FT_FORMS-14303', - 'FT_FORMS-16466', - 'FT_FORMS-17789', - // ToSummaryTransformer.js - 'FT_FORMS-13519', - // FunctionsConfigV2.js - 'FT_FORMS-13209', - 'FT_FORMS-19884', - 'FT_FORMS-20002', - 'FT_FORMS-20129', - // RuntimeUtil.js - 'FT_FORMS-19582', - // AFJSONFormulaTransformer.js - 'FT_FORMS-19810', // RETRY_REQUEST_HANDLER_FT - 'FT_FORMS-17090', - 'FT_FORMS-21266', - 'FT_FORMS-21359', - 'FT_FORMS-13193', - 'FT_FORMS-21264', - 'FT_FORMS-19581', - // Via guidelib.author.ConfigUpdater - 'FT_FORMS_11581', - 'FT_FORMS_11584', - 'FT_FORMS_9611', - 'FT_FORMS_15407', -]; - -// Track which toggles are checked (for debugging) -const checkedToggles = new Set(); - -// Mock Granite (AEM's client-side framework) -global.Granite = { - Toggles: { - isEnabled: (featureFlag) => { - // Track checked toggles - checkedToggles.add(featureFlag); - // All feature flags return true for full functionality - return true; - }, - // Utility to see which toggles were checked - getCheckedToggles: () => Array.from(checkedToggles), - // List of known toggles - KNOWN_TOGGLES: ENABLED_FEATURE_TOGGLES - }, - I18n: { - get: (key) => key, - getVar: (key) => key // Same as get, returns key as-is - }, - HTTP: { - handleError: () => {} - } -}; - -// Create expeditor namespace (exp-editor base) -global.expeditor = { - rb: { - FeatureToggles: { - isCommComposerChannel: () => false, // Default to AF (not COMM_COMPOSER) - isHighlightBrokenRulesInSummaryViewEnabled: () => false - }, - customFunctionParser: null // Will be set when parser is loaded - }, - Utils: {}, - model: {}, // Model classes will be added here - Class: null // Will be set by jquery_oops.js -}; - -// Create af namespace (af-exp-editor) -global.af = { - expeditor: { - author: { - ExpressionEditorTree: null // Will be set when loaded - } - } -}; - -// Create guidelib namespace (AEM Forms) -global.guidelib = { - author: { - ConfigUpdater: { - FT_FORMS_11581: 'FT_FORMS_11581', - FT_FORMS_11584: 'FT_FORMS_11584', - FT_FORMS_9611: 'FT_FORMS_9611', - FT_FORMS_15407: 'FT_FORMS_15407' - }, - FunctionsConfig_v2: null, // Will be loaded from JSON - AFJSONFormulaTransformer: null, - ToSummaryTransformer: null, - AFJSONFormulaMerger: null - }, - // RuntimeUtil will be populated from RuntimeUtil.js, but we set defaults here - RuntimeUtil: null // Will be set by RuntimeUtil.js -}; - -// Pre-initialize RuntimeUtil with event mappings (will be overwritten by RuntimeUtil.js) -// This ensures these properties exist even if RuntimeUtil.js fails to load -global.guidelib.RuntimeUtil = { - bindRefToAFNameMap: null, - SCRIPT_INDENT: ' ', - DEFAULT_EVENT: 'Value Commit', - // Event name to trigger event mapping - eventToEventName: { - 'is changed': 'Value Commit', - 'is clicked': 'Click', - 'is initialised': 'Initialize', - 'is initialized': 'Initialize' - }, - // Inverse mapping - eventNameToEvent: { - 'Value Commit': 'is changed', - 'Click': 'is clicked', - 'Initialize': 'is initialised' - }, - // fd:events property names - SECURE_EVENT_PROPERTY_MAPPING: { - 'Calculate': 'fd:calc', - 'Visibility': 'fd:visible', - 'Initialize': 'fd:init', - 'Click': 'fd:click', - 'Value Commit': 'fd:valueCommit', - 'Enabled': 'fd:enabled', - 'Validate': 'fd:validate' - }, - // Get event from condition (used by transformer) - getEventFromCondition: function(condition) { - return null; // Default - let transformer handle it - }, - setCurrentEventField: function(condition) { - return null; - }, - isConditionOnlyAnEvent: function(condition) { - return false; - } -}; - -// Mock jQuery (minimal - for code that uses $() syntax) -const mockjQuery = function(selector) { - return { - find: () => mockjQuery(), - each: () => mockjQuery(), - attr: () => '', - val: () => '', - text: () => '', - html: () => '', - on: () => mockjQuery(), - off: () => mockjQuery(), - trigger: () => mockjQuery(), - proxy: (fn, context) => fn.bind(context), - extend: Object.assign, - isArray: Array.isArray, - isFunction: (fn) => typeof fn === 'function', - isPlainObject: (obj) => obj && typeof obj === 'object' && obj.constructor === Object, - map: (arr, fn) => arr.map(fn), - each: (obj, fn) => { - if (Array.isArray(obj)) { - obj.forEach((item, i) => fn(i, item)); - } else { - Object.keys(obj).forEach(key => fn(key, obj[key])); - } - } - }; -}; - -mockjQuery.extend = Object.assign; -mockjQuery.isArray = Array.isArray; -mockjQuery.isFunction = (fn) => typeof fn === 'function'; -mockjQuery.isPlainObject = (obj) => obj && typeof obj === 'object' && obj.constructor === Object; -mockjQuery.map = (arr, fn) => arr.map(fn); -mockjQuery.each = (obj, fn) => { - if (Array.isArray(obj)) { - obj.forEach((item, i) => fn(i, item)); - } else { - Object.keys(obj).forEach(key => fn(key, obj[key])); - } -}; -mockjQuery.proxy = (fn, context) => fn.bind(context); -mockjQuery.Deferred = () => { - let resolve, reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { - resolve: (val) => { resolve(val); return promise; }, - reject: (err) => { reject(err); return promise; }, - promise: () => promise - }; -}; - -global.jQuery = global.$ = mockjQuery; - -// Mock lodash if not available -if (typeof global._ === 'undefined') { - try { - global._ = require('lodash'); - } catch (e) { - // Minimal lodash mock - global._ = { - isUndefined: (val) => val === undefined, - isNull: (val) => val === null, - isEmpty: (val) => { - if (val == null) return true; - if (Array.isArray(val) || typeof val === 'string') return val.length === 0; - return Object.keys(val).length === 0; - }, - get: (obj, path, defaultVal) => { - const keys = path.split('.'); - let result = obj; - for (const key of keys) { - if (result == null) return defaultVal; - result = result[key]; - } - return result === undefined ? defaultVal : result; - }, - set: (obj, path, value) => { - const keys = path.split('.'); - let current = obj; - for (let i = 0; i < keys.length - 1; i++) { - if (!(keys[i] in current)) current[keys[i]] = {}; - current = current[keys[i]]; - } - current[keys[keys.length - 1]] = value; - return obj; - }, - extend: Object.assign, - merge: (target, ...sources) => { - sources.forEach(source => { - Object.keys(source || {}).forEach(key => { - if (typeof source[key] === 'object' && source[key] !== null) { - target[key] = target[key] || {}; - global._.merge(target[key], source[key]); - } else { - target[key] = source[key]; - } - }); - }); - return target; - } - }; - } -} - -// Create fd namespace (AEM Forms client library namespace) -// fd._ is lodash used by AF transformers -global.fd = { - _: global._ // Reference to lodash -}; - -// Console debug - can be controlled via environment variable -if (process.env.DEBUG !== 'true') { - console.debug = () => {}; -} - -module.exports = { - expeditor: global.expeditor, - af: global.af, - guidelib: global.guidelib, - Granite: global.Granite -}; diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/loader.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/loader.js deleted file mode 100644 index 85c6f3a1..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/setup/loader.js +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Load JavaScript files from local vendor directory - * - * This loader makes the AEM Forms JavaScript code available in a Node.js environment - * for use by CLI scripts. All files are loaded from the local vendor/ directory - * for complete independence from external repositories. - */ - -'use strict'; - -const path = require('path'); -const fs = require('fs'); - -// Base paths for the source files (LOCAL VENDOR DIRECTORY) -// __dirname is tools/rule_coder/bridge/setup -const VENDOR_BASE = path.resolve(__dirname, '../vendor'); -const AF_EXP_EDITOR_BASE = path.join(VENDOR_BASE, 'af-exp-editor'); -const EXP_EDITOR_BASE = path.join(VENDOR_BASE, 'exp-editor'); - -// Grammar path (tools/rule_coder/grammar/) -const GRAMMAR_BASE = path.resolve(__dirname, '../../grammar'); - -/** - * Load a JavaScript file and execute it - * @param {string} filePath - Path to the JS file - * @param {boolean} silent - If true, don't log warnings for missing files - */ -function loadFile(filePath, silent = false) { - if (!fs.existsSync(filePath)) { - if (!silent) { - console.error(`Warning: File not found: ${filePath}`); - } - return false; - } - const code = fs.readFileSync(filePath, 'utf-8'); - try { - // Execute the code in global context - const vm = require('vm'); - vm.runInThisContext(code, { filename: filePath }); - return true; - } catch (e) { - if (!silent) { - console.error(`Error loading ${filePath}:`, e.message); - } - return false; - } -} - -/** - * Load ExpressionEditorTree.js for form transformation - * This sets up af.expeditor.author.ExpressionEditorTree - */ -function loadExpressionEditorTree() { - // Load the ExpressionEditorTree.js file from local vendor - const expressionEditorTreePath = path.join(AF_EXP_EDITOR_BASE, 'authoring/ExpressionEditorTree.js'); - loadFile(expressionEditorTreePath); -} - -/** - * Load the custom function parser - * This sets up expeditor.rb.customFunctionParser - */ -function loadCustomFunctionParser() { - const parserPath = path.join(AF_EXP_EDITOR_BASE, 'custom-function-parser/custom-function-parser.js'); - - if (!fs.existsSync(parserPath)) { - console.error('Warning: Custom function parser not found at:', parserPath); - return; - } - - // The bundled parser is a UMD module that will detect the global context - try { - const parserCode = fs.readFileSync(parserPath, 'utf-8'); - const vm = require('vm'); - - // Create a context with module.exports support for UMD detection - const script = new vm.Script(parserCode, { filename: parserPath }); - script.runInThisContext(); - - // The parser should now be available on expeditor.rb.customFunctionParser - if (!expeditor.rb.customFunctionParser) { - // If not set by the module, check if it's exported globally - if (typeof customFunctionParser !== 'undefined') { - expeditor.rb.customFunctionParser = customFunctionParser; - } - } - } catch (e) { - console.error('Error loading custom function parser:', e.message); - } -} - -/** - * Load FunctionsConfigV2 (OOTB functions) - */ -function loadFunctionsConfig() { - const functionsConfigPath = path.join(AF_EXP_EDITOR_BASE, 'runtime/FunctionsConfigV2.js'); - loadFile(functionsConfigPath); -} - -/** - * Load all required files for transformation - */ -function loadForTransform() { - loadExpressionEditorTree(); -} - -/** - * Load all required files for function parsing - */ -function loadForParseFunctions() { - loadCustomFunctionParser(); -} - -/** - * Load functions configuration (OOTB functions) - */ -function loadForFunctionsConfig() { - loadFunctionsConfig(); -} - -/** - * Load RuntimeUtil.js for transformer utilities - */ -function loadRuntimeUtil() { - const runtimeUtilPath = path.join(AF_EXP_EDITOR_BASE, 'runtime/RuntimeUtil.js'); - loadFile(runtimeUtilPath); -} - -/** - * Load exp-editor core files in dependency order - * These are required for model classes and transformers - * Files are loaded from the local vendor/exp-editor directory - */ -function loadExpEditorCore() { - const files = [ - // Core namespace and utilities (flattened in vendor/) - 'namespace.js', - 'jquery_oops.js', - 'utils.js', - // Model classes (in vendor/exp-editor/model/) - // Order matters! Base classes must be loaded before subclasses. - 'model/BaseModel.js', // Base class for all models - 'model/TerminalModel.js', // extends BaseModel - 'model/SequenceModel.js', // extends BaseModel - 'model/ListModel.js', // extends BaseModel - 'model/ChoiceModel.js', // extends BaseModel - 'model/RootModel.js', // extends SequenceModel (must come after) - 'model/ScriptModel.js', // extends BaseModel - 'model/FunctionModel.js', // extends SequenceModel - 'model/ConditionModel.js', // extends ChoiceModel (must come after) - // Core transformer classes (in vendor/exp-editor/core/) - 'core/BaseTransformer.js', - 'core/ToJsonFormulaTransformer.js', - 'core/ToSummaryTransformer.js', - 'core/RBScope.js' - ]; - - files.forEach(file => { - const filePath = path.join(EXP_EDITOR_BASE, file); - loadFile(filePath, true); // silent=true, these are optional - }); -} - -/** - * Load AF-specific transformer files - */ -function loadAFTransformers() { - // Load RuntimeUtil first (has dependencies) - loadRuntimeUtil(); - - // Load AF transformers from local vendor - const transformerPath = path.join(AF_EXP_EDITOR_BASE, 'runtime/AFJSONFormulaTransformer.js'); - loadFile(transformerPath); - - const mergerPath = path.join(AF_EXP_EDITOR_BASE, 'runtime/AFJSONFormulaMerger.js'); - loadFile(mergerPath); - - const summaryPath = path.join(AF_EXP_EDITOR_BASE, 'authoring/ToSummaryTransformer.js'); - loadFile(summaryPath, true); -} - -/** - * Load SimpleContext for CLI transformation - * This provides a minimal context that can create models without full grammar - */ -function loadSimpleContext() { - const contextPath = path.join(__dirname, 'SimpleContext.js'); - loadFile(contextPath); -} - -/** - * Load all files needed for rule transformation - * This includes exp-editor core, RuntimeUtil, AF transformers, and SimpleContext - */ -function loadForRuleTransform() { - loadExpEditorCore(); - loadSimpleContext(); // Load after models but before transformers - loadAFTransformers(); -} - -/** - * Load ContextLoader for managing FormContext in CLI tools - */ -function loadContextLoader() { - const contextLoaderPath = path.join(__dirname, 'ContextLoader.js'); - loadFile(contextLoaderPath); -} - -/** - * Load the annotated subset grammar for model class resolution - * This grammar provides node_type annotations used by SimpleContext._getModelClass - * - * @returns {Object|null} The grammar object or null if not found - */ -function loadGrammar() { - const grammarPath = path.join(GRAMMAR_BASE, 'annotated_subset_grammar.json'); - - if (!fs.existsSync(grammarPath)) { - console.error('Warning: Grammar file not found at:', grammarPath); - return null; - } - - try { - const content = fs.readFileSync(grammarPath, 'utf-8'); - const grammar = JSON.parse(content); - - // Make grammar available globally - if (typeof global !== 'undefined') { - global.AnnotatedGrammar = grammar; - } - - return grammar; - } catch (e) { - console.error('Error loading grammar:', e.message); - return null; - } -} - -/** - * Create a SimpleContext with grammar loaded - * This is a convenience function for CLI tools - * - * @returns {expeditor.SimpleContext} Context with grammar set - */ -function createSimpleContextWithGrammar() { - const grammar = loadGrammar(); - const ctx = new expeditor.SimpleContext(); - - if (grammar) { - ctx.setGrammar(grammar); - } - - return ctx; -} - -module.exports = { - loadFile, - loadExpressionEditorTree, - loadCustomFunctionParser, - loadFunctionsConfig, - loadForTransform, - loadForParseFunctions, - loadForFunctionsConfig, - loadRuntimeUtil, - loadExpEditorCore, - loadSimpleContext, - loadAFTransformers, - loadForRuleTransform, - loadContextLoader, - loadGrammar, - createSimpleContextWithGrammar, - // Export paths for direct access - AF_EXP_EDITOR_BASE, - EXP_EDITOR_BASE, - VENDOR_BASE, - GRAMMAR_BASE -}; diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/VERSION.md b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/VERSION.md deleted file mode 100644 index 907a98d5..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/VERSION.md +++ /dev/null @@ -1,108 +0,0 @@ -# Vendor Files Version Tracking - -Track which versions of `exp-editor` and `af-exp-editor` the rule_coder tool is synced with. - ---- - -## Current Sync Point - -| Repository | Branch | Commit | Date | -|----------------|--------|------------|------------| -| exp-editor | master | `0e5ef7b` | 2026-01-07 | -| af-exp-editor | master | `c8229f6` | 2026-01-07 | - -**Full Commit Hashes:** -- exp-editor: `0e5ef7b2163797ea7ab40298ec1d4228da04d74c` -- af-exp-editor: `c8229f6b3cf32ac9a3b90fb80b3922cae6f27ee4` - ---- - -## Vendored Files - -### From exp-editor - -Source: `rule-builder/src/main/` - -| Category | Source Path | Vendor Path | -|----------|-------------|-------------| -| **Base** | `resources/libs/fd/expeditor/clientlibs/base/js/namespace.js` | `exp-editor/namespace.js` | -| | `resources/libs/fd/expeditor/clientlibs/base/js/jquery_oops.js` | `exp-editor/jquery_oops.js` | -| | `resources/libs/fd/expeditor/clientlibs/base/js/utils.js` | `exp-editor/utils.js` | -| **Model** | `javascript/rulebuilder/model/BaseModel.js` | `exp-editor/model/BaseModel.js` | -| | `javascript/rulebuilder/model/TerminalModel.js` | `exp-editor/model/TerminalModel.js` | -| | `javascript/rulebuilder/model/ListModel.js` | `exp-editor/model/ListModel.js` | -| | `javascript/rulebuilder/model/ChoiceModel.js` | `exp-editor/model/ChoiceModel.js` | -| | `javascript/rulebuilder/model/RootModel.js` | `exp-editor/model/RootModel.js` | -| | `javascript/rulebuilder/model/ScriptModel.js` | `exp-editor/model/ScriptModel.js` | -| | `javascript/rulebuilder/model/SequenceModel.js` | `exp-editor/model/SequenceModel.js` | -| | `javascript/rulebuilder/model/FunctionModel.js` | `exp-editor/model/FunctionModel.js` | -| | `javascript/rulebuilder/model/ConditionModel.js` | `exp-editor/model/ConditionModel.js` | -| **Core** | `javascript/rulebuilder/core/BaseTransformer.js` | `exp-editor/core/BaseTransformer.js` | -| | `javascript/rulebuilder/core/ToJsonFormulaTransformer.js` | `exp-editor/core/ToJsonFormulaTransformer.js` | -| | `javascript/rulebuilder/core/ToSummaryTransformer.js` | `exp-editor/core/ToSummaryTransformer.js` | -| | `javascript/rulebuilder/core/RBScope.js` | `exp-editor/core/RBScope.js` | - -### From af-exp-editor - -Source: `content/src/main/content/jcr_root/libs/fd/af-expeditor/clientlibs/` - -| Category | Source Path | Vendor Path | -|----------|-------------|-------------| -| **Authoring** | `authoring/js/ExpressionEditorTree.js` | `af-exp-editor/authoring/ExpressionEditorTree.js` | -| | `authoring/js/ToSummaryTransformer.js` | `af-exp-editor/authoring/ToSummaryTransformer.js` | -| **Runtime** | `runtime/js/RuntimeUtil.js` | `af-exp-editor/runtime/RuntimeUtil.js` | -| | `runtime/js/AFJSONFormulaTransformer.js` | `af-exp-editor/runtime/AFJSONFormulaTransformer.js` | -| | `runtime/js/AFJSONFormulaMerger.js` | `af-exp-editor/runtime/AFJSONFormulaMerger.js` | -| | `runtime/js/FunctionsConfigV2.js` | `af-exp-editor/runtime/FunctionsConfigV2.js` | -| **Parser** | `custom-function-parser/js/custom-function-parser.js` | `af-exp-editor/custom-function-parser/custom-function-parser.js` | - -**Total: 23 files** (16 from exp-editor, 7 from af-exp-editor) - ---- - -## Check for Updates - -```bash -# exp-editor changes since last sync -cd <path-to-exp-editor> -git log --oneline 0e5ef7b..HEAD -- rule-builder/src/main/ - -# af-exp-editor changes since last sync -cd <path-to-af-exp-editor> -git log --oneline c8229f6..HEAD -- content/src/main/content/jcr_root/libs/fd/af-expeditor/clientlibs/ -``` - -To see which files changed: -```bash -# exp-editor -git diff --name-only 0e5ef7b..HEAD -- rule-builder/src/main/ - -# af-exp-editor -git diff --name-only c8229f6..HEAD -- content/src/main/content/jcr_root/libs/fd/af-expeditor/clientlibs/ -``` - ---- - -## Update Workflow - -1. Run the check commands above -2. Review changed files for impact -3. Copy updated files to vendor directory -4. Test CLI tools: - ```bash - cd tools/rule_coder/bridge - node cli/summary.js <test-rule.json> - node cli/generate-formula.js <test-rule.json> - ``` -5. Update this file with new commit hashes -6. Add entry to changelog below - ---- - -## Changelog - -| Date | Action | Details | -|------------|--------|---------| -| 2025-01-13 | Initial | Vendored base + model files | -| 2025-01-15 | Added | Core transformers (BaseTransformer, ToJsonFormulaTransformer, ToSummaryTransformer, RBScope) | -| 2025-01-15 | Updated | Switched to master branch commits | diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/authoring/ExpressionEditorTree.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/authoring/ExpressionEditorTree.js deleted file mode 100644 index ffd9311c..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/authoring/ExpressionEditorTree.js +++ /dev/null @@ -1,463 +0,0 @@ -/************************************************************************* - * ADOBE CONFIDENTIAL - * ___________________ - * - * Copyright 2022 Adobe - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Adobe and its suppliers, if any. The intellectual - * and technical concepts contained herein are proprietary to Adobe - * and its suppliers and are protected by all applicable intellectual - * property laws, including trade secret and copyright laws. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Adobe. - **************************************************************************/ - -(function () { - /** - * Each node in the tree must have the following properties - * id - * path - * name - * type - * displayName - * qualifiedName (SOM for AF 1) - * - * For backward compatibilty, the node should have the following properties - * status - * resourceType - * isFragment - */ - var ExpressionEditorTree = af.expeditor.author.ExpressionEditorTree = { - - - /** - * Converts the form json to exp-editor tree json - * @param {object} formJson - The input form JSON - * @returns {object|null} exp-editor tree json or null - */ - transformJson: function(formJson) { - if(!expeditor.rb.FeatureToggles.isCommComposerChannel()){ - return ExpressionEditorTree._getTreeJson("", "object", false, false)(formJson); - } - // Initial transformation for the main form structure - // Note: _getTreeJson returns a function, which is then immediately called with formJson - const baseTree = ExpressionEditorTree._getTreeJson("", "object", false, false)(formJson); - - // If source is COMM_COMPOSER, process DOR template items as well - if (expeditor.rb.FeatureToggles.isCommComposerChannel() && baseTree) { - // Safely access the nested template container - const templateContainer = formJson?.properties?.["fd:dor"]?.pageTemplate?.template?.[':items']; - const panelKey = Object.keys(templateContainer ?? {})?.[0]; - const panel = templateContainer?.[panelKey]; - - console.log(panel); - - if (panel && (panel[':items'] || panel.items)) { // Check if template has items - try { - const templateTree = ExpressionEditorTree._filterTemplateTree(ExpressionEditorTree._getTreeJson("", "object", false, false)(panel)); - console.debug("templateTree", templateTree); - - // Merge templateNodes into the base tree's items - if (templateTree.items.length > 0) { - // Initialize items array if it doesn't exist - if (!baseTree.items) { - baseTree.items = []; - } - - // Concatenate the processed template nodes - baseTree.items = [...templateTree.items, ...baseTree.items]; - } - } catch (e) { - // Log error and return the base tree (or handle error differently) - console.error("ExpressionEditorTree: Error processing DOR template items.", e); - } - } - - // Add data models to tree so they're included in scope, but mark them for filtering from tree display - const dataDescriptions = formJson?.properties?.["fd:dor"]?.pageTemplate?.datasets?.dataDescriptions; - if (dataDescriptions) { - try { - // Extract the template item name to prepend to data model IDs - const templateItems = formJson?.properties?.["fd:dor"]?.pageTemplate?.template?.[':items']; - let templateItemName = null; - - if (templateItems) { - const firstItemKey = Object.keys(templateItems)[0]; - templateItemName = templateItems[firstItemKey]?.name; - console.debug("DEBUG: Template item name =", templateItemName); - } - - const dataModelItems = ExpressionEditorTree._parseDataModelsAsTreeItems(dataDescriptions, templateItemName); - if (dataModelItems.length > 0) { - if (!baseTree.dataModelItems) { - baseTree.dataModelItems = []; - } - // Add data models to dataModelItems (stored separately from regular items) - baseTree.dataModelItems = [...baseTree.dataModelItems, ...dataModelItems]; - } - } catch (e) { - console.error("ExpressionEditorTree: Error processing data models.", e); - } - } - } - - return baseTree; - }, - - _filterTemplateTree : function (tree) { - if (!tree.items || !Array.isArray(tree.items)) { - return tree; - } - - tree.items = tree.items - .filter(item => item.path !== undefined && item.path !== null) - .map(item => ExpressionEditorTree._filterTemplateTree(item)); // Recursively filter nested items - - return tree; - }, - - _parseDataModelsAsTreeItems: function(dataDescriptions, templateItemName) { - const models = JSON.parse(dataDescriptions); - const items = []; - models.forEach(model => { - if (model.dataConnection) { - const modelItems = ExpressionEditorTree._flattenDataModelToTree(model.dataConnection, templateItemName); - items.push(...modelItems); - } - }); - return items; - }, - - _flattenDataModelToTree: function(node, templateItemName = null) { - const items = []; - if (node.key && node.datapath !== undefined) { - // Build ID with template name prefix if provided - let itemId = node.datapath || ('/' + node.key); - - if (templateItemName) { - itemId = `${templateItemName}${itemId}`; - } - const item = { - id: itemId, - name: node.key, - displayName: node.title || node.key, - type: ExpressionEditorTree._mapDataModelType(node.type), - fieldType: 'data-model', - path: node.datapath || ('/' + node.key), - status: 'none', - }; - items.push(item); - } else { - console.log("DEBUG: Skipping node - condition failed. node.key =", node.key, "node.datapath =", node.datapath); - } - if (node.children && Array.isArray(node.children)) { - node.children.forEach(child => { - const childItems = ExpressionEditorTree._flattenDataModelToTree(child, templateItemName); - items.push(...childItems); - }); - } - return items; - }, - - _mapDataModelType: function(dataType) { - const typeMap = { - 'string': 'STRING', - 'number': 'NUMBER', - 'boolean': 'BOOLEAN', - 'object': 'OBJECT', - 'array': 'ARRAY' - }; - return typeMap[dataType?.toLowerCase()] || 'STRING'; - }, - - - _isSiteContainer : function(item) { - // for example, some custom components in AEM (like demo) is also returning items - return (':items' in item || 'items' in item) && !('fieldType' in item); - }, - - - _walkThroughContainer : function(parentId, container, isAncestorRepeatable) { - const oldItems = container.items instanceof Array ? container.items : []; - const cqItems = container[':items'] ? container[':items'] : {}; - const cqItemsOrder = container[':itemsOrder'] ? container[':itemsOrder'] : []; - const items = (oldItems.length > 0 ? oldItems : (cqItemsOrder.map(x => cqItems[x]))); - return items.flatMap(ExpressionEditorTree._getTreeJson(parentId, container.type, container.repeatable, isAncestorRepeatable || !!container.repeatable)) - .filter(i => i != null); - }, - - _sanitizeFieldName(name) { - // regex: name should start with a letter and have only [A-Za-z0-9_] else add quotes - const nameRegex = /^[A-Za-z][A-Za-z0-9_]*$/; - if (!nameRegex.test(name)) { - name = `"${name}"`; - } - return name; - }, - - _getTreeJson: (parentSOM, parentType, isParentRepeatable, isAncestorRepeatable) => (json, index) => { - if (json.hasOwnProperty("fieldType") || ExpressionEditorTree._isSiteContainer(json)) { - if (ExpressionEditorTree._isSiteContainer(json)) { - return ExpressionEditorTree._walkThroughContainer(parentSOM, json, isAncestorRepeatable).flat(); - } else { - const unnamed = json.name == null || json.name === ""; - let selfJson; - if (Granite.Toggles.isEnabled("FT_FORMS-14303")) { - selfJson = ExpressionEditorTree._getTreeJsonForNode(json, isAncestorRepeatable && !unnamed); - } else { - selfJson = ExpressionEditorTree._getTreeJsonForNode(json); - } - - if (parentSOM === "") { - if (Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_11581)) { - // form id is required to generate save form action so before replacing adding the same in options. - const originalFormId = { - 'originalId': selfJson.id - } - selfJson.options = {...selfJson.options, ...originalFormId}; - } - - if (Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_9611) || Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_15407)) { - var schemaInfo = ExpressionEditorTree._getSchemaInfo(json['properties']); - selfJson.options = { ...selfJson.options, ...schemaInfo }; - } - selfJson.id = "$form" - } else if (isParentRepeatable && !unnamed) { - if (Granite.Toggles.isEnabled('FT_FORMS-16466')) { - selfJson.id = parentSOM + "[getRelativeInstanceIndex(" + parentSOM + ")]" + "." + ExpressionEditorTree._sanitizeFieldName(selfJson.name); - } else { - selfJson.id = parentSOM + "[length(" + parentSOM + ") - 1]" + "." + ExpressionEditorTree._sanitizeFieldName(selfJson.name); - } - } else if (parentType !== "array" && !unnamed) { - selfJson.id = parentSOM + "." + ExpressionEditorTree._sanitizeFieldName(selfJson.name); - } else if (parentType === "array") { - selfJson.id = `${parentSOM}[${index}]` - } else if (unnamed) { - selfJson.id = parentSOM; - } - if (expeditor.rb.FeatureToggles.isCommComposerChannel()) { - selfJson.fieldId = json.id; - } - - if (expeditor.rb.FeatureToggles.isCommComposerChannel() && json.fieldType === "panel") { - const dorContainerItems = json?.properties?.["fd:dor"]?.dorContainer?.[":items"]; - if (dorContainerItems) { - try { - const processedItems = Object.values(dorContainerItems).map(item => - ExpressionEditorTree._getTreeJsonForNode(item, isAncestorRepeatable) - ); - selfJson.items = [...(selfJson.items || []), ...processedItems]; - return selfJson; - } catch (e) { - console.error("ExpressionEditorTree: Error processing dorcontainer items.", e); - } - } - } - - if (json.hasOwnProperty("fieldType") && (json.fieldType !== 'panel' && json.fieldType !== 'form' && json.fieldType !== 'pageset' && json.fieldType !== 'pagearea')) { - if (unnamed) { - //unnamed leaf elements are not visible in the tree - return null; - } - return selfJson - } else { - selfJson.items = ExpressionEditorTree._walkThroughContainer(selfJson.id, json, isAncestorRepeatable); - selfJson.isFragment = json.properties?.['fd:fragment'] || false; - return selfJson; - } - } - } - }, - - //TODO: Support all field types - _getExpEditorDataType: function(nodeJson, isAncestorRepeatable) { - var type = []; - - if(expeditor.rb.FeatureToggles.isCommComposerChannel() && nodeJson.fieldType && nodeJson.fieldType === 'radio-group') { - nodeJson.fieldType = 'panel'; - } - - var isField = function (fieldType) { - //pageset and pagearea are for communication composer template items - return (fieldType.length > 0 && - [ 'panel', 'form', 'image', 'plain-text', 'pageset', 'pagearea', 'contentarea'].indexOf(fieldType) === -1); - } - - var fieldTypeMapping = { - 'pageset' : ['PAGESET'], - 'pagearea' : ['PAGEAREA'], - 'text-input' : ["TEXT FIELD"], - 'number-input' : ["NUMBER FIELD"], - 'date-input' : ['DATE FIELD'], - 'file-input' : ['FILE ATTACHMENT', 'BINARY'], - 'drop-down' : ['DROPDOWN'], - 'radio-group' : ['RADIO BUTTON'], - 'checkbox-group' : ['CHECK BOX'], - 'plain-text' : ['STATIC TEXT', 'STRING'], - 'checkbox' : [], //todo: define a type - 'captcha' : [], - 'button' : ['BUTTON'], - 'image' : ['IMAGE', 'STRING'], - 'multiline-input' : ['TEXT FIELD'], - 'email' : ['TEXT FIELD'], - 'panel' : ['PANEL'], - 'form' : ['FORM'] - } - - if (nodeJson.hasOwnProperty("fieldType")) { - var fieldType = nodeJson.fieldType - if (fieldType === 'form') { - type.push('FORM') - } else { - type.push("AFCOMPONENT") - if (isField(fieldType)) { - type.push("FIELD") - } - if (fieldTypeMapping.hasOwnProperty(fieldType)) { - type = type.concat(fieldTypeMapping[fieldType]) - } else { - console.error("Unsupported fieldType " + fieldType) - } - switch (nodeJson.type) { - case 'number': - case 'integer': - type.push('NUMBER') - if (isAncestorRepeatable) { - type.push('NUMBER[]') - } - break; - case 'number[]': - case 'string[]': - case 'boolean[]': - case 'object': - case 'array': - type.push(nodeJson.type.toUpperCase()); - break; - case 'file': - type.push('FILE'); - break; - case 'file[]': - type.push('FILE[]'); - break; - case 'boolean': - type.push('BOOLEAN') - if (isAncestorRepeatable) { - type.push('BOOLEAN[]') - } - break; - case "string": - default: - if (nodeJson.format === "date") { - type.push('DATE'); - if (isAncestorRepeatable) { - type.push('DATE[]') - } - } else if (isField(fieldType) && nodeJson.fieldType !== 'button') { //hack to disable comparison operators in button - type.push('STRING'); - if (isAncestorRepeatable) { - type.push('STRING[]') - } - } - break; - } - } - } - return type.join("|"); - }, - - _getOptionsObject : function(nodeJson) { - const _enum = nodeJson.enum; - if (_enum && _enum.length > 0) { - const _enumNames = nodeJson.enumNames || _enum; - return { - options: Object.fromEntries( - _enum.map((x, i) => [x, i < _enumNames.length ? (!!_enumNames[i].value ? _enumNames[i].value : _enumNames[i]) : x]) - ) - }; - } - return {} - }, - - _hasEventsOrRules : function (nodeJson) { - const events = nodeJson.events || {} - const rules = nodeJson.rules || {} - const ootbEvents = Object.keys(events).filter(x => !x.startsWith("custom:")) - return Object.keys(ootbEvents).length > 0 || Object.keys(rules).length > 0 - }, - - _getExpEditorNodeName: function(nodeJson) { - if (expeditor.rb.FeatureToggles.isCommComposerChannel()) { - if (nodeJson.id === "$form" || nodeJson.fieldType === "form") { - return "FORM"; - } - - return nodeJson.name || nodeJson.id; - } - return nodeJson.name || "FORM"; - }, - - _getTreeJsonForNode: function(nodeJson, isAncestorRepeatable) { - let resultNode; - const icon = 'properties' in nodeJson && 'fd:icon' in nodeJson.properties ? - nodeJson.properties['fd:icon'] : undefined; - if (Granite.Toggles.isEnabled("FT_FORMS-14303")) { - resultNode = { - id: nodeJson.id || nodeJson.name || "$form", - name: this._getExpEditorNodeName(nodeJson), - displayName: nodeJson.label && nodeJson.label.value ? nodeJson.label.value : nodeJson.name || "FORM", - type: this._getExpEditorDataType(nodeJson, isAncestorRepeatable), - status: nodeJson.properties?.['fd:rules']?.validationStatus || "none", - path : nodeJson.properties?.['fd:path'], - ...(this._getOptionsObject(nodeJson)), - fieldType : nodeJson.fieldType, - adaptiveFormVersion: nodeJson.adaptiveform, - isAncestorRepeatable: isAncestorRepeatable, - icon - } - } else { - resultNode = { - id: nodeJson.id || nodeJson.name || "$form", - name: this._getExpEditorNodeName(nodeJson), - displayName: nodeJson.label && nodeJson.label.value ? nodeJson.label.value : nodeJson.name || "FORM", - type: this._getExpEditorDataType(nodeJson), - status: nodeJson.properties?.['fd:rules']?.validationStatus || "none", - path : nodeJson.properties?.['fd:path'], - ...(this._getOptionsObject(nodeJson)), - fieldType : nodeJson.fieldType, - adaptiveFormVersion: nodeJson.adaptiveform, - icon - } - } - - if (expeditor.rb.FeatureToggles.isCommComposerChannel()) { - const dorContainer = nodeJson.properties?.["fd:dor"]?.dorContainer; - resultNode.qualifiedName = dorContainer?.qualifiedName || nodeJson.id; - resultNode.templateLock = dorContainer?.policies?.contentLock?.enabled || false; - } - if (Granite.Toggles.isEnabled("FT_FORMS-17789")) { - resultNode.isDorEnabled = nodeJson.properties?.['fd:dor'] && nodeJson.properties?.['fd:dor']['dorType'] && nodeJson.properties?.['fd:dor']['dorType'] !== 'none' || false; - } - return resultNode; - }, - - _isEmpty: function (obj) { - return obj - && Object.keys(obj).length === 0 - && Object.getPrototypeOf(obj) === Object.prototype - }, - - _getSchemaInfo(propJson) { - // schema info is required for direct connector integrations - propJson = (propJson && typeof propJson === 'object') ? propJson : {}; - var schemaInfo = { - 'schemaRef': propJson['schemaRef'] || "", - 'schemaType': propJson['schemaType'] || "" - }; - return schemaInfo; - } - - } -})(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/authoring/ToSummaryTransformer.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/authoring/ToSummaryTransformer.js deleted file mode 100644 index d5338257..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/authoring/ToSummaryTransformer.js +++ /dev/null @@ -1,673 +0,0 @@ -/************************************************************************* -* ADOBE CONFIDENTIAL -* ___________________ -* -* Copyright 2015 Adobe Systems Incorporated -* All Rights Reserved. -* -* NOTICE: All information contained herein is, and remains -* the property of Adobe Systems Incorporated and its suppliers, -* if any. The intellectual and technical concepts contained -* herein are proprietary to Adobe Systems Incorporated and its -* suppliers and are protected by all applicable intellectual property -* laws, including trade secret and copyright laws. -* Dissemination of this information or reproduction of this material -* is strictly forbidden unless prior written permission is obtained -* from Adobe Systems Incorporated. -**************************************************************************/ -(function (guidelib, _) { - var ExpressionEditorUtil = guidelib.author.ExpressionEditorUtil, - RuntimeUtil = guidelib.RuntimeUtil, - ToSummaryTransformer = guidelib.author.ToSummaryTransformer = expeditor.ToSummaryTransformer.extend({ - init : function (ctx) { - this._super.apply(this, arguments); - }, - - _getFieldModel : function (condition) { - if (condition.choiceModel.nodeName == "EVENT_AND_COMPARISON") { - return condition.choiceModel.items[0]; - } else { - return this._getFieldModel(condition.choiceModel.items[0]); - } - }, - - enterROOT : function (model) { - this._super.apply(this, arguments); - var ruleType = model.ruleType, - description = model.description; - if (!_.isUndefined(ruleType) && ruleType === "formdatamodel") { - this._currentScriptContext().eventName = "Calculate"; - this._currentScriptContext().field = this.ctx.currentFieldId; - this._currentScriptContext().isProxyRule = true; - this.writeInfo(description); - } - }, - - enterEVENT_SCRIPTS : function (model) { - if (expeditor.rb.FeatureToggles.isCommComposerChannel()) { - if (model.items.length > 1 && model.items[0].choiceModel != null) { - this.writeLogicalOperator(" " + Granite.I18n.get("AND") + " "); - this.writeBreak(); - } - } else { - var condition = model.items[0]; - var conditionEvent = RuntimeUtil.getEventFromCondition(condition); - this.writeStatement(" " + Granite.I18n.get("WHEN") + " "); - this.writeBreak(); - if (conditionEvent) { - this._currentScriptContext().eventName = RuntimeUtil.eventToEventName[conditionEvent]; - } else { - this._currentScriptContext().eventName = "Value Commit"; - var field = this._getFieldModel(condition); - field.accept(this); - this.writeNormal(" " + Granite.I18n.get("is changed") + " "); - this.writeBreak(); - this.writeLogicalOperator(" " + Granite.I18n.get("AND") + " "); - this.writeBreak(); - } - condition.accept(this); - this.writeBreak(); - this.writeKeyword(" " + Granite.I18n.get("THEN") + " "); - this.writeBreak(); - model.items[2].accept(this); - - if (model.items.length > 4) { - this.writeKeyword(" " + Granite.I18n.get("ELSE") + " "); - this.writeBreak(); - model.items[4].accept(this); - } - return true; - } - }, - - enterEVENT_AND_COMPARISON : function (model) { - var field = model.ctx.currentFieldId; - this._currentScriptContext().field = field; - var operator = expeditor.Utils.getOrElse(model.items[1], 'choiceModel.nodeName', null); - if (operator && RuntimeUtil.eventToEventName.hasOwnProperty(operator)) { - model.items[0].accept(this); - this.writeNormal(" " + Granite.I18n.get(operator) + " "); - return true; - } - this.writeNormal(" ("); - if (ExpressionEditorUtil.unaryOperators.hasOwnProperty(operator)) { - model.items[0].accept(this); - model.items[1].accept(this); - return true; - } - }, - - exitEVENT_AND_COMPARISON : function (model) { - var operator = expeditor.Utils.getOrElse(model.items[1], 'choiceModel.nodeName', null); - if (!(operator && RuntimeUtil.eventToEventName.hasOwnProperty(operator))) { - this.writeNormal(") "); - } - }, - - enterBLOCK_STATEMENT : function (model) { - }, - - exitBLOCK_STATEMENT : function (model) { - this.writeBreak(); - }, - - enterWSDL_BLOCK_STATEMENT : function (model) {}, - - exitWSDL_BLOCK_STATEMENT : function (model) { - this.writeBreak(); - }, - - enterEVENT_CONDITION : function (model) { - if (model.nested) { - this.writeNormal(" ("); - } - }, - - exitEVENT_CONDITION : function (model) { - if (model.nested) { - this.writeNormal(") "); - } - }, - - enterPRIMITIVE_EXPRESSION : function (model) { - }, - - enterAFCOMPONENT : function (model) { - this._writeVariable(model); - }, - - enterPANEL : function (model) { - this._writeVariable(model); - }, - - enterCOMPONENT : function (model) { - this._writeVariable(model); - }, - - enterDATA_MODEL_EXPRESSION : function (model) { - var valObj = model.getValue(); - if (valObj && valObj.displayName) { - this.writeVariable(valObj.displayName); - } else if (valObj && valObj.name) { - this.writeVariable(valObj.name); - } else { - this.writeVariable("Unknown Data Model"); - } - }, - - enterEVENT : function (model) { - this.writeKeyword(model.getChoiceModel().nodeName); - }, - - enterThen : function (model) { - if (Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_11584) && !expeditor.rb.FeatureToggles.isCommComposerChannel()) { - // If condition is empty then do not show THEN - if (model?.show) { - this.writeBreak(); - this.writeStatement(" " + Granite.I18n.get("THEN") + " "); - this.writeBreak(); - } - } else { - this.writeBreak(); - this.writeStatement(" " + Granite.I18n.get("THEN") + " "); - this.writeBreak(); - } - }, - - enterHIDE_STATEMENT : function (model) { - this.writeNormal(" " + Granite.I18n.get("Hide") + " "); - }, - - enterSHOW_STATEMENT : function (model) { - this.writeNormal(" " + Granite.I18n.get("Show") + " "); - }, - - enterCONDITIONORALWAYS : function (model) { - if (model.getChoiceModel()) { - this.writeBreak(); - this.writeKeyword(" " + Granite.I18n.get("WHEN") + " "); - this.writeBreak(); - } - }, - - exitCONDITIONORALWAYS : function (model) { - if (model.getChoiceModel()) { - this.writeBreak(); - } - }, - - enterENABLE_STATEMENT : function (model) { - this.writeNormal(" " + Granite.I18n.get("Enable") + " "); - }, - - enterDISABLE_STATEMENT : function (model) { - this.writeNormal(" " + Granite.I18n.get("Disable") + " "); - }, - - enterACCESS_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Enable"; - this.writeStatement(" " + Granite.I18n.get("ENABLE") + " "); - this.writeBreak(); - }, - - exitACCESS_EXPRESSION : function (model) { - var condition = model.items[2]; - if (condition.choiceModel) { - this._enterELSE(); - this._enterDONOTHING_OR_ELSE(model.items[4]); - } - }, - - enterDISABLE_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Disable"; - this.writeStatement(" " + Granite.I18n.get("DISABLE") + " "); - this.writeBreak(); - }, - - exitDISABLE_EXPRESSION : function (model) { - var condition = model.items[2]; - if (condition.choiceModel) { - this._enterELSE(); - this._enterDONOTHING_OR_ELSE(model.items[4]); - } - }, - - enterCALC_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Calculate"; - this.writeStatement(" " + Granite.I18n.get("SET VALUE OF") + " "); - this.writeBreak(); - }, - - enterCLEAR_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Calculate"; - this.writeStatement(" " + Granite.I18n.get("CLEAR VALUE OF") + " "); - this.writeBreak(); - }, - - enterVALUE_COMMIT_EXPRESSION : function (model) { - this.writeStatement(" " + Granite.I18n.get("WHEN VALUE OF") + " "); - this.writeBreak(); - }, - - enterSUMMARY_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Summary"; - this.writeStatement(" " + Granite.I18n.get("SET SUMMARY OF") + " "); - this.writeBreak(); - }, - - enterNAVIGABLE_PANEL : function (model) { - this._writeVariable(model); - }, - - enterREPEATABLE_PANEL : function (model) { - this._writeVariable(model); - }, - - enterCOMPLETION_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Completion"; - this.writeStatement(" " + Granite.I18n.get("SET COMPLETE") + " "); - this.writeBreak(); - }, - - enterVALIDATE_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Validate"; - this.writeStatement(" " + Granite.I18n.get("VALIDATE") + " "); - this.writeBreak(); - }, - enterFORMAT_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Format"; - this.writeStatement(" " + Granite.I18n.get("FORMAT") + " "); - this.writeBreak(); - }, - - enterVISIBLE_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Hide"; - this.writeStatement(" " + Granite.I18n.get("HIDE") + " "); - this.writeBreak(); - }, - - _enterELSE : function (model) { - this.writeKeyword(" " + Granite.I18n.get("ELSE") + " "); - this.writeBreak(); - }, - - _enterDONOTHING_OR_ELSE : function (model) { - this.writeNormal(Granite.I18n.getVar(model.choiceModel.nodeName)); - }, - - exitVISIBLE_EXPRESSION : function (model) { - var condition = model.items[2]; - if (condition.choiceModel) { - this._enterELSE(); - this._enterDONOTHING_OR_ELSE(model.items[4]); - } - }, - - enterSHOW_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Show"; - this.writeStatement(" " + Granite.I18n.get("SHOW") + " "); - this.writeBreak(); - }, - - exitSHOW_EXPRESSION : function (model) { - var condition = model.items[2]; - if (condition.choiceModel) { - this._enterELSE(); - this._enterDONOTHING_OR_ELSE(model.items[4]); - } - }, - - enterUsing : function (model) { - this.writeBreak(); - this.writeNormal(" " + Granite.I18n.get("using") + " "); - }, - - enterExpression : function (model) { - this.writeNormal(" " + Granite.I18n.get("expression") + " "); - this.writeBreak(); - }, - - enterDROPDOWN : function (model) { - this.enterAFCOMPONENT(model); - }, - - enterOPTIONS_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this._currentScriptContext().eventName = "Options"; - this.writeStatement(" " + Granite.I18n.get("SET OPTIONS OF") + " "); - this.writeBreak(); - }, - - enterNAVIGATION_EXPRESSION : function (model) { - this._currentScriptContext().field = model.ctx.currentFieldId; - this._currentScriptContext().eventName = "Navigation"; - this.writeStatement(" " + Granite.I18n.get("ON NAVIGATION CHANGE") + " "); - this.writeBreak(); - }, - - enterTOOLBAR_BUTTON_OPTIONS : function (model) { - var option = model.choiceModel.nodeName; - this.writeKeyword(option + " "); - }, - - enterTOOLBAR_BUTTON : function (model) { - this.enterAFCOMPONENT(model); - }, - - enterSET_PROPERTY : function (model) { - this.writeNormal(Granite.I18n.get(" Set ")); - model.items[0].accept(this); - model.items[1].accept(this); - if (model.items[2].choiceModel.nodeName == "COMPARISON_EXPRESSION") { - this.writeLiteral(" " + Granite.I18n.get("TRUE") + " "); - this.writeKeyword(" " + Granite.I18n.get("WHEN") + " "); - } - model.items[2].accept(this); - return true; - }, - - enterCLEAR_VALUE_STATEMENT : function (model) { - this.writeNormal(" " + Granite.I18n.get("Clear value of") + " "); - }, - - enterSAVE_FORM : function (model) { - if (model.ctx.version === '2.0' && !Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_11581)) { - console.error("Save Form rule can not be modified. Please remove the rule or enable feature toggle."); - } - this.writeNormal(Granite.I18n.get("Save Form")); - }, - - enterSUBMIT_FORM : function (model) { - this.writeNormal(Granite.I18n.get("Submit Form")); - }, - - enterRESET_FORM : function (model) { - if (model.value && model.value.name) { - this.writeNormal(" " + Granite.I18n.get("Reset") + " "); - this._writeVariable(model); - } else { - this.writeNormal(" " + Granite.I18n.get("Reset Form") + " "); - } - }, - - enterVALIDATE_FORM : function (model) { - if (model.value && model.value.name) { - this.writeNormal(" " + Granite.I18n.get("Validate") + " "); - this._writeVariable(model); - } else { - this.writeNormal(" " + Granite.I18n.get("Validate Form") + " "); - } - - }, - - enterREPEATABLE_COMPONENT : function (model) { - this.enterCOMPONENT(model); - }, - - enterSET_FOCUS : function (model) { - this.writeNormal(Granite.I18n.get("Set Focus to") + " "); - }, - - enterNAVIGATE_IN_PANEL : function (model) { - this.writeNormal(Granite.I18n.get("Navigate in Panel") + " "); - }, - - enterPANEL_FOCUS_OPTION : function (model) { - this.writeNormal(Granite.I18n.get("and focus on") + " "); - var focusOptionType = model.choiceModel.nodeName === "NEXT_ITEM" ? Granite.I18n.get("Next Item") : Granite.I18n.get("Previous Item"); - this.writeVariable(focusOptionType); - this.writeNormal(" "+Granite.I18n.get("of")+ " "); - }, - - enterADD_INSTANCE : function (model) { - this.writeNormal(Granite.I18n.get("Add Instance of") + " "); - }, - - enterREMOVE_INSTANCE : function (model) { - this.writeNormal(Granite.I18n.get("Remove Instance of") + " "); - }, - - enterWSDL_OPTIONS_EXPRESSION : function (model) { - this.writeNormal(Granite.I18n.get(" Webservice Output: ")); - var val = model.getValue(); - if (val && val.wsdlInfo) { - //Different summary statement for normal and preconfigured WSDL - if (val.wsdlInfo.webServiceTitle == null) { - this.writeLiteral(val.wsdlInfo.wsdlEndPoint + " "); - this.writeBreak(); - this.writeNormal(Granite.I18n.get("Operation: ")); - this.writeLiteral(val.wsdlInfo.operationName); - } else { - //Preconfigured WSDL statement just shows the jcr:title for the service - this.writeLiteral(val.wsdlInfo.webServiceTitle); - } - } - }, - - enterWSDL_VALUE_EXPRESSION : function (model) { - this.enterWSDL_OPTIONS_EXPRESSION(model); - }, - getScript : function () { - var scriptCtx = this._currentScriptContext(); - var scriptObj = this._super.apply(this, arguments); - var fieldName = scriptCtx.field ? this._getDisplayName(scriptCtx.field) : this.undefinedFieldDisplayName; - var tooltipTitle = scriptCtx.field ? this._getDisplayName(scriptCtx.field, "displayName") : this.undefinedFieldDisplayName; - const isCommComposerChannelEnabled = expeditor?.rb?.FeatureToggles?.isCommComposerChannel?.() ?? false; - const eventNameDisplayText = !isCommComposerChannelEnabled ? ` - ${Granite.I18n.getVar(scriptCtx.eventName)}` : ''; - return $.extend(scriptObj, { - title: fieldName + eventNameDisplayText, - tooltipTitle: tooltipTitle + eventNameDisplayText - }); - }, - - enterNAVIGATE_TO : function (model) { - this.writeNormal(Granite.I18n.get("Navigate to URL") + " "); - }, - - enterNAVIGATE_METHOD_OPTIONS : function (model) { - this.writeNormal(Granite.I18n.get(" in") + " "); - var navigationType = model.choiceModel.nodeName; - var navigationSummary = navigationType === "SAME_TAB" ? "Same Tab" : navigationType === "NEW_TAB" ? "New Tab" : "New Window"; - this.writeVariable(Granite.I18n.get(navigationSummary)); - }, - - enterURL_LITERAL : function (model) { - this.writeLiteral("'" + model.getValue() + "'"); - }, - - enterCONCAT(model) { - if (this.ctx.version === "2.0") { - this.writeOperator(" " + Granite.I18n.get("&") + " "); - } - }, - - enterSTRING_LITERAL(model) { - if (model.getValue() != null) { - if (this.ctx.version === "2.0") { - this.writeLiteral("'" + model.getValue() + "'"); - } else { - this._super.apply(this, arguments) - } - } - }, - - enterEVENT_PAYLOAD(model) { - if (model && model.getValue() != null) { - this.writeLiteral("'" + model.getValue() + "'"); - } - }, - - enterDISPATCH_EVENT : function (model) { - this.writeLiteral(Granite.I18n.get("Dispatch") + " '"); - model.items[0].accept(this); - this.writeLiteral("' " + Granite.I18n.get("on") + " "); - if (model.items[2] && model.items[2].getValue()) { - model.items[2].accept(this); - } else { - this.writeLiteral(Granite.I18n.get("FORM")); - } - return true; - }, - - enterASYNC_FUNCTION_CALL: function (model) { - if (Granite.Toggles.isEnabled("FT_FORMS-13519")) { - var funcDef = model.getFunctionName(); - if (funcDef && funcDef.displayName) { - this.writeNormal(Granite.I18n.get("Wait for Function ")); - this.writeVariable(funcDef.displayName); - } - } - }, - - enterWSDL_STATEMENT: function (model) { - - var val = model.getValue(); - if (val && val.wsdlInfo) { - //Different summary statement for normal and preconfigured WSDL - if (val.wsdlInfo.wsdlEndPoint) { - this.writeNormal(" " + Granite.I18n.get("Invoke Webservice:") + " "); - if (val.wsdlInfo.webServiceTitle == null) { - this.writeLiteral(val.wsdlInfo.wsdlEndPoint + " "); - this.writeBreak(); - this.writeNormal(Granite.I18n.get("Operation:") + " "); - this.writeLiteral(val.wsdlInfo.operationName); - } else { - //Preconfigured WSDL statement just shows the jcr:title for the service - this.writeLiteral(val.wsdlInfo.webServiceTitle); - } - } else { - this.writeNormal(" " + Granite.I18n.get("Invoke Service:") + " "); - this.writeLiteral(val.wsdlInfo.operationTitle || val.wsdlInfo.operationName); - this.writeBreak(); - this.writeNormal(Granite.I18n.get(" of FormDataModel:") + " "); - this.writeLiteral(val.wsdlInfo.formDataModelId + " "); - } - } - }, - - enterIS_VALID : function (model) { - this.writeNormal(" " + Granite.I18n.get("is valid")); - }, - - enterIS_NOT_VALID : function (model) { - this.writeNormal(" " + Granite.I18n.get("is not valid")); - }, - - enterTRIGGER_EVENT_SCRIPTS : function (model) { - if (model.items.length > 1 && model.items[0].choiceModel != null) { - this.writeLogicalOperator(" " + Granite.I18n.get("AND") + " "); - model.items[0].choiceModel.accept(this); - this.writeBreak(); - } - this.writeKeyword(" " + Granite.I18n.get("THEN") + " "); - this.writeBreak(); - if (model.items[2]) { - model.items[2].accept(this); - } - if (model.items.length > 4) { - this.writeKeyword(" " + Granite.I18n.get("ELSE") + " "); - this.writeBreak(); - model.items[4].accept(this); - } - return true; - }, - - enterSINGLE_TRIGGER_SCRIPTS : function (model) { - this._currentScriptContext().field = model.ctx.currentFieldId - this.writeStatement(" " + Granite.I18n.get("WHEN") + " "); - this.writeBreak(); - }, - - enterTRIGGER_EVENT : function (model) { - var eventName; - if (expeditor.rb.FeatureToggles.isCommComposerChannel()) { - eventName = model.choiceModel.nodeName; - } else { - eventName = model.value; - } - if (RuntimeUtil.eventToEventName.hasOwnProperty(eventName)) { - eventName = RuntimeUtil.eventToEventName[eventName]; - } - if (eventName && eventName.startsWith('custom:')) { - eventName = eventName.replace('custom:', ''); - } - this._currentScriptContext().eventName = eventName; - this.writeNormal(" " + Granite.I18n.get(eventName) + " "); - this.writeBreak(); - }, - - enterUTM_PARAMETER : function (model) { - if (model.getValue()) { - this.write("UTM Parameter "); - this.writeNormal(model.getValue()); - } - }, - - enterQUERY_PARAMETER : function (model) { - if (model.getValue()) { - this.write("Query Parameter "); - this.writeNormal(model.getValue()); - } - }, - - enterBROWSER_DETAILS : function (model) { - if (model.getValue()) { - this.write("Browser Parameter "); - this.writeNormal(model.getValue()); - } - }, - - enterURL_DETAILS : function (model) { - if (model.getValue()) { - this.write("URL Parameter "); - this.writeNormal(model.getValue()); - } - }, - - enterGET_VARIABLE : function (model) { - var oldScript = this.script; - this.script = ""; - model.items[1].accept(this); - var variableName = this.script; - - this.script = ""; - model.items[3].accept(this); - var fieldId = this.script; - - this.script = oldScript; - - this.write("GetVariable " + variableName + " from " + fieldId); - return true; - }, - - enterSET_VARIABLE : function (model) { - var oldScript = this.script; - this.script = ""; - model.items[1].accept(this); - var variableName = this.script; - - this.script = ""; - model.items[3].accept(this); - var variableValue = this.script; - - this.script = ""; - model.items[5].accept(this); - var fieldId = this.script; - - this.script = oldScript; - - this.write("SetVariable " + variableName + " to " + variableValue + " on " + fieldId); - return true; - } - }); -})(guidelib, fd ? fd._ : _); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/custom-function-parser/custom-function-parser.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/custom-function-parser/custom-function-parser.js deleted file mode 100644 index 3e99fe92..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/custom-function-parser/custom-function-parser.js +++ /dev/null @@ -1,44 +0,0 @@ -/*! For license information please see custom-function-parser.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("expeditor",[],t):"object"==typeof exports?exports.expeditor=t():(e.expeditor=e.expeditor||{},e.expeditor.rb=e.expeditor.rb||{},e.expeditor.rb.customFunctionParser=t())}(this,(()=>(()=>{var e={41:(e,t,r)=>{"use strict";var n=r(655),s=r(8068),i=r(9675),a=r(5795);e.exports=function(e,t,r){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new i("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new i("`loose`, if provided, must be a boolean");var o=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,p=arguments.length>6&&arguments[6],u=!!a&&a(e,t);if(n)n(e,t,{configurable:null===c&&u?u.configurable:!c,enumerable:null===o&&u?u.enumerable:!o,value:r,writable:null===l&&u?u.writable:!l});else{if(!p&&(o||l||c))throw new s("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}}},76:e=>{"use strict";e.exports=Function.prototype.call},130:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"OptionValidator",{enumerable:!0,get:function(){return n.OptionValidator}}),Object.defineProperty(t,"findSuggestion",{enumerable:!0,get:function(){return s.findSuggestion}});var n=r(3380),s=r(8500)},228:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prettifyTargets=function(e){return Object.keys(e).reduce(((t,r)=>{let n=e[r];const a=s.unreleasedLabels[r];return"string"==typeof n&&a!==n&&(n=i(n)),t[r]=n,t}),{})},t.prettifyVersion=i;var n=r(5345),s=r(1884);function i(e){if("string"!=typeof e)return e;const{major:t,minor:r,patch:s}=n.parse(e),i=[t];return(r||s)&&i.push(r),s&&i.push(s),i.join(".")}},245:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.default)(e)};var n=r(5279)},259:e=>{"use strict";e.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},299:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.evaluate=function(){const e={confident:!0,deoptPath:null,seen:new Map};let t=c(this,e);return e.confident||(t=void 0),{confident:e.confident,deopt:e.deoptPath,value:t}},t.evaluateTruthy=function(){const e=this.evaluate();if(e.confident)return!!e.value};const n=["Number","String","Math"],s=["isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent",null,null],i=["random"];function a(e){return n.includes(e)}function o(e,t){t.confident&&(t.deoptPath=e,t.confident=!1)}const l=new Map([["undefined",void 0],["Infinity",1/0],["NaN",NaN]]);function c(e,t){const{node:n}=e,{seen:u}=t;if(u.has(n)){const r=u.get(n);return r.resolved?r.value:void o(e,t)}{const d={resolved:!1};u.set(n,d);const f=function(e,t){if(t.confident){if(e.isSequenceExpression()){const r=e.get("expressions");return c(r[r.length-1],t)}if(e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral())return e.node.value;if(e.isNullLiteral())return null;if(e.isTemplateLiteral())return p(e,e.node.quasis,t);if(e.isTaggedTemplateExpression()&&e.get("tag").isMemberExpression()){const r=e.get("tag.object"),{node:{name:n}}=r,s=e.get("tag.property");if(r.isIdentifier()&&"String"===n&&!e.scope.getBinding(n)&&s.isIdentifier()&&"raw"===s.node.name)return p(e,e.node.quasi.quasis,t,!0)}if(e.isConditionalExpression()){const r=c(e.get("test"),t);if(!t.confident)return;return c(r?e.get("consequent"):e.get("alternate"),t)}if(e.isExpressionWrapper())return c(e.get("expression"),t);if(e.isMemberExpression()&&!e.parentPath.isCallExpression({callee:e.node})){const r=e.get("property"),n=e.get("object");if(n.isLiteral()){const s=n.node.value,i=typeof s;let a=null;if(e.node.computed){if(a=c(r,t),!t.confident)return}else r.isIdentifier()&&(a=r.node.name);if(!("number"!==i&&"string"!==i||null==a||"number"!=typeof a&&"string"!=typeof a))return s[a]}}if(e.isReferencedIdentifier()){const r=e.scope.getBinding(e.node.name);if(r){if(r.constantViolations.length>0||e.node.start<r.path.node.end)return void o(r.path,t);if(r.hasValue)return r.value}const n=e.node.name;if(l.has(n))return r?void o(r.path,t):l.get(n);const s=e.resolve();return s===e?void o(e,t):c(s,t)}if(e.isUnaryExpression({prefix:!0})){if("void"===e.node.operator)return;const r=e.get("argument");if("typeof"===e.node.operator&&(r.isFunction()||r.isClass()))return"function";const n=c(r,t);if(!t.confident)return;switch(e.node.operator){case"!":return!n;case"+":return+n;case"-":return-n;case"~":return~n;case"typeof":return typeof n}}if(e.isArrayExpression()){const r=[],n=e.get("elements");for(const e of n){const n=e.evaluate();if(!n.confident)return void o(n.deopt,t);r.push(n.value)}return r}if(e.isObjectExpression()){const r={},n=e.get("properties");for(const e of n){if(e.isObjectMethod()||e.isSpreadElement())return void o(e,t);const n=e.get("key");let s;if(e.node.computed){if(s=n.evaluate(),!s.confident)return void o(s.deopt,t);s=s.value}else s=n.isIdentifier()?n.node.name:n.node.value;let i=e.get("value").evaluate();if(!i.confident)return void o(i.deopt,t);i=i.value,r[s]=i}return r}if(e.isLogicalExpression()){const r=t.confident,n=c(e.get("left"),t),s=t.confident;t.confident=r;const i=c(e.get("right"),t),a=t.confident;switch(e.node.operator){case"||":if(t.confident=s&&(!!n||a),!t.confident)return;return n||i;case"&&":if(t.confident=s&&(!n||a),!t.confident)return;return n&&i;case"??":if(t.confident=s&&(null!=n||a),!t.confident)return;return null!=n?n:i}}if(e.isBinaryExpression()){const r=c(e.get("left"),t);if(!t.confident)return;const n=c(e.get("right"),t);if(!t.confident)return;switch(e.node.operator){case"-":return r-n;case"+":return r+n;case"/":return r/n;case"*":return r*n;case"%":return r%n;case"**":return Math.pow(r,n);case"<":return r<n;case">":return r>n;case"<=":return r<=n;case">=":return r>=n;case"==":return r==n;case"!=":return r!=n;case"===":return r===n;case"!==":return r!==n;case"|":return r|n;case"&":return r&n;case"^":return r^n;case"<<":return r<<n;case">>":return r>>n;case">>>":return r>>>n}}if(e.isCallExpression()){const n=e.get("callee");let o,l;if(n.isIdentifier()&&!e.scope.getBinding(n.node.name)&&(a(n.node.name)||function(e){return s.includes(e)}(n.node.name))&&(l=r.g[n.node.name]),n.isMemberExpression()){const e=n.get("object"),t=n.get("property");if(e.isIdentifier()&&t.isIdentifier()&&a(e.node.name)&&!function(e){return i.includes(e)}(t.node.name)){o=r.g[e.node.name];const n=t.node.name;hasOwnProperty.call(o,n)&&(l=o[n])}if(e.isLiteral()&&t.isIdentifier()){const r=typeof e.node.value;"string"!==r&&"number"!==r||(o=e.node.value,l=o[t.node.name])}}if(l){const r=e.get("arguments").map((e=>c(e,t)));if(!t.confident)return;return l.apply(o,r)}}o(e,t)}}(e,t);return t.confident&&(d.resolved=!0,d.value=f),f}}function p(e,t,r,n=!1){let s="",i=0;const a=e.isTemplateLiteral()?e.get("expressions"):e.get("quasi.expressions");for(const e of t){if(!r.confident)break;s+=n?e.value.raw:e.value.cooked;const t=a[i++];t&&(s+=String(c(t,r)))}if(r.confident)return s}},322:(e,t,r)=>{"use strict";function n(){const e=r(4092);return n=function(){return e},e}function s(){const e=r(8992);return s=function(){return e},e}function i(){const e=r(2485);return i=function(){return e},e}function a(){const e=r(2352);return a=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t="global"){let r;const n={global:C,module:O,umd:I,var:N}[t];if(!n)throw new Error(`Unsupported output type ${t}`);return r=n(e),(0,s().default)(r).code};const{arrayExpression:o,assignmentExpression:l,binaryExpression:c,blockStatement:p,callExpression:u,cloneNode:d,conditionalExpression:f,exportNamedDeclaration:h,exportSpecifier:m,expressionStatement:y,functionExpression:g,identifier:b,memberExpression:v,objectExpression:T,program:x,stringLiteral:S,unaryExpression:E,variableDeclaration:P,variableDeclarator:A}=a(),w=e=>i().default.statement` - (function (root, factory) { - if (typeof define === "function" && define.amd) { - define(AMD_ARGUMENTS, factory); - } else if (typeof exports === "object") { - factory(COMMON_ARGUMENTS); - } else { - factory(BROWSER_ARGUMENTS); - } - })(UMD_ROOT, function (FACTORY_PARAMETERS) { - FACTORY_BODY - }); - `(e);function C(e){const t=b("babelHelpers"),r=[],n=g(null,[b("global")],p(r)),s=x([y(u(n,[f(c("===",E("typeof",b("global")),S("undefined")),b("self"),b("global"))]))]);return r.push(P("var",[A(t,l("=",v(b("global"),t),T([])))])),k(r,t,e),s}function O(e){const t=[],r=k(t,null,e);return t.unshift(h(null,Object.keys(r).map((e=>m(d(r[e]),b(e)))))),x(t,[],"module")}function I(e){const t=b("babelHelpers"),r=[];return r.push(P("var",[A(t,b("global"))])),k(r,t,e),x([w({FACTORY_PARAMETERS:b("global"),BROWSER_ARGUMENTS:l("=",v(b("root"),t),T([])),COMMON_ARGUMENTS:b("exports"),AMD_ARGUMENTS:o([S("exports")]),FACTORY_BODY:r,UMD_ROOT:b("this")})])}function N(e){const t=b("babelHelpers"),r=[];r.push(P("var",[A(t,T([]))]));const n=x(r);return k(r,t,e),r.push(y(t)),n}function k(e,t,r){const s=e=>t?v(t,b(e)):b(`_${e}`),i={};return n().list.forEach((function(a){if(r&&!r.includes(a))return;const o=i[a]=s(a),{nodes:c}=n().get(a,s,t?null:`_${a}`,[],t?(e,t,r)=>{r((e=>l("=",o,e))),e.body.push(y(l("=",o,b(t))))}:null);e.push(...c)})),i}},324:(e,t,r)=>{"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0}),t.getEnv=function(e="development"){return n.env.BABEL_ENV||"production"}},329:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=s;var n=r(8960);function s(e,t,r,i){const a=[].concat(e),o=Object.create(null);for(;a.length;){const e=a.shift();if(!e)continue;if(i&&((0,n.isAssignmentExpression)(e)||(0,n.isUnaryExpression)(e)||(0,n.isUpdateExpression)(e)))continue;if((0,n.isIdentifier)(e)){t?(o[e.name]=o[e.name]||[]).push(e):o[e.name]=e;continue}if((0,n.isExportDeclaration)(e)&&!(0,n.isExportAllDeclaration)(e)){(0,n.isDeclaration)(e.declaration)&&a.push(e.declaration);continue}if(r){if((0,n.isFunctionDeclaration)(e)){a.push(e.id);continue}if((0,n.isFunctionExpression)(e))continue}const l=s.keys[e.type];if(l)for(let t=0;t<l.length;t++){const r=e[l[t]];r&&(Array.isArray(r)?a.push(...r):a.push(r))}}return o}s.keys={DeclareClass:["id"],DeclareFunction:["id"],DeclareModule:["id"],DeclareVariable:["id"],DeclareInterface:["id"],DeclareTypeAlias:["id"],DeclareOpaqueType:["id"],InterfaceDeclaration:["id"],TypeAlias:["id"],OpaqueType:["id"],CatchClause:["param"],LabeledStatement:["label"],UnaryExpression:["argument"],AssignmentExpression:["left"],ImportSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportDefaultSpecifier:["local"],ImportDeclaration:["specifiers"],TSImportEqualsDeclaration:["id"],ExportSpecifier:["exported"],ExportNamespaceSpecifier:["exported"],ExportDefaultSpecifier:["exported"],FunctionDeclaration:["id","params"],FunctionExpression:["id","params"],ArrowFunctionExpression:["params"],ObjectMethod:["params"],ClassMethod:["params"],ClassPrivateMethod:["params"],ForInStatement:["left"],ForOfStatement:["left"],ClassDeclaration:["id"],ClassExpression:["id"],RestElement:["argument"],UpdateExpression:["argument"],ObjectProperty:["value"],AssignmentPattern:["left"],ArrayPattern:["elements"],ObjectPattern:["properties"],VariableDeclaration:["declarations"],VariableDeclarator:["id"]}},354:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if(!this.isReferenced())return;const t=this.scope.getBinding(e.name);return t?t.identifier.typeAnnotation?t.identifier.typeAnnotation:function(e,t,r){const n=[],i=[];let a=c(e,t,i);const o=u(e,t,r);if(o){const t=c(e,o.ifStatement);a=a.filter((e=>!t.includes(e))),n.push(o.typeAnnotation)}if(a.length){a.push(...i);for(const e of a)n.push(e.getTypeAnnotation())}if(n.length)return(0,s.createUnionType)(n)}(t,this,e.name):"undefined"===e.name?l():"NaN"===e.name||"Infinity"===e.name?o():void e.name};var n=r(2352),s=r(3141);const{BOOLEAN_NUMBER_BINARY_OPERATORS:i,createTypeAnnotationBasedOnTypeof:a,numberTypeAnnotation:o,voidTypeAnnotation:l}=n;function c(e,t,r){const n=e.constantViolations.slice();return n.unshift(e.path),n.filter((e=>{const n=(e=e.resolve())._guessExecutionStatusRelativeTo(t);return r&&"unknown"===n&&r.push(e),"before"===n}))}function p(e,t){const r=t.node.operator,n=t.get("right").resolve(),s=t.get("left").resolve();let l,c,p;if(s.isIdentifier({name:e})?l=n:n.isIdentifier({name:e})&&(l=s),l)return"==="===r?l.getTypeAnnotation():i.includes(r)?o():void 0;if("==="!==r&&"=="!==r)return;if(s.isUnaryExpression({operator:"typeof"})?(c=s,p=n):n.isUnaryExpression({operator:"typeof"})&&(c=n,p=s),!c)return;if(!c.get("argument").isIdentifier({name:e}))return;if(p=p.resolve(),!p.isLiteral())return;const u=p.node.value;return"string"==typeof u?a(u):void 0}function u(e,t,r){const n=function(e,t,r){let n;for(;n=t.parentPath;){if(n.isIfStatement()||n.isConditionalExpression()){if("test"===t.key)return;return n}if(n.isFunction()&&n.parentPath.scope.getBinding(r)!==e)return;t=n}}(e,t,r);if(!n)return;const i=[n.get("test")],a=[];for(let e=0;e<i.length;e++){const t=i[e];if(t.isLogicalExpression())"&&"===t.node.operator&&(i.push(t.get("left")),i.push(t.get("right")));else if(t.isBinaryExpression()){const e=p(r,t);e&&a.push(e)}}return a.length?{typeAnnotation:(0,s.createUnionType)(a),ifStatement:n}:u(e,n,r)}},414:e=>{"use strict";e.exports=Math.round},439:e=>{"use strict";e.exports=JSON.parse('{"transform-duplicate-named-capturing-groups-regex":{"chrome":"126","opera":"112","edge":"126","firefox":"129","safari":"17.4","node":"23","ios":"17.4","electron":"31.0"},"transform-regexp-modifiers":{"chrome":"125","opera":"111","edge":"125","firefox":"132","node":"23","electron":"31.0"},"transform-unicode-sets-regex":{"chrome":"112","opera":"98","edge":"112","firefox":"116","safari":"17","node":"20","deno":"1.32","ios":"17","opera_mobile":"75","electron":"24.0"},"bugfix/transform-v8-static-class-fields-redefine-readonly":{"chrome":"98","opera":"84","edge":"98","firefox":"75","safari":"15","node":"12","deno":"1.18","ios":"15","samsung":"11","opera_mobile":"52","electron":"17.0"},"bugfix/transform-firefox-class-in-computed-class-key":{"chrome":"74","opera":"62","edge":"79","safari":"16","node":"12","deno":"1","ios":"16","samsung":"11","opera_mobile":"53","electron":"6.0"},"bugfix/transform-safari-class-field-initializer-scope":{"chrome":"74","opera":"62","edge":"79","firefox":"69","safari":"16","node":"12","deno":"1","ios":"16","samsung":"11","opera_mobile":"53","electron":"6.0"},"transform-class-static-block":{"chrome":"94","opera":"80","edge":"94","firefox":"93","safari":"16.4","node":"16.11","deno":"1.14","ios":"16.4","samsung":"17","opera_mobile":"66","electron":"15.0"},"proposal-class-static-block":{"chrome":"94","opera":"80","edge":"94","firefox":"93","safari":"16.4","node":"16.11","deno":"1.14","ios":"16.4","samsung":"17","opera_mobile":"66","electron":"15.0"},"transform-private-property-in-object":{"chrome":"91","opera":"77","edge":"91","firefox":"90","safari":"15","node":"16.9","deno":"1.9","ios":"15","samsung":"16","opera_mobile":"64","electron":"13.0"},"proposal-private-property-in-object":{"chrome":"91","opera":"77","edge":"91","firefox":"90","safari":"15","node":"16.9","deno":"1.9","ios":"15","samsung":"16","opera_mobile":"64","electron":"13.0"},"transform-class-properties":{"chrome":"74","opera":"62","edge":"79","firefox":"90","safari":"14.1","node":"12","deno":"1","ios":"14.5","samsung":"11","opera_mobile":"53","electron":"6.0"},"proposal-class-properties":{"chrome":"74","opera":"62","edge":"79","firefox":"90","safari":"14.1","node":"12","deno":"1","ios":"14.5","samsung":"11","opera_mobile":"53","electron":"6.0"},"transform-private-methods":{"chrome":"84","opera":"70","edge":"84","firefox":"90","safari":"15","node":"14.6","deno":"1","ios":"15","samsung":"14","opera_mobile":"60","electron":"10.0"},"proposal-private-methods":{"chrome":"84","opera":"70","edge":"84","firefox":"90","safari":"15","node":"14.6","deno":"1","ios":"15","samsung":"14","opera_mobile":"60","electron":"10.0"},"transform-numeric-separator":{"chrome":"75","opera":"62","edge":"79","firefox":"70","safari":"13","node":"12.5","deno":"1","ios":"13","samsung":"11","rhino":"1.7.14","opera_mobile":"54","electron":"6.0"},"proposal-numeric-separator":{"chrome":"75","opera":"62","edge":"79","firefox":"70","safari":"13","node":"12.5","deno":"1","ios":"13","samsung":"11","rhino":"1.7.14","opera_mobile":"54","electron":"6.0"},"transform-logical-assignment-operators":{"chrome":"85","opera":"71","edge":"85","firefox":"79","safari":"14","node":"15","deno":"1.2","ios":"14","samsung":"14","opera_mobile":"60","electron":"10.0"},"proposal-logical-assignment-operators":{"chrome":"85","opera":"71","edge":"85","firefox":"79","safari":"14","node":"15","deno":"1.2","ios":"14","samsung":"14","opera_mobile":"60","electron":"10.0"},"transform-nullish-coalescing-operator":{"chrome":"80","opera":"67","edge":"80","firefox":"72","safari":"13.1","node":"14","deno":"1","ios":"13.4","samsung":"13","opera_mobile":"57","electron":"8.0"},"proposal-nullish-coalescing-operator":{"chrome":"80","opera":"67","edge":"80","firefox":"72","safari":"13.1","node":"14","deno":"1","ios":"13.4","samsung":"13","opera_mobile":"57","electron":"8.0"},"transform-optional-chaining":{"chrome":"91","opera":"77","edge":"91","firefox":"74","safari":"13.1","node":"16.9","deno":"1.9","ios":"13.4","samsung":"16","opera_mobile":"64","electron":"13.0"},"proposal-optional-chaining":{"chrome":"91","opera":"77","edge":"91","firefox":"74","safari":"13.1","node":"16.9","deno":"1.9","ios":"13.4","samsung":"16","opera_mobile":"64","electron":"13.0"},"transform-json-strings":{"chrome":"66","opera":"53","edge":"79","firefox":"62","safari":"12","node":"10","deno":"1","ios":"12","samsung":"9","rhino":"1.7.14","opera_mobile":"47","electron":"3.0"},"proposal-json-strings":{"chrome":"66","opera":"53","edge":"79","firefox":"62","safari":"12","node":"10","deno":"1","ios":"12","samsung":"9","rhino":"1.7.14","opera_mobile":"47","electron":"3.0"},"transform-optional-catch-binding":{"chrome":"66","opera":"53","edge":"79","firefox":"58","safari":"11.1","node":"10","deno":"1","ios":"11.3","samsung":"9","opera_mobile":"47","electron":"3.0"},"proposal-optional-catch-binding":{"chrome":"66","opera":"53","edge":"79","firefox":"58","safari":"11.1","node":"10","deno":"1","ios":"11.3","samsung":"9","opera_mobile":"47","electron":"3.0"},"transform-parameters":{"chrome":"49","opera":"36","edge":"18","firefox":"53","safari":"16.3","node":"6","deno":"1","ios":"16.3","samsung":"5","opera_mobile":"36","electron":"0.37"},"transform-async-generator-functions":{"chrome":"63","opera":"50","edge":"79","firefox":"57","safari":"12","node":"10","deno":"1","ios":"12","samsung":"8","opera_mobile":"46","electron":"3.0"},"proposal-async-generator-functions":{"chrome":"63","opera":"50","edge":"79","firefox":"57","safari":"12","node":"10","deno":"1","ios":"12","samsung":"8","opera_mobile":"46","electron":"3.0"},"transform-object-rest-spread":{"chrome":"60","opera":"47","edge":"79","firefox":"55","safari":"11.1","node":"8.3","deno":"1","ios":"11.3","samsung":"8","opera_mobile":"44","electron":"2.0"},"proposal-object-rest-spread":{"chrome":"60","opera":"47","edge":"79","firefox":"55","safari":"11.1","node":"8.3","deno":"1","ios":"11.3","samsung":"8","opera_mobile":"44","electron":"2.0"},"transform-dotall-regex":{"chrome":"62","opera":"49","edge":"79","firefox":"78","safari":"11.1","node":"8.10","deno":"1","ios":"11.3","samsung":"8","rhino":"1.7.15","opera_mobile":"46","electron":"3.0"},"transform-unicode-property-regex":{"chrome":"64","opera":"51","edge":"79","firefox":"78","safari":"11.1","node":"10","deno":"1","ios":"11.3","samsung":"9","opera_mobile":"47","electron":"3.0"},"proposal-unicode-property-regex":{"chrome":"64","opera":"51","edge":"79","firefox":"78","safari":"11.1","node":"10","deno":"1","ios":"11.3","samsung":"9","opera_mobile":"47","electron":"3.0"},"transform-named-capturing-groups-regex":{"chrome":"64","opera":"51","edge":"79","firefox":"78","safari":"11.1","node":"10","deno":"1","ios":"11.3","samsung":"9","opera_mobile":"47","electron":"3.0"},"transform-async-to-generator":{"chrome":"55","opera":"42","edge":"15","firefox":"52","safari":"11","node":"7.6","deno":"1","ios":"11","samsung":"6","opera_mobile":"42","electron":"1.6"},"transform-exponentiation-operator":{"chrome":"52","opera":"39","edge":"14","firefox":"52","safari":"10.1","node":"7","deno":"1","ios":"10.3","samsung":"6","rhino":"1.7.14","opera_mobile":"41","electron":"1.3"},"transform-template-literals":{"chrome":"41","opera":"28","edge":"13","firefox":"34","safari":"13","node":"4","deno":"1","ios":"13","samsung":"3.4","opera_mobile":"28","electron":"0.21"},"transform-literals":{"chrome":"44","opera":"31","edge":"12","firefox":"53","safari":"9","node":"4","deno":"1","ios":"9","samsung":"4","rhino":"1.7.15","opera_mobile":"32","electron":"0.30"},"transform-function-name":{"chrome":"51","opera":"38","edge":"79","firefox":"53","safari":"10","node":"6.5","deno":"1","ios":"10","samsung":"5","opera_mobile":"41","electron":"1.2"},"transform-arrow-functions":{"chrome":"47","opera":"34","edge":"13","firefox":"43","safari":"10","node":"6","deno":"1","ios":"10","samsung":"5","rhino":"1.7.13","opera_mobile":"34","electron":"0.36"},"transform-block-scoped-functions":{"chrome":"41","opera":"28","edge":"12","firefox":"46","safari":"10","node":"4","deno":"1","ie":"11","ios":"10","samsung":"3.4","opera_mobile":"28","electron":"0.21"},"transform-classes":{"chrome":"46","opera":"33","edge":"13","firefox":"45","safari":"10","node":"5","deno":"1","ios":"10","samsung":"5","opera_mobile":"33","electron":"0.36"},"transform-object-super":{"chrome":"46","opera":"33","edge":"13","firefox":"45","safari":"10","node":"5","deno":"1","ios":"10","samsung":"5","opera_mobile":"33","electron":"0.36"},"transform-shorthand-properties":{"chrome":"43","opera":"30","edge":"12","firefox":"33","safari":"9","node":"4","deno":"1","ios":"9","samsung":"4","rhino":"1.7.14","opera_mobile":"30","electron":"0.27"},"transform-duplicate-keys":{"chrome":"42","opera":"29","edge":"12","firefox":"34","safari":"9","node":"4","deno":"1","ios":"9","samsung":"3.4","opera_mobile":"29","electron":"0.25"},"transform-computed-properties":{"chrome":"44","opera":"31","edge":"12","firefox":"34","safari":"7.1","node":"4","deno":"1","ios":"8","samsung":"4","opera_mobile":"32","electron":"0.30"},"transform-for-of":{"chrome":"51","opera":"38","edge":"15","firefox":"53","safari":"10","node":"6.5","deno":"1","ios":"10","samsung":"5","opera_mobile":"41","electron":"1.2"},"transform-sticky-regex":{"chrome":"49","opera":"36","edge":"13","firefox":"3","safari":"10","node":"6","deno":"1","ios":"10","samsung":"5","rhino":"1.7.15","opera_mobile":"36","electron":"0.37"},"transform-unicode-escapes":{"chrome":"44","opera":"31","edge":"12","firefox":"53","safari":"9","node":"4","deno":"1","ios":"9","samsung":"4","rhino":"1.7.15","opera_mobile":"32","electron":"0.30"},"transform-unicode-regex":{"chrome":"50","opera":"37","edge":"13","firefox":"46","safari":"12","node":"6","deno":"1","ios":"12","samsung":"5","opera_mobile":"37","electron":"1.1"},"transform-spread":{"chrome":"46","opera":"33","edge":"13","firefox":"45","safari":"10","node":"5","deno":"1","ios":"10","samsung":"5","opera_mobile":"33","electron":"0.36"},"transform-destructuring":{"chrome":"51","opera":"38","edge":"15","firefox":"53","safari":"10","node":"6.5","deno":"1","ios":"10","samsung":"5","opera_mobile":"41","electron":"1.2"},"transform-block-scoping":{"chrome":"50","opera":"37","edge":"14","firefox":"53","safari":"11","node":"6","deno":"1","ios":"11","samsung":"5","opera_mobile":"37","electron":"1.1"},"transform-typeof-symbol":{"chrome":"48","opera":"35","edge":"12","firefox":"36","safari":"9","node":"6","deno":"1","ios":"9","samsung":"5","opera_mobile":"35","electron":"0.37"},"transform-new-target":{"chrome":"46","opera":"33","edge":"14","firefox":"41","safari":"10","node":"5","deno":"1","ios":"10","samsung":"5","opera_mobile":"33","electron":"0.36"},"transform-regenerator":{"chrome":"50","opera":"37","edge":"13","firefox":"53","safari":"10","node":"6","deno":"1","ios":"10","samsung":"5","opera_mobile":"37","electron":"1.1"},"transform-member-expression-literals":{"chrome":"7","opera":"12","edge":"12","firefox":"2","safari":"5.1","node":"0.4","deno":"1","ie":"9","android":"4","ios":"6","phantom":"1.9","samsung":"1","rhino":"1.7.13","opera_mobile":"12","electron":"0.20"},"transform-property-literals":{"chrome":"7","opera":"12","edge":"12","firefox":"2","safari":"5.1","node":"0.4","deno":"1","ie":"9","android":"4","ios":"6","phantom":"1.9","samsung":"1","rhino":"1.7.13","opera_mobile":"12","electron":"0.20"},"transform-reserved-words":{"chrome":"13","opera":"10.50","edge":"12","firefox":"2","safari":"3.1","node":"0.6","deno":"1","ie":"9","android":"4.4","ios":"6","phantom":"1.9","samsung":"1","rhino":"1.7.13","opera_mobile":"10.1","electron":"0.20"},"transform-export-namespace-from":{"chrome":"72","deno":"1.0","edge":"79","firefox":"80","node":"13.2","opera":"60","opera_mobile":"51","safari":"14.1","ios":"14.5","samsung":"11.0","android":"72","electron":"5.0"},"proposal-export-namespace-from":{"chrome":"72","deno":"1.0","edge":"79","firefox":"80","node":"13.2","opera":"60","opera_mobile":"51","safari":"14.1","ios":"14.5","samsung":"11.0","android":"72","electron":"5.0"}}')},453:(e,t,r)=>{"use strict";var n,s=r(9612),i=r(9383),a=r(1237),o=r(9290),l=r(9538),c=r(8068),p=r(9675),u=r(7726),d=r(1514),f=r(8968),h=r(6188),m=r(8002),y=r(5880),g=r(414),b=r(3093),v=Function,T=function(e){try{return v('"use strict"; return ('+e+").constructor;")()}catch(e){}},x=r(5795),S=r(655),E=function(){throw new p},P=x?function(){try{return E}catch(e){try{return x(arguments,"callee").get}catch(e){return E}}}():E,A=r(4039)(),w=r(3628),C=r(1064),O=r(8648),I=r(1002),N=r(76),k={},_="undefined"!=typeof Uint8Array&&w?w(Uint8Array):n,D={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":A&&w?w([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":k,"%AsyncGenerator%":k,"%AsyncGeneratorFunction%":k,"%AsyncIteratorPrototype%":k,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?n:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":"undefined"==typeof Float16Array?n:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":k,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":A&&w?w(w([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&A&&w?w((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":s,"%Object.getOwnPropertyDescriptor%":x,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":o,"%ReferenceError%":l,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&A&&w?w((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":A&&w?w(""[Symbol.iterator]()):n,"%Symbol%":A?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":P,"%TypedArray%":_,"%TypeError%":p,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":u,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet,"%Function.prototype.call%":N,"%Function.prototype.apply%":I,"%Object.defineProperty%":S,"%Object.getPrototypeOf%":C,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":h,"%Math.min%":m,"%Math.pow%":y,"%Math.round%":g,"%Math.sign%":b,"%Reflect.getPrototypeOf%":O};if(w)try{null.error}catch(e){var j=w(w(e));D["%Error.prototype%"]=j}var B=function e(t){var r;if("%AsyncFunction%"===t)r=T("async function () {}");else if("%GeneratorFunction%"===t)r=T("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=T("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var s=e("%AsyncGenerator%");s&&w&&(r=w(s.prototype))}return D[t]=r,r},M={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},L=r(6743),F=r(9957),R=L.call(N,Array.prototype.concat),U=L.call(I,Array.prototype.splice),V=L.call(N,String.prototype.replace),q=L.call(N,String.prototype.slice),W=L.call(N,RegExp.prototype.exec),K=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,$=/\\(\\)?/g,G=function(e,t){var r,n=e;if(F(M,n)&&(n="%"+(r=M[n])[0]+"%"),F(D,n)){var s=D[n];if(s===k&&(s=B(n)),void 0===s&&!t)throw new p("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:s}}throw new c("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new p("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new p('"allowMissing" argument must be a boolean');if(null===W(/^%?[^%]*%?$/,e))throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=q(e,0,1),r=q(e,-1);if("%"===t&&"%"!==r)throw new c("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new c("invalid intrinsic syntax, expected opening `%`");var n=[];return V(e,K,(function(e,t,r,s){n[n.length]=r?V(s,$,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",s=G("%"+n+"%",t),i=s.name,a=s.value,o=!1,l=s.alias;l&&(n=l[0],U(r,R([0,1],l)));for(var u=1,d=!0;u<r.length;u+=1){var f=r[u],h=q(f,0,1),m=q(f,-1);if(('"'===h||"'"===h||"`"===h||'"'===m||"'"===m||"`"===m)&&h!==m)throw new c("property names with quotes must have matching quotes");if("constructor"!==f&&d||(o=!0),F(D,i="%"+(n+="."+f)+"%"))a=D[i];else if(null!=a){if(!(f in a)){if(!t)throw new p("base intrinsic for "+e+" exists, but the property is not available.");return}if(x&&u+1>=r.length){var y=x(a,f);a=(d=!!y)&&"get"in y&&!("originalValue"in y.get)?y.get:a[f]}else d=F(a,f),a=a[f];d&&!o&&(D[i]=a)}}return a}},487:(e,t,r)=>{"use strict";var n=r(6897),s=r(655),i=r(3126),a=r(2205);e.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},s?s(e.exports,"apply",{value:a}):e.exports.apply=a},499:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.isVariableDeclaration)(e,{kind:"var"})&&!e[s.BLOCK_SCOPED_SYMBOL]};var n=r(8960),s=r(3422)},521:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BreakStatement=function(e){this.word("break"),u(this,e.label)},t.CatchClause=function(e){this.word("catch"),this.space(),e.param&&(this.tokenChar(40),this.print(e.param),this.print(e.param.typeAnnotation),this.tokenChar(41),this.space()),this.print(e.body)},t.ContinueStatement=function(e){this.word("continue"),u(this,e.label)},t.DebuggerStatement=function(){this.word("debugger"),this.semicolon()},t.DoWhileStatement=function(e){this.word("do"),this.space(),this.print(e.body),this.space(),this.word("while"),this.space(),this.tokenChar(40),this.print(e.test),this.tokenChar(41),this.semicolon()},t.ForOfStatement=t.ForInStatement=void 0,t.ForStatement=function(e){this.word("for"),this.space(),this.tokenChar(40);{const t=this.enterForStatementInit();this.tokenContext|=s.TokenContext.forHead,this.print(e.init),t()}this.tokenChar(59),e.test&&(this.space(),this.print(e.test)),this.token(";",!1,1),e.update&&(this.space(),this.print(e.update)),this.tokenChar(41),this.printBlock(e)},t.IfStatement=function(e){this.word("if"),this.space(),this.tokenChar(40),this.print(e.test),this.tokenChar(41),this.space();const t=e.alternate&&o(c(e.consequent));t&&(this.tokenChar(123),this.newline(),this.indent()),this.printAndIndentOnComments(e.consequent),t&&(this.dedent(),this.newline(),this.tokenChar(125)),e.alternate&&(this.endsWith(125)&&this.space(),this.word("else"),this.space(),this.printAndIndentOnComments(e.alternate))},t.LabeledStatement=function(e){this.print(e.label),this.tokenChar(58),this.space(),this.print(e.body)},t.ReturnStatement=function(e){this.word("return"),u(this,e.argument)},t.SwitchCase=function(e){e.test?(this.word("case"),this.space(),this.print(e.test),this.tokenChar(58)):(this.word("default"),this.tokenChar(58)),e.consequent.length&&(this.newline(),this.printSequence(e.consequent,!0))},t.SwitchStatement=function(e){this.word("switch"),this.space(),this.tokenChar(40),this.print(e.discriminant),this.tokenChar(41),this.space(),this.tokenChar(123),this.printSequence(e.cases,!0,void 0,(function(t,r){if(!t&&e.cases[e.cases.length-1]===r)return-1})),this.rightBrace(e)},t.ThrowStatement=function(e){this.word("throw"),u(this,e.argument)},t.TryStatement=function(e){this.word("try"),this.space(),this.print(e.block),this.space(),e.handlers?this.print(e.handlers[0]):this.print(e.handler),e.finalizer&&(this.space(),this.word("finally"),this.space(),this.print(e.finalizer))},t.VariableDeclaration=function(e,t){e.declare&&(this.word("declare"),this.space());const{kind:r}=e;"await using"===r?(this.word("await"),this.space(),this.word("using",!0)):this.word(r,"using"===r),this.space();let n=!1;if(!i(t))for(const t of e.declarations)t.init&&(n=!0);if(this.printList(e.declarations,void 0,void 0,e.declarations.length>1,n?function(e){this.token(",",!1,e),this.newline()}:void 0),i(t))if(a(t)){if(t.init===e)return}else if(t.left===e)return;this.semicolon()},t.VariableDeclarator=function(e){this.print(e.id),e.definite&&this.tokenChar(33),this.print(e.id.typeAnnotation),e.init&&(this.space(),this.tokenChar(61),this.space(),this.print(e.init))},t.WhileStatement=function(e){this.word("while"),this.space(),this.tokenChar(40),this.print(e.test),this.tokenChar(41),this.printBlock(e)},t.WithStatement=function(e){this.word("with"),this.space(),this.tokenChar(40),this.print(e.object),this.tokenChar(41),this.printBlock(e)};var n=r(2352),s=r(1373);const{isFor:i,isForStatement:a,isIfStatement:o,isStatement:l}=n;function c(e){const{body:t}=e;return!1===l(t)?e:c(t)}function p(e){this.word("for"),this.space();const t="ForOfStatement"===e.type;t&&e.await&&(this.word("await"),this.space()),this.noIndentInnerCommentsHere(),this.tokenChar(40);{const r=t?null:this.enterForStatementInit();this.tokenContext|=t?s.TokenContext.forOfHead:s.TokenContext.forInHead,this.print(e.left),null==r||r()}this.space(),this.word(t?"of":"in"),this.space(),this.print(e.right),this.tokenChar(41),this.printBlock(e)}function u(e,t){t&&(e.space(),e.printTerminatorless(t)),e.semicolon()}t.ForInStatement=p,t.ForOfStatement=p},537:(e,t,r)=>{var n=r(5606),s=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++)r[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return r},i=/%[sdj%]/g;t.format=function(e){if(!v(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(c(arguments[r]));return t.join(" ")}r=1;for(var n=arguments,s=n.length,a=String(e).replace(i,(function(e){if("%%"===e)return"%";if(r>=s)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),o=n[r];r<s;o=n[++r])g(o)||!S(o)?a+=" "+o:a+=" "+c(o);return a},t.deprecate=function(e,r){if(void 0!==n&&!0===n.noDeprecation)return e;if(void 0===n)return function(){return t.deprecate(e,r).apply(this,arguments)};var s=!1;return function(){if(!s){if(n.throwDeprecation)throw new Error(r);n.traceDeprecation?console.trace(r):console.error(r),s=!0}return e.apply(this,arguments)}};var a={},o=/^$/;if(n.env.NODE_DEBUG){var l=n.env.NODE_DEBUG;l=l.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),o=new RegExp("^"+l+"$","i")}function c(e,r){var n={seen:[],stylize:u};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),y(r)?n.showHidden=r:r&&t._extend(n,r),T(n.showHidden)&&(n.showHidden=!1),T(n.depth)&&(n.depth=2),T(n.colors)&&(n.colors=!1),T(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=p),d(n,e,n.depth)}function p(e,t){var r=c.styles[t];return r?"["+c.colors[r][0]+"m"+e+"["+c.colors[r][1]+"m":e}function u(e,t){return e}function d(e,r,n){if(e.customInspect&&r&&A(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var s=r.inspect(n,e);return v(s)||(s=d(e,s,n)),s}var i=function(e,t){if(T(t))return e.stylize("undefined","undefined");if(v(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return b(t)?e.stylize(""+t,"number"):y(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,r);if(i)return i;var a=Object.keys(r),o=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(r)),P(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(r);if(0===a.length){if(A(r)){var l=r.name?": "+r.name:"";return e.stylize("[Function"+l+"]","special")}if(x(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(E(r))return e.stylize(Date.prototype.toString.call(r),"date");if(P(r))return f(r)}var c,p="",u=!1,S=["{","}"];return m(r)&&(u=!0,S=["[","]"]),A(r)&&(p=" [Function"+(r.name?": "+r.name:"")+"]"),x(r)&&(p=" "+RegExp.prototype.toString.call(r)),E(r)&&(p=" "+Date.prototype.toUTCString.call(r)),P(r)&&(p=" "+f(r)),0!==a.length||u&&0!=r.length?n<0?x(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),c=u?function(e,t,r,n,s){for(var i=[],a=0,o=t.length;a<o;++a)I(t,String(a))?i.push(h(e,t,r,n,String(a),!0)):i.push("");return s.forEach((function(s){s.match(/^\d+$/)||i.push(h(e,t,r,n,s,!0))})),i}(e,r,n,o,a):a.map((function(t){return h(e,r,n,o,t,u)})),e.seen.pop(),function(e,t,r){return e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}(c,p,S)):S[0]+p+S[1]}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,r,n,s,i){var a,o,l;if((l=Object.getOwnPropertyDescriptor(t,s)||{value:t[s]}).get?o=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(o=e.stylize("[Setter]","special")),I(n,s)||(a="["+s+"]"),o||(e.seen.indexOf(l.value)<0?(o=g(r)?d(e,l.value,null):d(e,l.value,r-1)).indexOf("\n")>-1&&(o=i?o.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+o.split("\n").map((function(e){return" "+e})).join("\n")):o=e.stylize("[Circular]","special")),T(a)){if(i&&s.match(/^\d+$/))return o;(a=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.slice(1,-1),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+o}function m(e){return Array.isArray(e)}function y(e){return"boolean"==typeof e}function g(e){return null===e}function b(e){return"number"==typeof e}function v(e){return"string"==typeof e}function T(e){return void 0===e}function x(e){return S(e)&&"[object RegExp]"===w(e)}function S(e){return"object"==typeof e&&null!==e}function E(e){return S(e)&&"[object Date]"===w(e)}function P(e){return S(e)&&("[object Error]"===w(e)||e instanceof Error)}function A(e){return"function"==typeof e}function w(e){return Object.prototype.toString.call(e)}function C(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(e=e.toUpperCase(),!a[e])if(o.test(e)){var r=n.pid;a[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else a[e]=function(){};return a[e]},t.inspect=c,c.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},c.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.types=r(9032),t.isArray=m,t.isBoolean=y,t.isNull=g,t.isNullOrUndefined=function(e){return null==e},t.isNumber=b,t.isString=v,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=T,t.isRegExp=x,t.types.isRegExp=x,t.isObject=S,t.isDate=E,t.types.isDate=E,t.isError=P,t.types.isNativeError=P,t.isFunction=A,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(1135);var O=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,r;console.log("%s - %s",(r=[C((e=new Date).getHours()),C(e.getMinutes()),C(e.getSeconds())].join(":"),[e.getDate(),O[e.getMonth()],r].join(" ")),t.format.apply(t,arguments))},t.inherits=r(6698),t._extend=function(e,t){if(!t||!S(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var N="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function k(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(N&&e[N]){var t;if("function"!=typeof(t=e[N]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,N,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),s=[],i=0;i<arguments.length;i++)s.push(arguments[i]);s.push((function(e,n){e?r(e):t(n)}));try{e.apply(this,s)}catch(e){r(e)}return n}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),N&&Object.defineProperty(t,N,{value:t,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(t,s(e))},t.promisify.custom=N,t.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function t(){for(var t=[],r=0;r<arguments.length;r++)t.push(arguments[r]);var s=t.pop();if("function"!=typeof s)throw new TypeError("The last argument must be of type Function");var i=this,a=function(){return s.apply(i,arguments)};e.apply(this,t).then((function(e){n.nextTick(a.bind(null,null,e))}),(function(e){n.nextTick(k.bind(null,e,a))}))}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),Object.defineProperties(t,s(e)),t}},546:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BlockStatement=function(e){var t;this.tokenChar(123);const r=this.enterDelimited(),n=null==(t=e.directives)?void 0:t.length;if(n){var s;const t=e.body.length?2:1;this.printSequence(e.directives,!0,t),null!=(s=e.directives[n-1].trailingComments)&&s.length||this.newline(t)}this.printSequence(e.body,!0),r(),this.rightBrace(e)},t.Directive=function(e){this.print(e.value),this.semicolon()},t.DirectiveLiteral=function(e){const t=this.getPossibleRaw(e);if(!this.format.minified&&void 0!==t)return void this.token(t);const{value:s}=e;if(n.test(s)){if(r.test(s))throw new Error("Malformed AST: it is not possible to print a directive containing both unescaped single and double quotes.");this.token(`'${s}'`)}else this.token(`"${s}"`)},t.File=function(e){e.program&&this.print(e.program.interpreter),this.print(e.program)},t.InterpreterDirective=function(e){this.token(`#!${e.value}`),this.newline(1,!0)},t.Placeholder=function(e){this.token("%%"),this.print(e.name),this.token("%%"),"Statement"===e.expectedNode&&this.semicolon()},t.Program=function(e){var t;this.noIndentInnerCommentsHere(),this.printInnerComments();const r=null==(t=e.directives)?void 0:t.length;if(r){var n;const t=e.body.length?2:1;this.printSequence(e.directives,void 0,t),null!=(n=e.directives[r-1].trailingComments)&&n.length||this.newline(t)}this.printSequence(e.body)};const r=/(?:^|[^\\])(?:\\\\)*'/,n=/(?:^|[^\\])(?:\\\\)*"/},562:e=>{e.exports={A:"ie",B:"edge",C:"firefox",D:"chrome",E:"safari",F:"opera",G:"ios_saf",H:"op_mini",I:"android",J:"bb",K:"op_mob",L:"and_chr",M:"and_ff",N:"ie_mob",O:"and_uc",P:"samsung",Q:"and_qq",R:"baidu",S:"kaios"}},592:(e,t,r)=>{"use strict";var n=r(655),s=function(){return!!n};s.hasArrayLengthDefineBug=function(){if(!n)return null;try{return 1!==n([],"length",{value:1}).length}catch(e){return!0}},e.exports=s},640:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(null==e||!e.length)return;const r=[],s=(0,n.default)(e,r);if(s){for(const e of r)t.push(e);return s}};var n=r(4089)},655:e=>{"use strict";var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}e.exports=t},682:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ROOT_CONFIG_FILENAMES=void 0,t.findConfigUpwards=function(e){return null},t.findPackageData=function*(e){return{filepath:e,directories:[],pkg:null,isPackage:!1}},t.findRelativeConfig=function*(e,t,r){return{config:null,ignore:null}},t.findRootConfig=function*(e,t,r){return null},t.loadConfig=function*(e,t,r,n){throw new Error(`Cannot load ${e} relative to ${t} in a browser`)},t.loadPlugin=function(e,t){throw new Error(`Cannot load plugin ${e} relative to ${t} in a browser`)},t.loadPreset=function(e,t){throw new Error(`Cannot load preset ${e} relative to ${t} in a browser`)},t.resolvePlugin=function(e,t){return null},t.resolvePreset=function(e,t){return null},t.resolveShowConfigPath=function*(e){return null},t.ROOT_CONFIG_FILENAMES=[]},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,i,a=null;function o(...e){if(!o.enabled)return;const n=o,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";a++;const i=t.formatters[s];if("function"==typeof i){const t=e[a];r=i.call(n,t),e.splice(a,1),a--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=n,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(" ",",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(s(e,r))return!1;for(const r of t.names)if(s(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},786:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.transformFile=void 0,t.transformFileAsync=function(){return Promise.reject(new Error("Transforming files is not supported in browsers"))},t.transformFileSync=function(){throw new Error("Transforming files is not supported in browsers")},t.transformFile=function(e,t,r){"function"==typeof t&&(r=t),r(new Error("Transforming files is not supported in browsers"),null)}},826:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statements=t.statement=t.smart=t.program=t.expression=void 0;var n=r(2352);const{assertExpressionStatement:s}=n;function i(e){return{code:e=>`/* @babel/template */;\n${e}`,validate:()=>{},unwrap:t=>e(t.program.body.slice(1))}}t.smart=i((e=>e.length>1?e:e[0])),t.statements=i((e=>e)),t.statement=i((e=>{if(0===e.length)throw new Error("Found nothing to return.");if(e.length>1)throw new Error("Found multiple statements but wanted one");return e[0]}));const a=t.expression={code:e=>`(\n${e}\n)`,validate:e=>{if(e.program.body.length>1)throw new Error("Found multiple statements but wanted one");if(0===a.unwrap(e).start)throw new Error("Parse result included parens.")},unwrap:({program:e})=>{const[t]=e.body;return s(t),t.expression}};t.program={code:e=>e,validate:()=>{},unwrap:e=>e.program}},854:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._guessExecutionStatusRelativeTo=function(e){return g(this,e,new Map)},t._resolve=b,t.canHaveVariableDeclarationOrExpression=function(){return("init"===this.key||"left"===this.key)&&this.parentPath.isFor()},t.canSwapBetweenExpressionAndStatement=function(e){return!("body"!==this.key||!this.parentPath.isArrowFunctionExpression())&&(this.isExpression()?a(e):!!this.isBlockStatement()&&o(e))},t.getSource=function(){const e=this.node;if(e.end){const t=this.hub.getCode();if(t)return t.slice(e.start,e.end)}return""},t.isCompletionRecord=function(e){let t=this,r=!0;do{const{type:n,container:s}=t;if(!r&&(t.isFunction()||"StaticBlock"===n))return!!e;if(r=!1,Array.isArray(s)&&t.key!==s.length-1)return!1}while((t=t.parentPath)&&!t.isProgram()&&!t.isDoExpression());return!0},t.isConstantExpression=function(){if(this.isIdentifier()){const e=this.scope.getBinding(this.node.name);return!!e&&e.constant}if(this.isLiteral())return!this.isRegExpLiteral()&&(!this.isTemplateLiteral()||this.get("expressions").every((e=>e.isConstantExpression())));if(this.isUnaryExpression())return"void"===this.node.operator&&this.get("argument").isConstantExpression();if(this.isBinaryExpression()){const{operator:e}=this.node;return"in"!==e&&"instanceof"!==e&&this.get("left").isConstantExpression()&&this.get("right").isConstantExpression()}return this.isMemberExpression()?!this.node.computed&&this.get("object").isIdentifier({name:"Symbol"})&&!this.scope.hasBinding("Symbol",{noGlobals:!0}):!!this.isCallExpression()&&(1===this.node.arguments.length&&this.get("callee").matchesPattern("Symbol.for")&&!this.scope.hasBinding("Symbol",{noGlobals:!0})&&this.get("arguments")[0].isStringLiteral())},t.isInStrictMode=function(){return!!(this.isProgram()?this:this.parentPath).find((e=>{if(e.isProgram({sourceType:"module"}))return!0;if(e.isClass())return!0;if(e.isArrowFunctionExpression()&&!e.get("body").isBlockStatement())return!1;let t;if(e.isFunction())t=e.node.body;else{if(!e.isProgram())return!1;t=e.node}for(const e of t.directives)if("use strict"===e.value.value)return!0}))},t.isNodeType=function(e){return u(this.type,e)},t.isStatementOrBlock=function(){return!this.parentPath.isLabeledStatement()&&!a(this.container)&&s.includes(this.key)},t.isStatic=function(){return this.scope.isStatic(this.node)},t.matchesPattern=function(e,t){return d(this.node,e,t)},t.referencesImport=function(e,t){if(!this.isReferencedIdentifier()){if(this.isJSXMemberExpression()&&this.node.property.name===t||(this.isMemberExpression()||this.isOptionalMemberExpression())&&(this.node.computed?p(this.node.property,{value:t}):this.node.property.name===t)){const t=this.get("object");return t.isReferencedIdentifier()&&t.referencesImport(e,"*")}return!1}const r=this.scope.getBinding(this.node.name);if(!r||"module"!==r.kind)return!1;const n=r.path,s=n.parentPath;return!!s.isImportDeclaration()&&(s.node.source.value===e&&(!t||(!(!n.isImportDefaultSpecifier()||"default"!==t)||(!(!n.isImportNamespaceSpecifier()||"*"!==t)||!(!n.isImportSpecifier()||!l(n.node.imported,{name:t}))))))},t.resolve=function(e,t){return b.call(this,e,t)||this},t.willIMaybeExecuteBefore=function(e){return"after"!==this._guessExecutionStatusRelativeTo(e)};var n=r(2352);const{STATEMENT_OR_BLOCK_KEYS:s,VISITOR_KEYS:i,isBlockStatement:a,isExpression:o,isIdentifier:l,isLiteral:c,isStringLiteral:p,isType:u,matchesPattern:d}=n;function f(e){return e.isProgram()?e:(e.parentPath.scope.getFunctionParent()||e.parentPath.scope.getProgramParent()).path}function h(e,t){switch(e){case"LogicalExpression":case"AssignmentPattern":return"right"===t;case"ConditionalExpression":case"IfStatement":return"consequent"===t||"alternate"===t;case"WhileStatement":case"DoWhileStatement":case"ForInStatement":case"ForOfStatement":return"body"===t;case"ForStatement":return"body"===t||"update"===t;case"SwitchStatement":return"cases"===t;case"TryStatement":return"handler"===t;case"OptionalMemberExpression":return"property"===t;case"OptionalCallExpression":return"arguments"===t;default:return!1}}function m(e,t){for(let r=0;r<t;r++){const t=e[r];if(h(t.parent.type,t.parentKey))return!0}return!1}t.has=function(e){var t;const r=null==(t=this.node)?void 0:t[e];return r&&Array.isArray(r)?!!r.length:!!r},t.is=t.has,t.isnt=function(e){return!this.has(e)},t.equals=function(e,t){return this.node[e]===t};const y=Symbol();function g(e,t,r){const n={this:f(e),target:f(t)};if(n.target.node!==n.this.node)return function(e,t,r){let n,s=r.get(e.node);if(s){if(n=s.get(t.node))return n===y?"unknown":n}else r.set(e.node,s=new Map);s.set(t.node,y);const i=function(e,t,r){if(!t.isFunctionDeclaration())return"before"===g(e,t,r)?"before":"unknown";if(t.parentPath.isExportDeclaration())return"unknown";const n=t.scope.getBinding(t.node.id.name);if(!n.references)return"before";const s=n.referencePaths;let i;for(const n of s){if(n.find((e=>e.node===t.node)))continue;if("callee"!==n.key||!n.parentPath.isCallExpression())return"unknown";const s=g(e,n,r);if(i&&i!==s)return"unknown";i=s}return i}(e,t,r);return s.set(t.node,i),i}(e,n.target,r);const s={target:t.getAncestry(),this:e.getAncestry()};if(s.target.includes(e))return"after";if(s.this.includes(t))return"before";let a;const o={target:0,this:0};for(;!a&&o.this<s.this.length;){const e=s.this[o.this];o.target=s.target.indexOf(e),o.target>=0?a=e:o.this++}if(!a)throw new Error("Internal Babel error - The two compared nodes don't appear to belong to the same program.");if(m(s.this,o.this-1)||m(s.target,o.target-1))return"unknown";const l={this:s.this[o.this-1],target:s.target[o.target-1]};if(l.target.listKey&&l.this.listKey&&l.target.container===l.this.container)return l.target.key>l.this.key?"before":"after";const c=i[a.type],p=c.indexOf(l.this.parentKey);return c.indexOf(l.target.parentKey)>p?"before":"after"}function b(e,t){var r;if(null==(r=t)||!r.includes(this))if((t=t||[]).push(this),this.isVariableDeclarator()){if(this.get("id").isIdentifier())return this.get("init").resolve(e,t)}else if(this.isReferencedIdentifier()){const r=this.scope.getBinding(this.node.name);if(!r)return;if(!r.constant)return;if("module"===r.kind)return;if(r.path!==this){const n=r.path.resolve(e,t);if(this.find((e=>e.node===n.node)))return;return n}}else{if(this.isTypeCastExpression())return this.get("expression").resolve(e,t);if(e&&this.isMemberExpression()){const r=this.toComputedKey();if(!c(r))return;const n=r.value,s=this.get("object").resolve(e,t);if(s.isObjectExpression()){const r=s.get("properties");for(const s of r){if(!s.isProperty())continue;const r=s.get("key");let i=s.isnt("computed")&&r.isIdentifier({name:n});if(i=i||r.isLiteral({value:n}),i)return s.get("value").resolve(e,t)}}else if(s.isArrayExpression()&&!isNaN(+n)){const r=s.get("elements")[n];if(r)return r.resolve(e,t)}}}}},906:(e,t,r)=>{"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"TargetNames",{enumerable:!0,get:function(){return p.TargetNames}}),t.default=function(e={},t={}){var r,a;let{browsers:o,esmodules:u}=e;const{configPath:d=".",onBrowserslistConfigFound:f}=t;!function(e){m.invariant(void 0===e||y(e),`'${String(e)}' is not a valid browserslist query`)}(o);let g=function(e){const t=Object.keys(p.TargetNames);for(const r of Object.keys(e))if(!(r in p.TargetNames))throw new Error(m.formatMessage(`'${r}' is not a valid target\n- Did you mean '${(0,i.findSuggestion)(r,t)}'?`));return e}(function(e){const t=Object.assign({},e);return delete t.esmodules,delete t.browsers,t}(e));const x=!!o||Object.keys(g).length>0,S=!t.ignoreBrowserslistConfig&&!x;if(!o&&S){if(o=n.env.BROWSERSLIST,!o){const e=t.configFile||n.env.BROWSERSLIST_CONFIG||s.findConfigFile(d);null!=e&&(null==f||f(e),o=s.loadConfig({config:e,env:t.browserslistEnv}))}null==o&&(o=[])}if(!u||"intersect"===u&&null!=(r=o)&&r.length||(o=Object.keys(h).map((e=>`${e} >= ${h[e]}`)).join(", "),u=!1),null!=(a=o)&&a.length){const e=function(e,t){const r="string"==typeof e?e:e.join()+t;let n=T.get(r);return n||(n=function(e,t){return function(e){return e.reduce(((e,t)=>{const[r,n]=t.split(" "),s=c.browserNameMap[r];if(!s)return e;try{const t=n.split("-")[0].toLowerCase(),r=(0,l.isUnreleasedVersion)(t,s);if(!e[s])return e[s]=r?t:(0,l.semverify)(t),e;const i=e[s],a=(0,l.isUnreleasedVersion)(i,s);if(a&&r)e[s]=(0,l.getLowestUnreleased)(i,t,s);else if(a)e[s]=(0,l.semverify)(t);else if(!a&&!r){const r=(0,l.semverify)(t);e[s]=(0,l.semverMin)(i,r)}}catch(e){}return e}),{})}(s(e,{mobileToDesktop:!0,env:t}))}(e,t),T.set(r,n)),Object.assign({},n)}(o,t.browserslistEnv);if("intersect"===u)for(const t of Object.keys(e))if("deno"!==t&&"ie"!==t){const r=h["opera_mobile"===t?"op_mob":t];if(r){const n=e[t];e[t]=(0,l.getHighestUnreleased)(n,(0,l.semverify)(r),t)}else delete e[t]}else delete e[t];g=Object.assign(e,g)}const E={},P=[];for(const e of Object.keys(g).sort()){const t=g[e];"number"==typeof t&&t%1!=0&&P.push({target:e,value:t});const[r,n]="node"===e?b(t):v(e,t);n&&(E[r]=n)}return(A=P).length&&(console.warn("Warning, the following targets are using a decimal version:\n"),A.forEach((({target:e,value:t})=>console.warn(` ${e}: ${t}`))),console.warn("\nWe recommend using a string for minor/patch versions to avoid numbers like 6.10\ngetting parsed as 6.1, which can lead to unexpected behavior.\n")),E;var A},Object.defineProperty(t,"filterItems",{enumerable:!0,get:function(){return f.default}}),Object.defineProperty(t,"getInclusionReasons",{enumerable:!0,get:function(){return d.getInclusionReasons}}),t.isBrowsersQueryValid=y,Object.defineProperty(t,"isRequired",{enumerable:!0,get:function(){return f.isRequired}}),Object.defineProperty(t,"prettifyTargets",{enumerable:!0,get:function(){return u.prettifyTargets}}),Object.defineProperty(t,"unreleasedLabels",{enumerable:!0,get:function(){return c.unreleasedLabels}});var s=r(4364),i=r(130),a=r(8761),o=r(9749),l=r(6299),c=r(1884),p=r(8404),u=r(228),d=r(2253),f=r(3347);const h=a["es6.module"],m=new i.OptionValidator("@babel/helper-compilation-targets");function y(e){return"string"==typeof e||Array.isArray(e)&&e.every((e=>"string"==typeof e))}function g(e,t){try{return(0,l.semverify)(t)}catch(r){throw new Error(m.formatMessage(`'${t}' is not a valid value for 'targets.${e}'.`))}}function b(e){return["node",!0===e||"current"===e?n.versions.node.split("-")[0]:g("node",e)]}function v(e,t){return[e,(0,l.isUnreleasedVersion)(t,e)?t.toLowerCase():g(e,t)]}const T=new o({max:64})},940:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.find=function(e){let t=this;do{if(e(t))return t}while(t=t.parentPath);return null},t.findParent=function(e){let t=this;for(;t=t.parentPath;)if(e(t))return t;return null},t.getAncestry=function(){let e=this;const t=[];do{t.push(e)}while(e=e.parentPath);return t},t.getDeepestCommonAncestorFrom=function(e,t){if(!e.length)return this;if(1===e.length)return e[0];let r,n,s=1/0;const i=e.map((e=>{const t=[];do{t.unshift(e)}while((e=e.parentPath)&&e!==this);return t.length<s&&(s=t.length),t})),a=i[0];e:for(let e=0;e<s;e++){const t=a[e];for(const r of i)if(r[e]!==t)break e;r=e,n=t}if(n)return t?t(n,r,i):n;throw new Error("Couldn't find intersection")},t.getEarliestCommonAncestorFrom=function(e){return this.getDeepestCommonAncestorFrom(e,(function(e,t,r){let n;const i=s[e.type];for(const e of r){const r=e[t+1];n?(r.listKey&&n.listKey===r.listKey&&r.key<n.key||i.indexOf(n.parentKey)>i.indexOf(r.parentKey))&&(n=r):n=r}return n}))},t.getFunctionParent=function(){return this.findParent((e=>e.isFunction()))},t.getStatementParent=function(){let e=this;do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement())break;e=e.parentPath}while(e);if(e&&(e.isProgram()||e.isFile()))throw new Error("File/Program node, we can't possibly find a statement parent to this");return e},t.inType=function(...e){let t=this;for(;t;){for(const r of e)if(t.node.type===r)return!0;t=t.parentPath}return!1},t.isAncestor=function(e){return e.isDescendant(this)},t.isDescendant=function(e){return!!this.findParent((t=>t===e))};var n=r(2352);const{VISITOR_KEYS:s}=n},947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.finalize=function(e){return Object.freeze(e)},t.flattenToSet=function(e){const t=new Set,r=[e];for(;r.length>0;)for(const e of r.pop())Array.isArray(e)?r.push(e):t.add(e);return t}},983:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t=!0){return"string"==typeof e&&((!t||!(0,n.isKeyword)(e)&&!(0,n.isStrictReservedWord)(e,!0))&&(0,n.isIdentifierName)(e))};var n=r(1e3)},985:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildUndefinedNode=function(){return(0,n.unaryExpression)("void",(0,n.numericLiteral)(0),!0)};var n=r(8079)},1e3:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isIdentifierChar",{enumerable:!0,get:function(){return n.isIdentifierChar}}),Object.defineProperty(t,"isIdentifierName",{enumerable:!0,get:function(){return n.isIdentifierName}}),Object.defineProperty(t,"isIdentifierStart",{enumerable:!0,get:function(){return n.isIdentifierStart}}),Object.defineProperty(t,"isKeyword",{enumerable:!0,get:function(){return s.isKeyword}}),Object.defineProperty(t,"isReservedWord",{enumerable:!0,get:function(){return s.isReservedWord}}),Object.defineProperty(t,"isStrictBindOnlyReservedWord",{enumerable:!0,get:function(){return s.isStrictBindOnlyReservedWord}}),Object.defineProperty(t,"isStrictBindReservedWord",{enumerable:!0,get:function(){return s.isStrictBindReservedWord}}),Object.defineProperty(t,"isStrictReservedWord",{enumerable:!0,get:function(){return s.isStrictReservedWord}});var n=r(8721),s=r(3115)},1002:e=>{"use strict";e.exports=Function.prototype.apply},1009:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){const t=(0,s.default)(e);return 1===t.length?t[0]:(0,n.unionTypeAnnotation)(t)};var n=r(8079),s=r(5237)},1064:(e,t,r)=>{"use strict";var n=r(9612);e.exports=n.getPrototypeOf||null},1093:e=>{"use strict";var t=Object.prototype.toString;e.exports=function(e){var r=t.call(e),n="[object Arguments]"===r;return n||(n="[object Array]"!==r&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===t.call(e.callee)),n}},1135:e=>{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},1156:(e,t,r)=>{t.getModuleName=()=>r(1792).ug},1189:(e,t,r)=>{"use strict";var n=Array.prototype.slice,s=r(1093),i=Object.keys,a=i?function(e){return i(e)}:r(8875),o=Object.keys;a.shim=function(){if(Object.keys){var e=function(){var e=Object.keys(arguments);return e&&e.length===arguments.length}(1,2);e||(Object.keys=function(e){return s(e)?o(n.call(e)):o(e)})}else Object.keys=a;return Object.keys||a},e.exports=a},1237:e=>{"use strict";e.exports=EvalError},1310:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.assertSimpleType=h,t.makeStrongCache=c,t.makeStrongCacheSync=function(e){return a(c(e))},t.makeWeakCache=l,t.makeWeakCacheSync=function(e){return a(l(e))};var s=r(3310),i=r(9923);const a=e=>n()(e).sync;function*o(){return!0}function l(e){return p(WeakMap,e)}function c(e){return p(Map,e)}function p(e,t){const r=new e,n=new e,a=new e;return function*(e,o){const l=yield*(0,s.isAsync)(),c=l?n:r,p=yield*function*(e,t,r,n,i){const a=yield*u(t,n,i);if(a.valid)return a;if(e){const e=yield*u(r,n,i);if(e.valid)return{valid:!0,value:yield*(0,s.waitFor)(e.value.promise)}}return{valid:!1,value:null}}(l,c,a,e,o);if(p.valid)return p.value;const h=new f(o),y=t(e,h);let g,b;return b=(0,i.isIterableIterator)(y)?yield*(0,s.onFirstPause)(y,(()=>{g=function(e,t,r){const n=new m;return d(t,e,r,n),n}(h,a,e)})):y,d(c,h,e,b),g&&(a.delete(e),g.release(b)),b}}function*u(e,t,r){const n=e.get(t);if(n)for(const{value:e,valid:t}of n)if(yield*t(r))return{valid:!0,value:e};return{valid:!1,value:null}}function d(e,t,r,n){t.configured()||t.forever();let s=e.get(r);switch(t.deactivate(),t.mode()){case"forever":s=[{value:n,valid:o}],e.set(r,s);break;case"invalidate":s=[{value:n,valid:t.validator()}],e.set(r,s);break;case"valid":s?s.push({value:n,valid:t.validator()}):(s=[{value:n,valid:t.validator()}],e.set(r,s))}}class f{constructor(e){this._active=!0,this._never=!1,this._forever=!1,this._invalidate=!1,this._configured=!1,this._pairs=[],this._data=void 0,this._data=e}simple(){return function(e){function t(t){if("boolean"!=typeof t)return e.using((()=>h(t())));t?e.forever():e.never()}return t.forever=()=>e.forever(),t.never=()=>e.never(),t.using=t=>e.using((()=>h(t()))),t.invalidate=t=>e.invalidate((()=>h(t()))),t}(this)}mode(){return this._never?"never":this._forever?"forever":this._invalidate?"invalidate":"valid"}forever(){if(!this._active)throw new Error("Cannot change caching after evaluation has completed.");if(this._never)throw new Error("Caching has already been configured with .never()");this._forever=!0,this._configured=!0}never(){if(!this._active)throw new Error("Cannot change caching after evaluation has completed.");if(this._forever)throw new Error("Caching has already been configured with .forever()");this._never=!0,this._configured=!0}using(e){if(!this._active)throw new Error("Cannot change caching after evaluation has completed.");if(this._never||this._forever)throw new Error("Caching has already been configured with .never or .forever()");this._configured=!0;const t=e(this._data),r=(0,s.maybeAsync)(e,"You appear to be using an async cache handler, but Babel has been called synchronously");return(0,s.isThenable)(t)?t.then((e=>(this._pairs.push([e,r]),e))):(this._pairs.push([t,r]),t)}invalidate(e){return this._invalidate=!0,this.using(e)}validator(){const e=this._pairs;return function*(t){for(const[r,n]of e)if(r!==(yield*n(t)))return!1;return!0}}deactivate(){this._active=!1}configured(){return this._configured}}function h(e){if((0,s.isThenable)(e))throw new Error("You appear to be using an async cache handler, which your current version of Babel does not support. We may add support for this in the future, but if you're on the most recent version of @babel/core and still seeing this error, then you'll need to synchronously handle your caching logic.");if(null!=e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e)throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");return e}class m{constructor(){this.released=!1,this.promise=void 0,this._resolve=void 0,this.promise=new Promise((e=>{this._resolve=e}))}release(e){this.released=!0,this._resolve(e)}}},1333:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var s=Object.getOwnPropertySymbols(e);if(1!==s.length||s[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},1339:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.beginHiddenCallStack=function(e){return s?Object.defineProperty((function(...t){return c(),e(...t)}),"name",{value:a}):e},t.endHiddenCallStack=function(e){return s?Object.defineProperty((function(...t){return e(...t)}),"name",{value:i}):e},t.expectedError=function(e){if(s)return o.add(e),e},t.injectVirtualStackFrame=function(e,t){if(!s)return;let r=l.get(e);return r||l.set(e,r=[]),r.push(function(e){return Object.create({isNative:()=>!1,isConstructor:()=>!1,isToplevel:()=>!0,getFileName:()=>e,getLineNumber:()=>{},getColumnNumber:()=>{},getFunctionName:()=>{},getMethodName:()=>{},getTypeName:()=>{},toString:()=>e})}(t)),e};const n=Function.call.bind(Error.prototype.toString),s=!!Error.captureStackTrace&&!0===(null==(r=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit"))?void 0:r.writable),i="startHiding - secret - don't use this - v1",a="stopHiding - secret - don't use this - v1",o=new WeakSet,l=new WeakMap;function c(){c=()=>{};const{prepareStackTrace:e=p}=Error;Error.stackTraceLimit&&(Error.stackTraceLimit=Math.max(Error.stackTraceLimit,50)),Error.prepareStackTrace=function(t,r){let n=[],s=o.has(t)?"hiding":"unknown";for(let e=0;e<r.length;e++){const o=r[e].getFunctionName();if(o===i)s="hiding";else if(o===a){if("hiding"===s)s="showing",l.has(t)&&n.unshift(...l.get(t));else if("unknown"===s){n=r;break}}else"hiding"!==s&&n.push(r[e])}return e(t,n)}}function p(e,t){return 0===t.length?n(e):`${n(e)}\n at ${t.join("\n at ")}`}},1343:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){const t=[].concat(e),r=Object.create(null);for(;t.length;){const e=t.pop();if(e)switch(e.type){case"ArrayPattern":t.push(...e.elements);break;case"AssignmentExpression":case"AssignmentPattern":case"ForInStatement":case"ForOfStatement":t.push(e.left);break;case"ObjectPattern":t.push(...e.properties);break;case"ObjectProperty":t.push(e.value);break;case"RestElement":case"UpdateExpression":t.push(e.argument);break;case"UnaryExpression":"delete"===e.operator&&t.push(e.argument);break;case"Identifier":r[e.name]=e}}return r}},1373:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenContext=void 0,t.isLastChild=function(e,t){const r=o[e.type];for(let n=r.length-1;n>=0;n--){const s=e[r[n]];if(s===t)return!0;if(Array.isArray(s)){let e=s.length-1;for(;e>=0&&null===s[e];)e--;return e>=0&&s[e]===t}if(s)return!1}return!1},t.needsParens=function(e,t,r,n,s){var i;return!!t&&(!(!d(t)||t.callee!==e||!g(e))||(c(t)?!(v(e)||l(e)&&v(e.callee)||f(e)):null==(i=m.get(e.type))?void 0:i(e,t,r,n,s)))},t.needsWhitespace=b,t.needsWhitespaceAfter=function(e,t){return b(e,t,2)},t.needsWhitespaceBefore=function(e,t){return b(e,t,1)};var n=r(2716),s=r(1773),i=r(2352);const{FLIPPED_ALIAS_KEYS:a,VISITOR_KEYS:o,isCallExpression:l,isDecorator:c,isExpressionStatement:p,isMemberExpression:u,isNewExpression:d,isParenthesizedExpression:f}=i;function h(e){const t=new Map;function r(e,r){const n=t.get(e);t.set(e,n?function(e,t,s,i,a){var o;return null!=(o=n(e,t,s,i,a))?o:r(e,t,s,i,a)}:r)}for(const t of Object.keys(e)){const n=a[t];if(n)for(const s of n)r(s,e[t]);else r(t,e[t])}return t}t.TokenContext={expressionStatement:1,arrowBody:2,exportDefault:4,forHead:8,forInHead:16,forOfHead:32,arrowFlowReturnType:64};const m=h(s),y=h(n.nodes);function g(e){return!!l(e)||u(e)&&g(e.object)}function b(e,t,r){var n;if(!e)return!1;p(e)&&(e=e.expression);const s=null==(n=y.get(e.type))?void 0:n(e,t);return"number"==typeof s&&!!(s&r)}function v(e){switch(e.type){case"Identifier":return!0;case"MemberExpression":return!e.computed&&"Identifier"===e.property.type&&v(e.object);default:return!1}}},1384:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.default)(e)&&!s.has(e)};var n=r(983);const s=new Set(["abstract","boolean","byte","char","double","enum","final","float","goto","implements","int","interface","long","native","package","private","protected","public","short","static","synchronized","throws","transient","volatile"])},1514:e=>{"use strict";e.exports=Math.abs},1602:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(9709),s=r(2352),i=r(9578);const{VISITOR_KEYS:a}=s;t.default=class{constructor(e,t,r,n){this.queue=null,this.priorityQueue=null,this.parentPath=n,this.scope=e,this.state=r,this.opts=t}shouldVisit(e){const t=this.opts;if(t.enter||t.exit)return!0;if(t[e.type])return!0;const r=a[e.type];if(null==r||!r.length)return!1;for(const t of r)if(e[t])return!0;return!1}create(e,t,r,s){return n.default.get({parentPath:this.parentPath,parent:e,container:t,key:r,listKey:s})}maybeQueue(e,t){this.queue&&(t?this.queue.push(e):this.priorityQueue.push(e))}visitMultiple(e,t,r){if(0===e.length)return!1;const n=[];for(let s=0;s<e.length;s++){const i=e[s];i&&this.shouldVisit(i)&&n.push(this.create(t,e,s,r))}return this.visitQueue(n)}visitSingle(e,t){return!!this.shouldVisit(e[t])&&this.visitQueue([this.create(e,e,t)])}visitQueue(e){this.queue=e,this.priorityQueue=[];const t=new WeakSet;let r=!1,n=0;for(;n<e.length;){const s=e[n];if(n++,i.resync.call(s),0!==s.contexts.length&&s.contexts[s.contexts.length-1]===this||i.pushContext.call(s,this),null===s.key)continue;const{node:a}=s;if(!t.has(a)){if(a&&t.add(a),s.visit()){r=!0;break}if(this.priorityQueue.length&&(r=this.visitQueue(this.priorityQueue),this.priorityQueue=[],this.queue=e,r))break}}for(let t=0;t<n;t++)i.popContext.call(e[t]);return this.queue=null,r}visit(e,t){const r=e[t];return!!r&&(Array.isArray(r)?this.visitMultiple(r,e,t):this.visitSingle(e,t))}}},1715:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validatePluginObject=function(e){const t={type:"root",source:"plugin"};return Object.keys(e).forEach((r=>{const n=s[r];if(!n){const e=new Error(`.${r} is not a valid Plugin property`);throw e.code="BABEL_UNKNOWN_PLUGIN_PROPERTY",e}n({type:"option",name:r,parent:t},e[r])})),e};var n=r(4374);const s={name:n.assertString,manipulateOptions:n.assertFunction,pre:n.assertFunction,post:n.assertFunction,inherits:n.assertFunction,visitor:function(e,t){const r=(0,n.assertObject)(e,t);if(r&&(Object.keys(r).forEach((e=>{"_exploded"!==e&&"_verified"!==e&&function(e,t){if(t&&"object"==typeof t)Object.keys(t).forEach((t=>{if("enter"!==t&&"exit"!==t)throw new Error(`.visitor["${e}"] may only have .enter and/or .exit handlers.`)}));else if("function"!=typeof t)throw new Error(`.visitor["${e}"] must be a function`)}(e,r[e])})),r.enter||r.exit))throw new Error(`${(0,n.msg)(e)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`);return r},parserOverride:n.assertFunction,generatorOverride:n.assertFunction}},1773:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssignmentExpression=function(e,t,r){return!(!T(r)||!u(e.left))||E(e,t)},t.Binary=x,t.BinaryExpression=function(e,t,r,n){return"in"===e.operator&&n},t.ClassExpression=function(e,t,r){return Boolean(r&(s.TokenContext.expressionStatement|s.TokenContext.exportDefault))},t.ArrowFunctionExpression=t.ConditionalExpression=E,t.DoExpression=function(e,t,r){return!e.async&&Boolean(r&s.TokenContext.expressionStatement)},t.FunctionExpression=function(e,t,r){return Boolean(r&(s.TokenContext.expressionStatement|s.TokenContext.exportDefault))},t.FunctionTypeAnnotation=function(e,t,r){const n=t.type;return"UnionTypeAnnotation"===n||"IntersectionTypeAnnotation"===n||"ArrayTypeAnnotation"===n||Boolean(r&s.TokenContext.arrowFlowReturnType)},t.Identifier=function(e,t,r,n,i){var a;const o=t.type;if(null!=(a=e.extra)&&a.parenthesized&&"AssignmentExpression"===o&&t.left===e){const e=t.right.type;if(("FunctionExpression"===e||"ClassExpression"===e)&&null==t.right.id)return!0}return(!i||i(e)===e.name)&&("let"===e.name?!!((p(t,{object:e,computed:!0})||d(t,{object:e,computed:!0,optional:!1}))&&r&(s.TokenContext.expressionStatement|s.TokenContext.forHead|s.TokenContext.forInHead))||Boolean(r&s.TokenContext.forOfHead):"async"===e.name&&l(t,{left:e,await:!1}))},t.LogicalExpression=function(e,t){const r=t.type;if(g(r))return!0;if("LogicalExpression"!==r)return!1;switch(e.operator){case"||":return"??"===t.operator||"&&"===t.operator;case"&&":return"??"===t.operator;case"??":return"??"!==t.operator}},t.NullableTypeAnnotation=function(e,t){return i(t)},t.ObjectExpression=function(e,t,r){return T(r)},t.OptionalIndexedAccessType=function(e,t){return c(t)&&t.objectType===e},t.OptionalCallExpression=t.OptionalMemberExpression=function(e,t){return o(t)&&t.callee===e||p(t)&&t.object===e},t.SequenceExpression=function(e,t){const r=t.type;return!("SequenceExpression"===r||"ParenthesizedExpression"===r||"MemberExpression"===r&&t.property===e||"OptionalMemberExpression"===r&&t.property===e||"TemplateLiteral"===r)&&("ClassDeclaration"===r||("ForOfStatement"===r?t.right===e:"ExportDefaultDeclaration"===r||!h(t)))},t.TSSatisfiesExpression=t.TSAsExpression=function(e,t){return("AssignmentExpression"===t.type||"AssignmentPattern"===t.type)&&t.left===e||("BinaryExpression"===t.type&&("|"===t.operator||"&"===t.operator)&&e===t.left||x(e,t))},t.TSConditionalType=function(e,t){const r=t.type;return"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r||"TSTypeOperator"===r||"TSTypeParameter"===r||(("TSIntersectionType"===r||"TSUnionType"===r)&&t.types[0]===e||"TSConditionalType"===r&&(t.checkType===e||t.extendsType===e))},t.TSConstructorType=t.TSFunctionType=function(e,t){const r=t.type;return"TSIntersectionType"===r||"TSUnionType"===r||"TSTypeOperator"===r||"TSOptionalType"===r||"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSConditionalType"===r&&(t.checkType===e||t.extendsType===e)},t.TSInferType=function(e,t){const r=t.type;return"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r||!(!e.typeParameter.constraint||"TSIntersectionType"!==r&&"TSUnionType"!==r||t.types[0]!==e)},t.TSInstantiationExpression=function(e,t){const r=t.type;return("CallExpression"===r||"OptionalCallExpression"===r||"NewExpression"===r||"TSInstantiationExpression"===r)&&!!t.typeParameters},t.TSIntersectionType=function(e,t){const r=t.type;return"TSTypeOperator"===r||"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r},t.UnaryLike=t.TSTypeAssertion=S,t.TSTypeOperator=function(e,t){const r=t.type;return"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r},t.TSUnionType=function(e,t){const r=t.type;return"TSIntersectionType"===r||"TSTypeOperator"===r||"TSArrayType"===r||"TSIndexedAccessType"===r&&t.objectType===e||"TSOptionalType"===r},t.IntersectionTypeAnnotation=t.UnionTypeAnnotation=function(e,t){const r=t.type;return"ArrayTypeAnnotation"===r||"NullableTypeAnnotation"===r||"IntersectionTypeAnnotation"===r||"UnionTypeAnnotation"===r},t.UpdateExpression=function(e,t){return v(e,t)||b(e,t)},t.AwaitExpression=t.YieldExpression=function(e,t){const r=t.type;return"BinaryExpression"===r||"LogicalExpression"===r||"UnaryExpression"===r||"SpreadElement"===r||v(e,t)||"AwaitExpression"===r&&f(e)||"ConditionalExpression"===r&&e===t.test||b(e,t)||g(r)};var n=r(2352),s=r(1373);const{isArrayTypeAnnotation:i,isBinaryExpression:a,isCallExpression:o,isForOfStatement:l,isIndexedAccessType:c,isMemberExpression:p,isObjectPattern:u,isOptionalMemberExpression:d,isYieldExpression:f,isStatement:h}=n,m=new Map([["||",0],["??",0],["|>",0],["&&",1],["|",2],["^",3],["&",4],["==",5],["===",5],["!=",5],["!==",5],["<",6],[">",6],["<=",6],[">=",6],["in",6],["instanceof",6],[">>",7],["<<",7],[">>>",7],["+",8],["-",8],["*",9],["/",9],["%",9],["**",10]]);function y(e,t){return"BinaryExpression"===t||"LogicalExpression"===t?m.get(e.operator):"TSAsExpression"===t||"TSSatisfiesExpression"===t?m.get("in"):void 0}function g(e){return"TSAsExpression"===e||"TSSatisfiesExpression"===e||"TSTypeAssertion"===e}const b=(e,t)=>{const r=t.type;return("ClassDeclaration"===r||"ClassExpression"===r)&&t.superClass===e},v=(e,t)=>{const r=t.type;return("MemberExpression"===r||"OptionalMemberExpression"===r)&&t.object===e||("CallExpression"===r||"OptionalCallExpression"===r||"NewExpression"===r)&&t.callee===e||"TaggedTemplateExpression"===r&&t.tag===e||"TSNonNullExpression"===r};function T(e){return Boolean(e&(s.TokenContext.expressionStatement|s.TokenContext.arrowBody))}function x(e,t){const r=t.type;if("BinaryExpression"===e.type&&"**"===e.operator&&"BinaryExpression"===r&&"**"===t.operator)return t.left===e;if(b(e,t))return!0;if(v(e,t)||"UnaryExpression"===r||"SpreadElement"===r||"AwaitExpression"===r)return!0;const n=y(t,r);if(null!=n){const s=y(e,e.type);if(n===s&&"BinaryExpression"===r&&t.right===e||n>s)return!0}}function S(e,t){return v(e,t)||a(t)&&"**"===t.operator&&t.left===e||b(e,t)}function E(e,t){const r=t.type;return!!("UnaryExpression"===r||"SpreadElement"===r||"BinaryExpression"===r||"LogicalExpression"===r||"ConditionalExpression"===r&&t.test===e||"AwaitExpression"===r||g(r))||S(e,t)}},1792:(e,t,r)=>{"use strict";Object.defineProperty(t,"ug",{enumerable:!0,get:function(){return n.default}});r(4148),r(6416),r(4865),r(3817),r(8274),r(7372),r(4184),r(6871);var n=r(4777);r(6871).getDynamicImportSource},1884:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unreleasedLabels=t.browserNameMap=void 0,t.unreleasedLabels={safari:"tp"},t.browserNameMap={and_chr:"chrome",and_ff:"firefox",android:"android",chrome:"chrome",edge:"edge",firefox:"firefox",ie:"ie",ie_mob:"ie",ios_saf:"ios",node:"node",deno:"deno",op_mob:"opera_mobile",opera:"opera",safari:"safari",samsung:"samsung"}},2037:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._replaceWith=R,t.replaceExpressionWithStatements=function(e){p.resync.call(this);const t=[],r=U(e,t);if(r){for(const e of t)this.scope.push({id:e});return this.replaceWith(r)[0].get("expressions")}const n=this.getFunctionParent(),i=null==n?void 0:n.node.async,a=null==n?void 0:n.node.generator,o=d([],m(e));this.replaceWith(g(o,[]));const l=this.get("callee");l.get("body").scope.hoistVariables((e=>this.scope.push({id:e})));const c=l.getCompletionRecords();for(const e of c){if(!e.isExpressionStatement())continue;const t=e.findParent((e=>e.isLoop()));if(t){let r=t.getData("expressionReplacementReturnUid");r?r=S(r.name):(r=l.scope.generateDeclaredUidIdentifier("ret"),l.get("body").pushContainer("body",B(b(r))),t.setData("expressionReplacementReturnUid",r)),e.get("expression").replaceWith(f("=",b(r),e.node.expression))}else e.replaceWith(B(e.node.expression))}l.arrowFunctionToExpression();const y=l,v=i&&s.default.hasType(this.get("callee.body").node,"AwaitExpression",u),T=a&&s.default.hasType(this.get("callee.body").node,"YieldExpression",u);return v&&(y.set("async",!0),T||this.replaceWith(h(this.node))),T&&(y.set("generator",!0),this.replaceWith(F(this.node,!0))),y.get("body.body")},t.replaceInline=function(e){if(p.resync.call(this),Array.isArray(e)){if(Array.isArray(this.container)){e=o._verifyNodeList.call(this,e);const t=o._containerInsertAfter.call(this,e);return this.remove(),t}return this.replaceWithMultiple(e)}return this.replaceWith(e)},t.replaceWith=function(e){if(p.resync.call(this),this.removed)throw new Error("You can't replace this node, we've already removed it");let t=e instanceof i.default?e.node:e;if(!t)throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");if(this.node===t)return[this];if(this.isProgram()&&!k(t))throw new Error("You can only replace a Program root node with another Program node");if(Array.isArray(t))throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");if("string"==typeof t)throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");let r="";if(this.isNodeType("Statement")&&O(t)&&(this.canHaveVariableDeclarationOrExpression()||this.canSwapBetweenExpressionAndStatement(t)||this.parentPath.isExportDefaultDeclaration()||(t=T(t),r="expression")),this.isNodeType("Expression")&&_(t)&&!this.canHaveVariableDeclarationOrExpression()&&!this.canSwapBetweenExpressionAndStatement(t))return this.replaceExpressionWithStatements([t]);const n=this.node;return n&&(A(t,n),j(n)),R.call(this,t),this.type=t.type,p.setScope.call(this),this.requeue(),[r?this.get(r):this]},t.replaceWithMultiple=function(e){var t;p.resync.call(this),e=o._verifyNodeList.call(this,e),E(e[0],this.node),P(e[e.length-1],this.node),null==(t=(0,a.getCachedPaths)(this.hub,this.parent))||t.delete(this.node),this.node=this.container[this.key]=null;const r=this.insertAfter(e);return this.node?this.requeue():this.remove(),r},t.replaceWithSourceString=function(e){let t;p.resync.call(this);try{e=`(${e})`,t=(0,l.parse)(e)}catch(t){const r=t.loc;throw r&&(t.message+=" - make sure this is an expression.\n"+(0,n.codeFrameColumns)(e,{start:{line:r.line,column:r.column+1}}),t.code="BABEL_REPLACE_SOURCE_ERROR"),t}const r=t.program.body[0].expression;return s.default.removeProperties(r),this.replaceWith(r)};var n=r(2882),s=r(5781),i=r(9709),a=r(7411),o=r(8345),l=r(2172),c=r(2352),p=r(9578);const{FUNCTION_TYPES:u,arrowFunctionExpression:d,assignmentExpression:f,awaitExpression:h,blockStatement:m,buildUndefinedNode:y,callExpression:g,cloneNode:b,conditionalExpression:v,expressionStatement:T,getBindingIdentifiers:x,identifier:S,inheritLeadingComments:E,inheritTrailingComments:P,inheritsComments:A,isBlockStatement:w,isEmptyStatement:C,isExpression:O,isExpressionStatement:I,isIfStatement:N,isProgram:k,isStatement:_,isVariableDeclaration:D,removeComments:j,returnStatement:B,sequenceExpression:M,validate:L,yieldExpression:F}=c;function R(e){var t;if(!this.container)throw new ReferenceError("Container is falsy");this.inList?L(this.parent,this.key,[e]):L(this.parent,this.key,e),this.debug(`Replace with ${null==e?void 0:e.type}`),null==(t=(0,a.getCachedPaths)(this.hub,this.parent))||t.set(e,this).delete(this.node),this.node=this.container[this.key]=e}function U(e,t){const r=[];let n=!0;for(const s of e)if(C(s)||(n=!1),O(s))r.push(s);else if(I(s))r.push(s.expression);else if(D(s)){if("var"!==s.kind)return;for(const e of s.declarations){const n=x(e);for(const e of Object.keys(n))t.push(b(n[e]));e.init&&r.push(f("=",e.id,e.init))}n=!0}else if(N(s)){const e=s.consequent?U([s.consequent],t):y(),n=s.alternate?U([s.alternate],t):y();if(!e||!n)return;r.push(v(s.test,e,n))}else if(w(s)){const e=U(s.body,t);if(!e)return;r.push(e)}else{if(!C(s))return;0===e.indexOf(s)&&(n=!0)}return n&&r.push(y()),1===r.length?r[0]:M(r)}},2107:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.default)(e,!1)};var n=r(5279)},2110:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var s=r(3310),i=r(9923),a=r(6416),o=r(5856),l=r(6140),c=r(3045),p=r(947);function u(){const e=r(5781);return u=function(){return e},e}var d=r(1310),f=r(7165),h=r(1715),m=r(6890),y=r(2610),g=r(7445);function b(e,t){return function*(r,n){try{return yield*t(r,n)}catch(t){var s;throw/^\[BABEL\]/.test(t.message)||(t.message=`[BABEL] ${null!=(s=e.filename)?s:"unknown file"}: ${t.message}`),t}}}t.default=n()((function*(e){var t;const r=yield*(0,y.default)(e);if(!r)return null;const{options:n,context:s,fileHandling:a}=r;if("ignored"===a)return null;const o={},{plugins:c,presets:u}=n;if(!c||!u)throw new Error("Assertion failure - plugins and presets exist");const d=Object.assign({},s,{targets:n.targets}),h=e=>{const t=(0,l.getItemDescriptor)(e);if(!t)throw new Error("Assertion failure - must be config item");return t},m=u.map(h),g=c.map(h),v=[[]],T=[],x=[],S=yield*b(s,(function*e(t,r){const n=[];for(let e=0;e<t.length;e++){const i=t[e];if(!1!==i.options){try{var s=yield*O(i,d)}catch(r){throw"BABEL_UNKNOWN_OPTION"===r.code&&(0,f.checkNoUnwrappedItemOptionPairs)(t,e,"preset",r),r}x.push(s.externalDependencies),i.ownPass?n.push({preset:s.chain,pass:[]}):n.unshift({preset:s.chain,pass:r})}}if(n.length>0){v.splice(1,0,...n.map((e=>e.pass)).filter((e=>e!==r)));for(const{preset:t,pass:r}of n){if(!t)return!0;if(r.push(...t.plugins),yield*e(t.presets,r))return!0;t.options.forEach((e=>{(0,i.mergeOptions)(o,e)}))}}}))(m,v[0]);if(S)return null;const P=o;(0,i.mergeOptions)(P,n);const A=Object.assign({},d,{assumptions:null!=(t=P.assumptions)?t:{}});return yield*b(s,(function*(){v[0].unshift(...g);for(const t of v){const r=[];T.push(r);for(let n=0;n<t.length;n++){const s=t[n];if(!1!==s.options){try{var e=yield*E(s,A)}catch(e){throw"BABEL_UNKNOWN_PLUGIN_PROPERTY"===e.code&&(0,f.checkNoUnwrappedItemOptionPairs)(t,n,"plugin",e),e}r.push(e),x.push(e.externalDependencies)}}}}))(),P.plugins=T[0],P.presets=T.slice(1).filter((e=>e.length>0)).map((e=>({plugins:e}))),P.passPerPreset=P.presets.length>0,{options:P,passes:T,externalDependencies:(0,p.finalize)(x)}}));const v=e=>(0,d.makeWeakCache)((function*({value:t,options:r,dirname:n,alias:i},o){if(!1===r)throw new Error("Assertion failure");r=r||{};const l=[];let c=t;if("function"==typeof t){const p=(0,s.maybeAsync)(t,"You appear to be using an async plugin/preset, but Babel has been called synchronously"),u=Object.assign({},a,e(o,l));try{c=yield*p(u,r,n)}catch(e){throw i&&(e.message+=` (While processing: ${JSON.stringify(i)})`),e}}if(!c||"object"!=typeof c)throw new Error("Plugin/Preset did not return an object.");if((0,s.isThenable)(c))throw yield*[],new Error(`You appear to be using a promise as a plugin, which your current version of Babel does not support. If you're using a published plugin, you may need to upgrade your @babel/core version. As an alternative, you can prefix the promise with "await". (While processing: ${JSON.stringify(i)})`);if(l.length>0&&(!o.configured()||"forever"===o.mode())){let e=`A plugin/preset has external untracked dependencies (${l[0]}), but the cache `;throw o.configured()?e+=" has been configured to never be invalidated. ":e+="has not been configured to be invalidated when the external dependencies change. ",e+=`Plugins/presets should configure their cache to be invalidated when the external dependencies change, for example using \`api.cache.invalidate(() => statSync(filepath).mtimeMs)\` or \`api.cache.never()\`\n(While processing: ${JSON.stringify(i)})`,new Error(e)}return{value:c,options:r,dirname:n,alias:i,externalDependencies:(0,p.finalize)(l)}})),T=v(m.makePluginAPI),x=v(m.makePresetAPI),S=(0,d.makeWeakCache)((function*({value:e,options:t,dirname:r,alias:n,externalDependencies:i},a){const l=(0,h.validatePluginObject)(e),c=Object.assign({},l);if(c.visitor&&(c.visitor=u().default.explode(Object.assign({},c.visitor))),c.inherits){const e={name:void 0,alias:`${n}$inherits`,value:c.inherits,options:t,dirname:r},o=yield*(0,s.forwardAsync)(E,(t=>a.invalidate((r=>t(e,r)))));c.pre=I(o.pre,c.pre),c.post=I(o.post,c.post),c.manipulateOptions=I(o.manipulateOptions,c.manipulateOptions),c.visitor=u().default.visitors.merge([o.visitor||{},c.visitor||{}]),o.externalDependencies.length>0&&(i=0===i.length?o.externalDependencies:(0,p.finalize)([i,o.externalDependencies]))}return new o.default(c,t,n,i)}));function*E(e,t){if(e.value instanceof o.default){if(e.options)throw new Error("Passed options to an existing Plugin instance will not work.");return e.value}return yield*S(yield*T(e,t),t)}const P=e=>e&&"function"!=typeof e,A=(e,t)=>{if(P(e.test)||P(e.include)||P(e.exclude)){const e=t.name?`"${t.name}"`:"/* your preset */";throw new g.default([`Preset ${e} requires a filename to be set when babel is called directly,`,"```",`babel.transformSync(code, { filename: 'file.ts', presets: [${e}] });`,"```","See https://babeljs.io/docs/en/options#filename for more information."].join("\n"))}},w=(e,t,r)=>{if(!t.filename){var n;const{options:t}=e;A(t,r),null==(n=t.overrides)||n.forEach((e=>A(e,r)))}},C=(0,d.makeWeakCacheSync)((({value:e,dirname:t,alias:r,externalDependencies:n})=>({options:(0,f.validate)("preset",e),alias:r,dirname:t,externalDependencies:n})));function*O(e,t){const r=C(yield*x(e,t));return w(r,t,e),{chain:yield*(0,c.buildPresetChain)(r,t),externalDependencies:r.externalDependencies}}function I(e,t){return e?t?function(...r){const n=e.apply(this,r);return n&&"function"==typeof n.then?n.then((()=>t.apply(this,r))):t.apply(this,r)}:e:t}},2120:(e,t,r)=>{"use strict";function n(){const e=r(5913);return n=function(){return e},e}function s(){const e=r(8992);return s=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const{opts:r,ast:a,code:o,inputMap:l}=t,{generatorOpts:c}=r;c.inputSourceMap=null==l?void 0:l.toObject();const p=[];for(const t of e)for(const e of t){const{generatorOverride:t}=e;if(t){const e=t(a,c,o,s().default);void 0!==e&&p.push(e)}}let u;if(0===p.length)u=(0,s().default)(a,c,o);else{if(1!==p.length)throw new Error("More than one plugin attempted to override codegen.");if(u=p[0],"function"==typeof u.then)throw new Error("You appear to be using an async codegen plugin, which your current version of Babel does not support. If you're using a published plugin, you may need to upgrade your @babel/core version.")}let{code:d,decodedMap:f=u.map}=u;return u.__mergedMap?f=Object.assign({},u.map):f&&(f=l?(0,i.default)(l.toObject(),f,c.sourceFileName):u.map),"inline"!==r.sourceMaps&&"both"!==r.sourceMaps||(d+="\n"+n().fromObject(f).toComment()),"inline"===r.sourceMaps&&(f=null),{outputCode:d,outputMap:f}};var i=r(6884)},2172:(e,t)=>{"use strict";function r(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(e,t,r){this.line=void 0,this.column=void 0,this.index=void 0,this.line=e,this.column=t,this.index=r}}class s{constructor(e,t){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=e,this.end=t}}function i(e,t){const{line:r,column:s,index:i}=e;return new n(r,s+t,i+t)}const a="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";var o={ImportMetaOutsideModule:{message:"import.meta may appear only with 'sourceType: \"module\"'",code:a},ImportOutsideModule:{message:"'import' and 'export' may appear only with 'sourceType: \"module\"'",code:a}};const l={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},c=e=>"UpdateExpression"===e.type?l.UpdateExpression[`${e.prefix}`]:l[e.type];var p={AccessorIsGenerator:({kind:e})=>`A ${e}ter cannot be a generator.`,ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncFunction:"'await' is only allowed within async functions.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:({kind:e})=>`Missing initializer in ${e} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:({exportName:e})=>`\`${e}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",DynamicImportPhaseRequiresImportExpressions:({phase:e})=>`'import.${e}(...)' can only be parsed when using the 'createImportExpressions' option.`,ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName:e,exportName:t})=>`A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${e}' as '${t}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:e})=>`'${"ForInStatement"===e?"for-in":"for-of"}' loop variable declaration may not have an initializer.`,ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:({type:e})=>`Unsyntactic ${"BreakStatement"===e?"break":"continue"}.`,IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportAttributesUseAssert:"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",ImportBindingIsString:({importName:e})=>`A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${e}" as foo }\`?`,ImportCallArity:"`import()` requires exactly one or two arguments.",ImportCallNotNewExpression:"Cannot use new with import(...).",ImportCallSpreadArgument:"`...` is not allowed in `import()`.",ImportJSONBindingNotDefault:"A JSON module can only be imported with `default`.",ImportReflectionHasAssertion:"`import module x` cannot have assertions.",ImportReflectionNotBinding:'Only `import module x from "./module"` is valid.',IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix:e})=>`Expected number in radix ${e}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:e})=>`Escape sequence in keyword ${e}.`,InvalidIdentifier:({identifierName:e})=>`Invalid identifier ${e}.`,InvalidLhs:({ancestor:e})=>`Invalid left-hand side in ${c(e)}.`,InvalidLhsBinding:({ancestor:e})=>`Binding invalid left-hand side in ${c(e)}.`,InvalidLhsOptionalChaining:({ancestor:e})=>`Invalid optional chaining in the left-hand side of ${c(e)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:e})=>`Unexpected character '${e}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:e})=>`Private name #${e} is not defined.`,InvalidPropertyBindingPattern:"Binding member expression.",InvalidRecordProperty:"Only properties and spread elements are allowed in record definitions.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:({labelName:e})=>`Label '${e}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:({missingPlugin:e})=>`This experimental syntax requires enabling the parser plugin: ${e.map((e=>JSON.stringify(e))).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:e})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${e.map((e=>JSON.stringify(e))).join(", ")}.`,MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeDifferentFromType:"The only accepted module attribute is `type`.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:({key:e})=>`Duplicate key "${e}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:e})=>`An export name cannot include a lone surrogate, found '\\u${e.toString(16)}'.`,ModuleExportUndefined:({localName:e})=>`Export '${e}' is not defined.`,MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:({identifierName:e})=>`Private names are only allowed in property accesses (\`obj.#${e}\`) or in \`in\` expressions (\`#${e} in obj\`).`,PrivateNameRedeclaration:({identifierName:e})=>`Duplicate private name #${e}.`,RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",RecordNoProto:"'__proto__' is not allowed in Record expressions.",RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode code, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:({keyword:e})=>`Unexpected keyword '${e}'.`,UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:({reservedWord:e})=>`Unexpected reserved word '${e}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:e,unexpected:t})=>`Unexpected token${t?` '${t}'.`:""}${e?`, expected "${e}"`:""}`,UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script`.",UnsupportedBind:"Binding should be performed on object property.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:({target:e,onlyValidPropertyName:t})=>`The only valid meta property for ${e} is ${e}.${t}.`,UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:e})=>`Identifier '${e}' has already been declared.`,YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."};const u=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]);var d=Object.assign({PipeBodyIsTighter:"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",PipeTopicRequiresHackPipes:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:({token:e})=>`Invalid topic token ${e}. In order to use ${e} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${e}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:e})=>`Hack-style pipe body cannot be an unparenthesized ${c({type:e})}; please wrap it in parentheses.`},{PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression.",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression.",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference.",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding.",PrimaryTopicRequiresSmartPipeline:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'});const f=["message"];function h(e,t,r){Object.defineProperty(e,t,{enumerable:!1,configurable:!0,value:r})}function m({toMessage:e,code:t,reasonCode:r,syntaxPlugin:s}){const i="MissingPlugin"===r||"MissingOneOfPlugins"===r;{const e={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};e[r]&&(r=e[r])}return function a(o,l){const c=new SyntaxError;return c.code=t,c.reasonCode=r,c.loc=o,c.pos=o.index,c.syntaxPlugin=s,i&&(c.missingPlugin=l.missingPlugin),h(c,"clone",(function(e={}){var t;const{line:r,column:s,index:i}=null!=(t=e.loc)?t:o;return a(new n(r,s,i),Object.assign({},l,e.details))})),h(c,"details",l),Object.defineProperty(c,"message",{configurable:!0,get(){const t=`${e(l)} (${o.line}:${o.column})`;return this.message=t,t},set(e){Object.defineProperty(this,"message",{value:e,writable:!0})}}),c}}function y(e,t){if(Array.isArray(e))return t=>y(t,e[0]);const n={};for(const s of Object.keys(e)){const i=e[s],a="string"==typeof i?{message:()=>i}:"function"==typeof i?{message:i}:i,{message:o}=a,l=r(a,f),c="string"==typeof o?()=>o:o;n[s]=m(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:s,toMessage:c},t?{syntaxPlugin:t}:{},l))}return n}const g=Object.assign({},y(o),y(p),y({StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:e})=>`Assigning to '${e}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:e})=>`Binding '${e}' in strict mode.`,StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block.",StrictNumericEscape:"The only valid numeric escape in strict mode is '\\0'.",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode.",StrictWith:"'with' in strict mode."}),y`pipelineOperator`(d)),{defineProperty:b}=Object,v=(e,t)=>{e&&b(e,t,{enumerable:!1,value:e[t]})};function T(e){return v(e.loc.start,"index"),v(e.loc.end,"index"),e}class x{constructor(e,t){this.token=void 0,this.preserveSpace=void 0,this.token=e,this.preserveSpace=!!t}}const S={brace:new x("{"),j_oTag:new x("<tag"),j_cTag:new x("</tag"),j_expr:new x("<tag>...</tag>",!0)};S.template=new x("`",!0);const E=!0,P=!0,A=!0,w=!0,C=!0;class O{constructor(e,t={}){this.label=void 0,this.keyword=void 0,this.beforeExpr=void 0,this.startsExpr=void 0,this.rightAssociative=void 0,this.isLoop=void 0,this.isAssign=void 0,this.prefix=void 0,this.postfix=void 0,this.binop=void 0,this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.rightAssociative=!!t.rightAssociative,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=null!=t.binop?t.binop:null,this.updateContext=null}}const I=new Map;function N(e,t={}){t.keyword=e;const r=R(e,t);return I.set(e,r),r}function k(e,t){return R(e,{beforeExpr:E,binop:t})}let _=-1;const D=[],j=[],B=[],M=[],L=[],F=[];function R(e,t={}){var r,n,s,i;return++_,j.push(e),B.push(null!=(r=t.binop)?r:-1),M.push(null!=(n=t.beforeExpr)&&n),L.push(null!=(s=t.startsExpr)&&s),F.push(null!=(i=t.prefix)&&i),D.push(new O(e,t)),_}function U(e,t={}){var r,n,s,i;return++_,I.set(e,_),j.push(e),B.push(null!=(r=t.binop)?r:-1),M.push(null!=(n=t.beforeExpr)&&n),L.push(null!=(s=t.startsExpr)&&s),F.push(null!=(i=t.prefix)&&i),D.push(new O("name",t)),_}const V={bracketL:R("[",{beforeExpr:E,startsExpr:P}),bracketHashL:R("#[",{beforeExpr:E,startsExpr:P}),bracketBarL:R("[|",{beforeExpr:E,startsExpr:P}),bracketR:R("]"),bracketBarR:R("|]"),braceL:R("{",{beforeExpr:E,startsExpr:P}),braceBarL:R("{|",{beforeExpr:E,startsExpr:P}),braceHashL:R("#{",{beforeExpr:E,startsExpr:P}),braceR:R("}"),braceBarR:R("|}"),parenL:R("(",{beforeExpr:E,startsExpr:P}),parenR:R(")"),comma:R(",",{beforeExpr:E}),semi:R(";",{beforeExpr:E}),colon:R(":",{beforeExpr:E}),doubleColon:R("::",{beforeExpr:E}),dot:R("."),question:R("?",{beforeExpr:E}),questionDot:R("?."),arrow:R("=>",{beforeExpr:E}),template:R("template"),ellipsis:R("...",{beforeExpr:E}),backQuote:R("`",{startsExpr:P}),dollarBraceL:R("${",{beforeExpr:E,startsExpr:P}),templateTail:R("...`",{startsExpr:P}),templateNonTail:R("...${",{beforeExpr:E,startsExpr:P}),at:R("@"),hash:R("#",{startsExpr:P}),interpreterDirective:R("#!..."),eq:R("=",{beforeExpr:E,isAssign:w}),assign:R("_=",{beforeExpr:E,isAssign:w}),slashAssign:R("_=",{beforeExpr:E,isAssign:w}),xorAssign:R("_=",{beforeExpr:E,isAssign:w}),moduloAssign:R("_=",{beforeExpr:E,isAssign:w}),incDec:R("++/--",{prefix:C,postfix:!0,startsExpr:P}),bang:R("!",{beforeExpr:E,prefix:C,startsExpr:P}),tilde:R("~",{beforeExpr:E,prefix:C,startsExpr:P}),doubleCaret:R("^^",{startsExpr:P}),doubleAt:R("@@",{startsExpr:P}),pipeline:k("|>",0),nullishCoalescing:k("??",1),logicalOR:k("||",1),logicalAND:k("&&",2),bitwiseOR:k("|",3),bitwiseXOR:k("^",4),bitwiseAND:k("&",5),equality:k("==/!=/===/!==",6),lt:k("</>/<=/>=",7),gt:k("</>/<=/>=",7),relational:k("</>/<=/>=",7),bitShift:k("<</>>/>>>",8),bitShiftL:k("<</>>/>>>",8),bitShiftR:k("<</>>/>>>",8),plusMin:R("+/-",{beforeExpr:E,binop:9,prefix:C,startsExpr:P}),modulo:R("%",{binop:10,startsExpr:P}),star:R("*",{binop:10}),slash:k("/",10),exponent:R("**",{beforeExpr:E,binop:11,rightAssociative:!0}),_in:N("in",{beforeExpr:E,binop:7}),_instanceof:N("instanceof",{beforeExpr:E,binop:7}),_break:N("break"),_case:N("case",{beforeExpr:E}),_catch:N("catch"),_continue:N("continue"),_debugger:N("debugger"),_default:N("default",{beforeExpr:E}),_else:N("else",{beforeExpr:E}),_finally:N("finally"),_function:N("function",{startsExpr:P}),_if:N("if"),_return:N("return",{beforeExpr:E}),_switch:N("switch"),_throw:N("throw",{beforeExpr:E,prefix:C,startsExpr:P}),_try:N("try"),_var:N("var"),_const:N("const"),_with:N("with"),_new:N("new",{beforeExpr:E,startsExpr:P}),_this:N("this",{startsExpr:P}),_super:N("super",{startsExpr:P}),_class:N("class",{startsExpr:P}),_extends:N("extends",{beforeExpr:E}),_export:N("export"),_import:N("import",{startsExpr:P}),_null:N("null",{startsExpr:P}),_true:N("true",{startsExpr:P}),_false:N("false",{startsExpr:P}),_typeof:N("typeof",{beforeExpr:E,prefix:C,startsExpr:P}),_void:N("void",{beforeExpr:E,prefix:C,startsExpr:P}),_delete:N("delete",{beforeExpr:E,prefix:C,startsExpr:P}),_do:N("do",{isLoop:A,beforeExpr:E}),_for:N("for",{isLoop:A}),_while:N("while",{isLoop:A}),_as:U("as",{startsExpr:P}),_assert:U("assert",{startsExpr:P}),_async:U("async",{startsExpr:P}),_await:U("await",{startsExpr:P}),_defer:U("defer",{startsExpr:P}),_from:U("from",{startsExpr:P}),_get:U("get",{startsExpr:P}),_let:U("let",{startsExpr:P}),_meta:U("meta",{startsExpr:P}),_of:U("of",{startsExpr:P}),_sent:U("sent",{startsExpr:P}),_set:U("set",{startsExpr:P}),_source:U("source",{startsExpr:P}),_static:U("static",{startsExpr:P}),_using:U("using",{startsExpr:P}),_yield:U("yield",{startsExpr:P}),_asserts:U("asserts",{startsExpr:P}),_checks:U("checks",{startsExpr:P}),_exports:U("exports",{startsExpr:P}),_global:U("global",{startsExpr:P}),_implements:U("implements",{startsExpr:P}),_intrinsic:U("intrinsic",{startsExpr:P}),_infer:U("infer",{startsExpr:P}),_is:U("is",{startsExpr:P}),_mixins:U("mixins",{startsExpr:P}),_proto:U("proto",{startsExpr:P}),_require:U("require",{startsExpr:P}),_satisfies:U("satisfies",{startsExpr:P}),_keyof:U("keyof",{startsExpr:P}),_readonly:U("readonly",{startsExpr:P}),_unique:U("unique",{startsExpr:P}),_abstract:U("abstract",{startsExpr:P}),_declare:U("declare",{startsExpr:P}),_enum:U("enum",{startsExpr:P}),_module:U("module",{startsExpr:P}),_namespace:U("namespace",{startsExpr:P}),_interface:U("interface",{startsExpr:P}),_type:U("type",{startsExpr:P}),_opaque:U("opaque",{startsExpr:P}),name:R("name",{startsExpr:P}),placeholder:R("%%",{startsExpr:!0}),string:R("string",{startsExpr:P}),num:R("num",{startsExpr:P}),bigint:R("bigint",{startsExpr:P}),decimal:R("decimal",{startsExpr:P}),regexp:R("regexp",{startsExpr:P}),privateName:R("#name",{startsExpr:P}),eof:R("eof"),jsxName:R("jsxName"),jsxText:R("jsxText",{beforeExpr:!0}),jsxTagStart:R("jsxTagStart",{startsExpr:!0}),jsxTagEnd:R("jsxTagEnd")};function q(e){return e>=93&&e<=133}function W(e){return e>=58&&e<=133}function K(e){return e>=58&&e<=137}function $(e){return L[e]}function G(e){return e>=129&&e<=131}function H(e){return e>=58&&e<=92}function Y(e){return j[e]}function J(e){return B[e]}function z(e){return e>=24&&e<=25}function X(e){return D[e]}D[8].updateContext=e=>{e.pop()},D[5].updateContext=D[7].updateContext=D[23].updateContext=e=>{e.push(S.brace)},D[22].updateContext=e=>{e[e.length-1]===S.template?e.pop():e.push(S.template)},D[143].updateContext=e=>{e.push(S.j_expr,S.j_oTag)};let Q="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",Z="·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・";const ee=new RegExp("["+Q+"]"),te=new RegExp("["+Q+Z+"]");Q=Z=null;const re=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],ne=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239];function se(e,t){let r=65536;for(let n=0,s=t.length;n<s;n+=2){if(r+=t[n],r>e)return!1;if(r+=t[n+1],r>=e)return!0}return!1}function ie(e){return e<65?36===e:e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&ee.test(String.fromCharCode(e)):se(e,re)))}function ae(e){return e<48?36===e:e<58||!(e<65)&&(e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&te.test(String.fromCharCode(e)):se(e,re)||se(e,ne))))}const oe=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"]),le=new Set(["implements","interface","let","package","private","protected","public","static","yield"]),ce=new Set(["eval","arguments"]);function pe(e,t){return t&&"await"===e||"enum"===e}function ue(e,t){return pe(e,t)||le.has(e)}function de(e){return ce.has(e)}function fe(e,t){return ue(e,t)||de(e)}const he=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);class me{constructor(e){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=e}}class ye{constructor(e,t){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=e,this.inModule=t}get inTopLevel(){return(1&this.currentScope().flags)>0}get inFunction(){return(2&this.currentVarScopeFlags())>0}get allowSuper(){return(16&this.currentThisScopeFlags())>0}get allowDirectSuper(){return(32&this.currentThisScopeFlags())>0}get inClass(){return(64&this.currentThisScopeFlags())>0}get inClassAndNotInNonArrowFunction(){const e=this.currentThisScopeFlags();return(64&e)>0&&!(2&e)}get inStaticBlock(){for(let e=this.scopeStack.length-1;;e--){const{flags:t}=this.scopeStack[e];if(128&t)return!0;if(451&t)return!1}}get inNonArrowFunction(){return(2&this.currentThisScopeFlags())>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(e){return new me(e)}enter(e){this.scopeStack.push(this.createScope(e))}exit(){return this.scopeStack.pop().flags}treatFunctionsAsVarInScope(e){return!!(130&e.flags||!this.parser.inModule&&1&e.flags)}declareName(e,t,r){let n=this.currentScope();if(8&t||16&t){this.checkRedeclarationInScope(n,e,t,r);let s=n.names.get(e)||0;16&t?s|=4:(n.firstLexicalName||(n.firstLexicalName=e),s|=2),n.names.set(e,s),8&t&&this.maybeExportDefined(n,e)}else if(4&t)for(let s=this.scopeStack.length-1;s>=0&&(n=this.scopeStack[s],this.checkRedeclarationInScope(n,e,t,r),n.names.set(e,1|(n.names.get(e)||0)),this.maybeExportDefined(n,e),!(387&n.flags));--s);this.parser.inModule&&1&n.flags&&this.undefinedExports.delete(e)}maybeExportDefined(e,t){this.parser.inModule&&1&e.flags&&this.undefinedExports.delete(t)}checkRedeclarationInScope(e,t,r,n){this.isRedeclaredInScope(e,t,r)&&this.parser.raise(g.VarRedeclaration,n,{identifierName:t})}isRedeclaredInScope(e,t,r){if(!(1&r))return!1;if(8&r)return e.names.has(t);const n=e.names.get(t);return 16&r?(2&n)>0||!this.treatFunctionsAsVarInScope(e)&&(1&n)>0:(2&n)>0&&!(8&e.flags&&e.firstLexicalName===t)||!this.treatFunctionsAsVarInScope(e)&&(4&n)>0}checkLocalExport(e){const{name:t}=e;this.scopeStack[0].names.has(t)||this.undefinedExports.set(t,e.loc.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let e=this.scopeStack.length-1;;e--){const{flags:t}=this.scopeStack[e];if(387&t)return t}}currentThisScopeFlags(){for(let e=this.scopeStack.length-1;;e--){const{flags:t}=this.scopeStack[e];if(451&t&&!(4&t))return t}}}class ge extends me{constructor(...e){super(...e),this.declareFunctions=new Set}}class be extends ye{createScope(e){return new ge(e)}declareName(e,t,r){const n=this.currentScope();if(2048&t)return this.checkRedeclarationInScope(n,e,t,r),this.maybeExportDefined(n,e),void n.declareFunctions.add(e);super.declareName(e,t,r)}isRedeclaredInScope(e,t,r){if(super.isRedeclaredInScope(e,t,r))return!0;if(2048&r&&!e.declareFunctions.has(t)){const r=e.names.get(t);return(4&r)>0||(2&r)>0}return!1}checkLocalExport(e){this.scopeStack[0].declareFunctions.has(e.name)||super.checkLocalExport(e)}}class ve{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}sourceToOffsetPos(e){return e+this.startIndex}offsetToSourcePos(e){return e-this.startIndex}hasPlugin(e){if("string"==typeof e)return this.plugins.has(e);{const[t,r]=e;if(!this.hasPlugin(t))return!1;const n=this.plugins.get(t);for(const e of Object.keys(r))if((null==n?void 0:n[e])!==r[e])return!1;return!0}}getPluginOption(e,t){var r;return null==(r=this.plugins.get(e))?void 0:r[t]}}function Te(e,t){void 0===e.trailingComments?e.trailingComments=t:e.trailingComments.unshift(...t)}function xe(e,t){void 0===e.innerComments?e.innerComments=t:e.innerComments.unshift(...t)}function Se(e,t,r){let n=null,s=t.length;for(;null===n&&s>0;)n=t[--s];null===n||n.start>r.start?xe(e,r.comments):Te(n,r.comments)}class Ee extends ve{addComment(e){this.filename&&(e.loc.filename=this.filename);const{commentsLen:t}=this.state;this.comments.length!==t&&(this.comments.length=t),this.comments.push(e),this.state.commentsLen++}processComment(e){const{commentStack:t}=this.state,r=t.length;if(0===r)return;let n=r-1;const s=t[n];s.start===e.end&&(s.leadingNode=e,n--);const{start:i}=e;for(;n>=0;n--){const r=t[n],s=r.end;if(!(s>i)){s===i&&(r.trailingNode=e);break}r.containingNode=e,this.finalizeComment(r),t.splice(n,1)}}finalizeComment(e){const{comments:t}=e;if(null!==e.leadingNode||null!==e.trailingNode)null!==e.leadingNode&&Te(e.leadingNode,t),null!==e.trailingNode&&function(e,t){void 0===e.leadingComments?e.leadingComments=t:e.leadingComments.unshift(...t)}(e.trailingNode,t);else{const{containingNode:r,start:n}=e;if(44===this.input.charCodeAt(this.offsetToSourcePos(n)-1))switch(r.type){case"ObjectExpression":case"ObjectPattern":case"RecordExpression":Se(r,r.properties,e);break;case"CallExpression":case"OptionalCallExpression":Se(r,r.arguments,e);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":Se(r,r.params,e);break;case"ArrayExpression":case"ArrayPattern":case"TupleExpression":Se(r,r.elements,e);break;case"ExportNamedDeclaration":case"ImportDeclaration":Se(r,r.specifiers,e);break;case"TSEnumDeclaration":case"TSEnumBody":Se(r,r.members,e);break;default:xe(r,t)}else xe(r,t)}}finalizeRemainingComments(){const{commentStack:e}=this.state;for(let t=e.length-1;t>=0;t--)this.finalizeComment(e[t]);this.state.commentStack=[]}resetPreviousNodeTrailingComments(e){const{commentStack:t}=this.state,{length:r}=t;if(0===r)return;const n=t[r-1];n.leadingNode===e&&(n.leadingNode=null)}resetPreviousIdentifierLeadingComments(e){const{commentStack:t}=this.state,{length:r}=t;0!==r&&(t[r-1].trailingNode===e?t[r-1].trailingNode=null:r>=2&&t[r-2].trailingNode===e&&(t[r-2].trailingNode=null))}takeSurroundingComments(e,t,r){const{commentStack:n}=this.state,s=n.length;if(0===s)return;let i=s-1;for(;i>=0;i--){const s=n[i],a=s.end;if(s.start===r)s.leadingNode=e;else if(a===t)s.trailingNode=e;else if(a<t)break}}}const Pe=new RegExp(/\r\n|[\r\n\u2028\u2029]/.source,"g");function Ae(e){switch(e){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function we(e,t,r){for(let n=t;n<r;n++)if(Ae(e.charCodeAt(n)))return!0;return!1}const Ce=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,Oe=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function Ie(e){switch(e){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}class Ne{constructor(){this.flags=1024,this.startIndex=void 0,this.curLine=void 0,this.lineStart=void 0,this.startLoc=void 0,this.endLoc=void 0,this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.labels=[],this.commentsLen=0,this.commentStack=[],this.pos=0,this.type=140,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.context=[S.brace],this.firstInvalidTemplateEscapePos=null,this.strictErrors=new Map,this.tokensLength=0}get strict(){return(1&this.flags)>0}set strict(e){e?this.flags|=1:this.flags&=-2}init({strictMode:e,sourceType:t,startIndex:r,startLine:s,startColumn:i}){this.strict=!1!==e&&(!0===e||"module"===t),this.startIndex=r,this.curLine=s,this.lineStart=-i,this.startLoc=this.endLoc=new n(s,i,r)}get maybeInArrowParameters(){return(2&this.flags)>0}set maybeInArrowParameters(e){e?this.flags|=2:this.flags&=-3}get inType(){return(4&this.flags)>0}set inType(e){e?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(8&this.flags)>0}set noAnonFunctionType(e){e?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(16&this.flags)>0}set hasFlowComment(e){e?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(32&this.flags)>0}set isAmbientContext(e){e?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(64&this.flags)>0}set inAbstractClass(e){e?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(128&this.flags)>0}set inDisallowConditionalTypesContext(e){e?this.flags|=128:this.flags&=-129}get soloAwait(){return(256&this.flags)>0}set soloAwait(e){e?this.flags|=256:this.flags&=-257}get inFSharpPipelineDirectBody(){return(512&this.flags)>0}set inFSharpPipelineDirectBody(e){e?this.flags|=512:this.flags&=-513}get canStartJSXElement(){return(1024&this.flags)>0}set canStartJSXElement(e){e?this.flags|=1024:this.flags&=-1025}get containsEsc(){return(2048&this.flags)>0}set containsEsc(e){e?this.flags|=2048:this.flags&=-2049}get hasTopLevelAwait(){return(4096&this.flags)>0}set hasTopLevelAwait(e){e?this.flags|=4096:this.flags&=-4097}curPosition(){return new n(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){const e=new Ne;return e.flags=this.flags,e.startIndex=this.startIndex,e.curLine=this.curLine,e.lineStart=this.lineStart,e.startLoc=this.startLoc,e.endLoc=this.endLoc,e.errors=this.errors.slice(),e.potentialArrowAt=this.potentialArrowAt,e.noArrowAt=this.noArrowAt.slice(),e.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),e.topicContext=this.topicContext,e.labels=this.labels.slice(),e.commentsLen=this.commentsLen,e.commentStack=this.commentStack.slice(),e.pos=this.pos,e.type=this.type,e.value=this.value,e.start=this.start,e.end=this.end,e.lastTokEndLoc=this.lastTokEndLoc,e.lastTokStartLoc=this.lastTokStartLoc,e.context=this.context.slice(),e.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,e.strictErrors=this.strictErrors,e.tokensLength=this.tokensLength,e}}var ke=function(e){return e>=48&&e<=57};const _e={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},De={bin:e=>48===e||49===e,oct:e=>e>=48&&e<=55,dec:e=>e>=48&&e<=57,hex:e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102};function je(e,t,r,n,s,i){const a=r,o=n,l=s;let c="",p=null,u=r;const{length:d}=t;for(;;){if(r>=d){i.unterminated(a,o,l),c+=t.slice(u,r);break}const f=t.charCodeAt(r);if(Be(e,f,t,r)){c+=t.slice(u,r);break}if(92===f){c+=t.slice(u,r);const a=Me(t,r,n,s,"template"===e,i);null!==a.ch||p?c+=a.ch:p={pos:r,lineStart:n,curLine:s},({pos:r,lineStart:n,curLine:s}=a),u=r}else 8232===f||8233===f?(++s,n=++r):10===f||13===f?"template"===e?(c+=t.slice(u,r)+"\n",++r,13===f&&10===t.charCodeAt(r)&&++r,++s,u=n=r):i.unterminated(a,o,l):++r}return{pos:r,str:c,firstInvalidLoc:p,lineStart:n,curLine:s,containsInvalid:!!p}}function Be(e,t,r,n){return"template"===e?96===t||36===t&&123===r.charCodeAt(n+1):t===("double"===e?34:39)}function Me(e,t,r,n,s,i){const a=!s;t++;const o=e=>({pos:t,ch:e,lineStart:r,curLine:n}),l=e.charCodeAt(t++);switch(l){case 110:return o("\n");case 114:return o("\r");case 120:{let s;return({code:s,pos:t}=Le(e,t,r,n,2,!1,a,i)),o(null===s?null:String.fromCharCode(s))}case 117:{let s;return({code:s,pos:t}=Re(e,t,r,n,a,i)),o(null===s?null:String.fromCodePoint(s))}case 116:return o("\t");case 98:return o("\b");case 118:return o("\v");case 102:return o("\f");case 13:10===e.charCodeAt(t)&&++t;case 10:r=t,++n;case 8232:case 8233:return o("");case 56:case 57:if(s)return o(null);i.strictNumericEscape(t-1,r,n);default:if(l>=48&&l<=55){const a=t-1;let l=/^[0-7]+/.exec(e.slice(a,t+2))[0],c=parseInt(l,8);c>255&&(l=l.slice(0,-1),c=parseInt(l,8)),t+=l.length-1;const p=e.charCodeAt(t);if("0"!==l||56===p||57===p){if(s)return o(null);i.strictNumericEscape(a,r,n)}return o(String.fromCharCode(c))}return o(String.fromCharCode(l))}}function Le(e,t,r,n,s,i,a,o){const l=t;let c;return({n:c,pos:t}=Fe(e,t,r,n,16,s,i,!1,o,!a)),null===c&&(a?o.invalidEscapeSequence(l,r,n):t=l-1),{code:c,pos:t}}function Fe(e,t,r,n,s,i,a,o,l,c){const p=t,u=16===s?_e.hex:_e.decBinOct,d=16===s?De.hex:10===s?De.dec:8===s?De.oct:De.bin;let f=!1,h=0;for(let p=0,m=null==i?1/0:i;p<m;++p){const i=e.charCodeAt(t);let p;if(95!==i||"bail"===o){if(p=i>=97?i-97+10:i>=65?i-65+10:ke(i)?i-48:1/0,p>=s){if(p<=9&&c)return{n:null,pos:t};if(p<=9&&l.invalidDigit(t,r,n,s))p=0;else{if(!a)break;p=0,f=!0}}++t,h=h*s+p}else{const s=e.charCodeAt(t-1),i=e.charCodeAt(t+1);if(o){if(Number.isNaN(i)||!d(i)||u.has(s)||u.has(i)){if(c)return{n:null,pos:t};l.unexpectedNumericSeparator(t,r,n)}}else{if(c)return{n:null,pos:t};l.numericSeparatorInEscapeSequence(t,r,n)}++t}}return t===p||null!=i&&t-p!==i||f?{n:null,pos:t}:{n:h,pos:t}}function Re(e,t,r,n,s,i){let a;if(123===e.charCodeAt(t)){if(++t,({code:a,pos:t}=Le(e,t,r,n,e.indexOf("}",t)-t,!0,s,i)),++t,null!==a&&a>1114111){if(!s)return{code:null,pos:t};i.invalidCodePoint(t,r,n)}}else({code:a,pos:t}=Le(e,t,r,n,4,!1,s,i));return{code:a,pos:t}}function Ue(e,t,r){return new n(r,e-t,e)}const Ve=new Set([103,109,115,105,121,117,100,118]);class qe{constructor(e){const t=e.startIndex||0;this.type=e.type,this.value=e.value,this.start=t+e.start,this.end=t+e.end,this.loc=new s(e.startLoc,e.endLoc)}}class We extends Ee{constructor(e,t){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(e,t,r,n)=>!!(1024&this.optionFlags)&&(this.raise(g.InvalidDigit,Ue(e,t,r),{radix:n}),!0),numericSeparatorInEscapeSequence:this.errorBuilder(g.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(g.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(g.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(g.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(e,t,r)=>{this.recordStrictModeErrors(g.StrictNumericEscape,Ue(e,t,r))},unterminated:(e,t,r)=>{throw this.raise(g.UnterminatedString,Ue(e-1,t,r))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(g.StrictNumericEscape),unterminated:(e,t,r)=>{throw this.raise(g.UnterminatedTemplate,Ue(e,t,r))}}),this.state=new Ne,this.state.init(e),this.input=t,this.length=t.length,this.comments=[],this.isLookahead=!1}pushToken(e){this.tokens.length=this.state.tokensLength,this.tokens.push(e),++this.state.tokensLength}next(){this.checkKeywordEscapes(),128&this.optionFlags&&this.pushToken(new qe(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(e){return!!this.match(e)&&(this.next(),!0)}match(e){return this.state.type===e}createLookaheadState(e){return{pos:e.pos,value:null,type:e.type,start:e.start,end:e.end,context:[this.curContext()],inType:e.inType,startLoc:e.startLoc,lastTokEndLoc:e.lastTokEndLoc,curLine:e.curLine,lineStart:e.lineStart,curPosition:e.curPosition}}lookahead(){const e=this.state;this.state=this.createLookaheadState(e),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;const t=this.state;return this.state=e,t}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(e){return Ce.lastIndex=e,Ce.test(this.input)?Ce.lastIndex:e}lookaheadCharCode(){return this.input.charCodeAt(this.nextTokenStart())}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(e){return Oe.lastIndex=e,Oe.test(this.input)?Oe.lastIndex:e}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(e){let t=this.input.charCodeAt(e);if(55296==(64512&t)&&++e<this.input.length){const r=this.input.charCodeAt(e);56320==(64512&r)&&(t=65536+((1023&t)<<10)+(1023&r))}return t}setStrict(e){this.state.strict=e,e&&(this.state.strictErrors.forEach((([e,t])=>this.raise(e,t))),this.state.strictErrors.clear())}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){this.skipSpace(),this.state.start=this.state.pos,this.isLookahead||(this.state.startLoc=this.state.curPosition()),this.state.pos>=this.length?this.finishToken(140):this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(e){let t;this.isLookahead||(t=this.state.curPosition());const r=this.state.pos,n=this.input.indexOf(e,r+2);if(-1===n)throw this.raise(g.UnterminatedComment,this.state.curPosition());for(this.state.pos=n+e.length,Pe.lastIndex=r+2;Pe.test(this.input)&&Pe.lastIndex<=n;)++this.state.curLine,this.state.lineStart=Pe.lastIndex;if(this.isLookahead)return;const i={type:"CommentBlock",value:this.input.slice(r+2,n),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(n+e.length),loc:new s(t,this.state.curPosition())};return 128&this.optionFlags&&this.pushToken(i),i}skipLineComment(e){const t=this.state.pos;let r;this.isLookahead||(r=this.state.curPosition());let n=this.input.charCodeAt(this.state.pos+=e);if(this.state.pos<this.length)for(;!Ae(n)&&++this.state.pos<this.length;)n=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;const i=this.state.pos,a={type:"CommentLine",value:this.input.slice(t+e,i),start:this.sourceToOffsetPos(t),end:this.sourceToOffsetPos(i),loc:new s(r,this.state.curPosition())};return 128&this.optionFlags&&this.pushToken(a),a}skipSpace(){const e=this.state.pos,t=2048&this.optionFlags?[]:null;e:for(;this.state.pos<this.length;){const r=this.input.charCodeAt(this.state.pos);switch(r){case 32:case 160:case 9:++this.state.pos;break;case 13:10===this.input.charCodeAt(this.state.pos+1)&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{const e=this.skipBlockComment("*/");void 0!==e&&(this.addComment(e),null==t||t.push(e));break}case 47:{const e=this.skipLineComment(2);void 0!==e&&(this.addComment(e),null==t||t.push(e));break}default:break e}break;default:if(Ie(r))++this.state.pos;else if(45===r&&!this.inModule&&4096&this.optionFlags){const r=this.state.pos;if(45!==this.input.charCodeAt(r+1)||62!==this.input.charCodeAt(r+2)||!(0===e||this.state.lineStart>e))break e;{const e=this.skipLineComment(3);void 0!==e&&(this.addComment(e),null==t||t.push(e))}}else{if(60!==r||this.inModule||!(4096&this.optionFlags))break e;{const e=this.state.pos;if(33!==this.input.charCodeAt(e+1)||45!==this.input.charCodeAt(e+2)||45!==this.input.charCodeAt(e+3))break e;{const e=this.skipLineComment(4);void 0!==e&&(this.addComment(e),null==t||t.push(e))}}}}}if((null==t?void 0:t.length)>0){const r=this.state.pos,n={start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(r),comments:t,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(n)}}finishToken(e,t){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();const r=this.state.type;this.state.type=e,this.state.value=t,this.isLookahead||this.updateContext(r)}replaceToken(e){this.state.type=e,this.updateContext()}readToken_numberSign(){if(0===this.state.pos&&this.readToken_interpreter())return;const e=this.state.pos+1,t=this.codePointAtPos(e);if(t>=48&&t<=57)throw this.raise(g.UnexpectedDigitAfterHash,this.state.curPosition());if(123===t||91===t&&this.hasPlugin("recordAndTuple")){if(this.expectPlugin("recordAndTuple"),"bar"===this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(123===t?g.RecordExpressionHashIncorrectStartSyntaxType:g.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,123===t?this.finishToken(7):this.finishToken(1)}else ie(t)?(++this.state.pos,this.finishToken(139,this.readWord1(t))):92===t?(++this.state.pos,this.finishToken(139,this.readWord1())):this.finishOp(27,1)}readToken_dot(){const e=this.input.charCodeAt(this.state.pos+1);e>=48&&e<=57?this.readNumber(!0):46===e&&46===this.input.charCodeAt(this.state.pos+2)?(this.state.pos+=3,this.finishToken(21)):(++this.state.pos,this.finishToken(16))}readToken_slash(){61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(31,2):this.finishOp(56,1)}readToken_interpreter(){if(0!==this.state.pos||this.length<2)return!1;let e=this.input.charCodeAt(this.state.pos+1);if(33!==e)return!1;const t=this.state.pos;for(this.state.pos+=1;!Ae(e)&&++this.state.pos<this.length;)e=this.input.charCodeAt(this.state.pos);const r=this.input.slice(t+2,this.state.pos);return this.finishToken(28,r),!0}readToken_mult_modulo(e){let t=42===e?55:54,r=1,n=this.input.charCodeAt(this.state.pos+1);42===e&&42===n&&(r++,n=this.input.charCodeAt(this.state.pos+2),t=57),61!==n||this.state.inType||(r++,t=37===e?33:30),this.finishOp(t,r)}readToken_pipe_amp(e){const t=this.input.charCodeAt(this.state.pos+1);if(t!==e){if(124===e){if(62===t)return void this.finishOp(39,2);if(this.hasPlugin("recordAndTuple")&&125===t){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(g.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition());return this.state.pos+=2,void this.finishToken(9)}if(this.hasPlugin("recordAndTuple")&&93===t){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(g.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition());return this.state.pos+=2,void this.finishToken(4)}}61!==t?this.finishOp(124===e?43:45,1):this.finishOp(30,2)}else 61===this.input.charCodeAt(this.state.pos+2)?this.finishOp(30,3):this.finishOp(124===e?41:42,2)}readToken_caret(){const e=this.input.charCodeAt(this.state.pos+1);61!==e||this.state.inType?94===e&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])?(this.finishOp(37,2),94===this.input.codePointAt(this.state.pos)&&this.unexpected()):this.finishOp(44,1):this.finishOp(32,2)}readToken_atSign(){64===this.input.charCodeAt(this.state.pos+1)&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])?this.finishOp(38,2):this.finishOp(26,1)}readToken_plus_min(e){const t=this.input.charCodeAt(this.state.pos+1);t!==e?61===t?this.finishOp(30,2):this.finishOp(53,1):this.finishOp(34,2)}readToken_lt(){const{pos:e}=this.state,t=this.input.charCodeAt(e+1);if(60===t)return 61===this.input.charCodeAt(e+2)?void this.finishOp(30,3):void this.finishOp(51,2);61!==t?this.finishOp(47,1):this.finishOp(49,2)}readToken_gt(){const{pos:e}=this.state,t=this.input.charCodeAt(e+1);if(62===t){const t=62===this.input.charCodeAt(e+2)?3:2;return 61===this.input.charCodeAt(e+t)?void this.finishOp(30,t+1):void this.finishOp(52,t)}61!==t?this.finishOp(48,1):this.finishOp(49,2)}readToken_eq_excl(e){const t=this.input.charCodeAt(this.state.pos+1);if(61!==t)return 61===e&&62===t?(this.state.pos+=2,void this.finishToken(19)):void this.finishOp(61===e?29:35,1);this.finishOp(46,61===this.input.charCodeAt(this.state.pos+2)?3:2)}readToken_question(){const e=this.input.charCodeAt(this.state.pos+1),t=this.input.charCodeAt(this.state.pos+2);63===e?61===t?this.finishOp(30,3):this.finishOp(40,2):46!==e||t>=48&&t<=57?(++this.state.pos,this.finishToken(17)):(this.state.pos+=2,this.finishToken(18))}getTokenFromCode(e){switch(e){case 46:return void this.readToken_dot();case 40:return++this.state.pos,void this.finishToken(10);case 41:return++this.state.pos,void this.finishToken(11);case 59:return++this.state.pos,void this.finishToken(13);case 44:return++this.state.pos,void this.finishToken(12);case 91:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(g.TupleExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(2)}else++this.state.pos,this.finishToken(0);return;case 93:return++this.state.pos,void this.finishToken(3);case 123:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(g.RecordExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(6)}else++this.state.pos,this.finishToken(5);return;case 125:return++this.state.pos,void this.finishToken(8);case 58:return void(this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(15,2):(++this.state.pos,this.finishToken(14)));case 63:return void this.readToken_question();case 96:return void this.readTemplateToken();case 48:{const e=this.input.charCodeAt(this.state.pos+1);if(120===e||88===e)return void this.readRadixNumber(16);if(111===e||79===e)return void this.readRadixNumber(8);if(98===e||66===e)return void this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return void this.readNumber(!1);case 34:case 39:return void this.readString(e);case 47:return void this.readToken_slash();case 37:case 42:return void this.readToken_mult_modulo(e);case 124:case 38:return void this.readToken_pipe_amp(e);case 94:return void this.readToken_caret();case 43:case 45:return void this.readToken_plus_min(e);case 60:return void this.readToken_lt();case 62:return void this.readToken_gt();case 61:case 33:return void this.readToken_eq_excl(e);case 126:return void this.finishOp(36,1);case 64:return void this.readToken_atSign();case 35:return void this.readToken_numberSign();case 92:return void this.readWord();default:if(ie(e))return void this.readWord(e)}throw this.raise(g.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(e)})}finishOp(e,t){const r=this.input.slice(this.state.pos,this.state.pos+t);this.state.pos+=t,this.finishToken(e,r)}readRegexp(){const e=this.state.startLoc,t=this.state.start+1;let r,n,{pos:s}=this.state;for(;;++s){if(s>=this.length)throw this.raise(g.UnterminatedRegExp,i(e,1));const t=this.input.charCodeAt(s);if(Ae(t))throw this.raise(g.UnterminatedRegExp,i(e,1));if(r)r=!1;else{if(91===t)n=!0;else if(93===t&&n)n=!1;else if(47===t&&!n)break;r=92===t}}const a=this.input.slice(t,s);++s;let o="";const l=()=>i(e,s+2-t);for(;s<this.length;){const e=this.codePointAtPos(s),t=String.fromCharCode(e);if(Ve.has(e))118===e?o.includes("u")&&this.raise(g.IncompatibleRegExpUVFlags,l()):117===e&&o.includes("v")&&this.raise(g.IncompatibleRegExpUVFlags,l()),o.includes(t)&&this.raise(g.DuplicateRegExpFlags,l());else{if(!ae(e)&&92!==e)break;this.raise(g.MalformedRegExpFlags,l())}++s,o+=t}this.state.pos=s,this.finishToken(138,{pattern:a,flags:o})}readInt(e,t,r=!1,n=!0){const{n:s,pos:i}=Fe(this.input,this.state.pos,this.state.lineStart,this.state.curLine,e,t,r,n,this.errorHandlers_readInt,!1);return this.state.pos=i,s}readRadixNumber(e){const t=this.state.pos,r=this.state.curPosition();let n=!1;this.state.pos+=2;const s=this.readInt(e);null==s&&this.raise(g.InvalidDigit,i(r,2),{radix:e});const a=this.input.charCodeAt(this.state.pos);if(110===a)++this.state.pos,n=!0;else if(109===a)throw this.raise(g.InvalidDecimal,r);if(ie(this.codePointAtPos(this.state.pos)))throw this.raise(g.NumberIdentifier,this.state.curPosition());if(n){const e=this.input.slice(t,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,e)}else this.finishToken(135,s)}readNumber(e){const t=this.state.pos,r=this.state.curPosition();let n=!1,s=!1,a=!1,o=!1;e||null!==this.readInt(10)||this.raise(g.InvalidNumber,this.state.curPosition());const l=this.state.pos-t>=2&&48===this.input.charCodeAt(t);if(l){const e=this.input.slice(t,this.state.pos);if(this.recordStrictModeErrors(g.StrictOctalLiteral,r),!this.state.strict){const t=e.indexOf("_");t>0&&this.raise(g.ZeroDigitNumericSeparator,i(r,t))}o=l&&!/[89]/.test(e)}let c=this.input.charCodeAt(this.state.pos);if(46!==c||o||(++this.state.pos,this.readInt(10),n=!0,c=this.input.charCodeAt(this.state.pos)),69!==c&&101!==c||o||(c=this.input.charCodeAt(++this.state.pos),43!==c&&45!==c||++this.state.pos,null===this.readInt(10)&&this.raise(g.InvalidOrMissingExponent,r),n=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),110===c&&((n||l)&&this.raise(g.InvalidBigIntLiteral,r),++this.state.pos,s=!0),109===c){this.expectPlugin("decimal",this.state.curPosition()),(a||l)&&this.raise(g.InvalidDecimal,r),++this.state.pos;var p=!0}if(ie(this.codePointAtPos(this.state.pos)))throw this.raise(g.NumberIdentifier,this.state.curPosition());const u=this.input.slice(t,this.state.pos).replace(/[_mn]/g,"");if(s)return void this.finishToken(136,u);if(p)return void this.finishToken(137,u);const d=o?parseInt(u,8):parseFloat(u);this.finishToken(135,d)}readCodePoint(e){const{code:t,pos:r}=Re(this.input,this.state.pos,this.state.lineStart,this.state.curLine,e,this.errorHandlers_readCodePoint);return this.state.pos=r,t}readString(e){const{str:t,pos:r,curLine:n,lineStart:s}=je(34===e?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=r+1,this.state.lineStart=s,this.state.curLine=n,this.finishToken(134,t)}readTemplateContinuation(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken()}readTemplateToken(){const e=this.input[this.state.pos],{str:t,firstInvalidLoc:r,pos:s,curLine:i,lineStart:a}=je("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=s+1,this.state.lineStart=a,this.state.curLine=i,r&&(this.state.firstInvalidTemplateEscapePos=new n(r.curLine,r.pos-r.lineStart,this.sourceToOffsetPos(r.pos))),96===this.input.codePointAt(s)?this.finishToken(24,r?null:e+t+"`"):(this.state.pos++,this.finishToken(25,r?null:e+t+"${"))}recordStrictModeErrors(e,t){const r=t.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(e,t):this.state.strictErrors.set(r,[e,t])}readWord1(e){this.state.containsEsc=!1;let t="";const r=this.state.pos;let n=this.state.pos;for(void 0!==e&&(this.state.pos+=e<=65535?1:2);this.state.pos<this.length;){const e=this.codePointAtPos(this.state.pos);if(ae(e))this.state.pos+=e<=65535?1:2;else{if(92!==e)break;{this.state.containsEsc=!0,t+=this.input.slice(n,this.state.pos);const e=this.state.curPosition(),s=this.state.pos===r?ie:ae;if(117!==this.input.charCodeAt(++this.state.pos)){this.raise(g.MissingUnicodeEscape,this.state.curPosition()),n=this.state.pos-1;continue}++this.state.pos;const i=this.readCodePoint(!0);null!==i&&(s(i)||this.raise(g.EscapedCharNotAnIdentifier,e),t+=String.fromCodePoint(i)),n=this.state.pos}}}return t+this.input.slice(n,this.state.pos)}readWord(e){const t=this.readWord1(e),r=I.get(t);void 0!==r?this.finishToken(r,Y(r)):this.finishToken(132,t)}checkKeywordEscapes(){const{type:e}=this.state;H(e)&&this.state.containsEsc&&this.raise(g.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Y(e)})}raise(e,t,r={}){const s=e(t instanceof n?t:t.loc.start,r);if(!(1024&this.optionFlags))throw s;return this.isLookahead||this.state.errors.push(s),s}raiseOverwrite(e,t,r={}){const s=t instanceof n?t:t.loc.start,i=s.index,a=this.state.errors;for(let t=a.length-1;t>=0;t--){const n=a[t];if(n.loc.index===i)return a[t]=e(s,r);if(n.loc.index<i)break}return this.raise(e,t,r)}updateContext(e){}unexpected(e,t){throw this.raise(g.UnexpectedToken,null!=e?e:this.state.startLoc,{expected:t?Y(t):null})}expectPlugin(e,t){if(this.hasPlugin(e))return!0;throw this.raise(g.MissingPlugin,null!=t?t:this.state.startLoc,{missingPlugin:[e]})}expectOnePlugin(e){if(!e.some((e=>this.hasPlugin(e))))throw this.raise(g.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:e})}errorBuilder(e){return(t,r,n)=>{this.raise(e,Ue(t,r,n))}}}class Ke{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}}class $e{constructor(e){this.parser=void 0,this.stack=[],this.undefinedPrivateNames=new Map,this.parser=e}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new Ke)}exit(){const e=this.stack.pop(),t=this.current();for(const[r,n]of Array.from(e.undefinedPrivateNames))t?t.undefinedPrivateNames.has(r)||t.undefinedPrivateNames.set(r,n):this.parser.raise(g.InvalidPrivateFieldResolution,n,{identifierName:r})}declarePrivateName(e,t,r){const{privateNames:n,loneAccessors:s,undefinedPrivateNames:i}=this.current();let a=n.has(e);if(3&t){const r=a&&s.get(e);r?(a=(3&r)==(3&t)||(4&r)!=(4&t),a||s.delete(e)):a||s.set(e,t)}a&&this.parser.raise(g.PrivateNameRedeclaration,r,{identifierName:e}),n.add(e),i.delete(e)}usePrivateName(e,t){let r;for(r of this.stack)if(r.privateNames.has(e))return;r?r.undefinedPrivateNames.set(e,t):this.parser.raise(g.InvalidPrivateFieldResolution,t,{identifierName:e})}}class Ge{constructor(e=0){this.type=e}canBeArrowParameterDeclaration(){return 2===this.type||1===this.type}isCertainlyParameterDeclaration(){return 3===this.type}}class He extends Ge{constructor(e){super(e),this.declarationErrors=new Map}recordDeclarationError(e,t){const r=t.index;this.declarationErrors.set(r,[e,t])}clearDeclarationError(e){this.declarationErrors.delete(e)}iterateErrors(e){this.declarationErrors.forEach(e)}}class Ye{constructor(e){this.parser=void 0,this.stack=[new Ge],this.parser=e}enter(e){this.stack.push(e)}exit(){this.stack.pop()}recordParameterInitializerError(e,t){const r=t.loc.start,{stack:n}=this;let s=n.length-1,i=n[s];for(;!i.isCertainlyParameterDeclaration();){if(!i.canBeArrowParameterDeclaration())return;i.recordDeclarationError(e,r),i=n[--s]}this.parser.raise(e,r)}recordArrowParameterBindingError(e,t){const{stack:r}=this,n=r[r.length-1],s=t.loc.start;if(n.isCertainlyParameterDeclaration())this.parser.raise(e,s);else{if(!n.canBeArrowParameterDeclaration())return;n.recordDeclarationError(e,s)}}recordAsyncArrowParametersError(e){const{stack:t}=this;let r=t.length-1,n=t[r];for(;n.canBeArrowParameterDeclaration();)2===n.type&&n.recordDeclarationError(g.AwaitBindingIdentifier,e),n=t[--r]}validateAsPattern(){const{stack:e}=this,t=e[e.length-1];t.canBeArrowParameterDeclaration()&&t.iterateErrors((([t,r])=>{this.parser.raise(t,r);let n=e.length-2,s=e[n];for(;s.canBeArrowParameterDeclaration();)s.clearDeclarationError(r.index),s=e[--n]}))}}function Je(){return new Ge}class ze{constructor(){this.stacks=[]}enter(e){this.stacks.push(e)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(2&this.currentFlags())>0}get hasYield(){return(1&this.currentFlags())>0}get hasReturn(){return(4&this.currentFlags())>0}get hasIn(){return(8&this.currentFlags())>0}}function Xe(e,t){return(e?2:0)|(t?1:0)}class Qe extends We{addExtra(e,t,r,n=!0){if(!e)return;let{extra:s}=e;null==s&&(s={},e.extra=s),n?s[t]=r:Object.defineProperty(s,t,{enumerable:n,value:r})}isContextual(e){return this.state.type===e&&!this.state.containsEsc}isUnparsedContextual(e,t){const r=e+t.length;if(this.input.slice(e,r)===t){const e=this.input.charCodeAt(r);return!(ae(e)||55296==(64512&e))}return!1}isLookaheadContextual(e){const t=this.nextTokenStart();return this.isUnparsedContextual(t,e)}eatContextual(e){return!!this.isContextual(e)&&(this.next(),!0)}expectContextual(e,t){if(!this.eatContextual(e)){if(null!=t)throw this.raise(t,this.state.startLoc);this.unexpected(null,e)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return we(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return we(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(e=!0){(e?this.isLineTerminator():this.eat(13))||this.raise(g.MissingSemicolon,this.state.lastTokEndLoc)}expect(e,t){this.eat(e)||this.unexpected(t,e)}tryParse(e,t=this.state.clone()){const r={node:null};try{const n=e(((e=null)=>{throw r.node=e,r}));if(this.state.errors.length>t.errors.length){const e=this.state;return this.state=t,this.state.tokensLength=e.tokensLength,{node:n,error:e.errors[t.errors.length],thrown:!1,aborted:!1,failState:e}}return{node:n,error:null,thrown:!1,aborted:!1,failState:null}}catch(e){const n=this.state;if(this.state=t,e instanceof SyntaxError)return{node:null,error:e,thrown:!0,aborted:!1,failState:n};if(e===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:n};throw e}}checkExpressionErrors(e,t){if(!e)return!1;const{shorthandAssignLoc:r,doubleProtoLoc:n,privateKeyLoc:s,optionalParametersLoc:i}=e;if(!t)return!!(r||n||i||s);null!=r&&this.raise(g.InvalidCoverInitializedName,r),null!=n&&this.raise(g.DuplicateProto,n),null!=s&&this.raise(g.UnexpectedPrivateField,s),null!=i&&this.unexpected(i)}isLiteralPropertyName(){return K(this.state.type)}isPrivateName(e){return"PrivateName"===e.type}getPrivateNameSV(e){return e.id.name}hasPropertyAsPrivateName(e){return("MemberExpression"===e.type||"OptionalMemberExpression"===e.type)&&this.isPrivateName(e.property)}isObjectProperty(e){return"ObjectProperty"===e.type}isObjectMethod(e){return"ObjectMethod"===e.type}initializeScopes(e="module"===this.options.sourceType){const t=this.state.labels;this.state.labels=[];const r=this.exportedIdentifiers;this.exportedIdentifiers=new Set;const n=this.inModule;this.inModule=e;const s=this.scope,i=this.getScopeHandler();this.scope=new i(this,e);const a=this.prodParam;this.prodParam=new ze;const o=this.classScope;this.classScope=new $e(this);const l=this.expressionScope;return this.expressionScope=new Ye(this),()=>{this.state.labels=t,this.exportedIdentifiers=r,this.inModule=n,this.scope=s,this.prodParam=a,this.classScope=o,this.expressionScope=l}}enterInitialScopes(){let e=0;this.inModule&&(e|=2),this.scope.enter(1),this.prodParam.enter(e)}checkDestructuringPrivate(e){const{privateKeyLoc:t}=e;null!==t&&this.expectPlugin("destructuringPrivate",t)}}class Ze{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null}}class et{constructor(e,t,r){this.type="",this.start=t,this.end=0,this.loc=new s(r),64&(null==e?void 0:e.optionFlags)&&(this.range=[t,0]),null!=e&&e.filename&&(this.loc.filename=e.filename)}}const tt=et.prototype;function rt(e){const{type:t,start:r,end:n,loc:s,range:i,extra:a,name:o}=e,l=Object.create(tt);return l.type=t,l.start=r,l.end=n,l.loc=s,l.range=i,l.extra=a,l.name=o,"Placeholder"===t&&(l.expectedNode=e.expectedNode),l}tt.__clone=function(){const e=new et(void 0,this.start,this.loc.start),t=Object.keys(this);for(let r=0,n=t.length;r<n;r++){const n=t[r];"leadingComments"!==n&&"trailingComments"!==n&&"innerComments"!==n&&(e[n]=this[n])}return e};class nt extends Qe{startNode(){const e=this.state.startLoc;return new et(this,e.index,e)}startNodeAt(e){return new et(this,e.index,e)}startNodeAtNode(e){return this.startNodeAt(e.loc.start)}finishNode(e,t){return this.finishNodeAt(e,t,this.state.lastTokEndLoc)}finishNodeAt(e,t,r){return e.type=t,e.end=r.index,e.loc.end=r,64&this.optionFlags&&(e.range[1]=r.index),2048&this.optionFlags&&this.processComment(e),e}resetStartLocation(e,t){e.start=t.index,e.loc.start=t,64&this.optionFlags&&(e.range[0]=t.index)}resetEndLocation(e,t=this.state.lastTokEndLoc){e.end=t.index,e.loc.end=t,64&this.optionFlags&&(e.range[1]=t.index)}resetStartLocationFromNode(e,t){this.resetStartLocation(e,t.loc.start)}}const st=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),it=y`flow`({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType:e})=>`Cannot overwrite reserved type ${e}.`,DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:({memberName:e,enumName:t})=>`Boolean enum members need to be initialized. Use either \`${e} = true,\` or \`${e} = false,\` in enum \`${t}\`.`,EnumDuplicateMemberName:({memberName:e,enumName:t})=>`Enum member names need to be unique, but the name \`${e}\` has already been used before in enum \`${t}\`.`,EnumInconsistentMemberValues:({enumName:e})=>`Enum \`${e}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:e,enumName:t})=>`Enum type \`${e}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:e})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${e}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:e,memberName:t,explicitType:r})=>`Enum \`${e}\` has type \`${r}\`, so the initializer of \`${t}\` needs to be a ${r} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:e,memberName:t})=>`Symbol enum members cannot be initialized. Use \`${t},\` in enum \`${e}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:e,memberName:t})=>`The enum member initializer for \`${t}\` needs to be a literal (either a boolean, number, or string) in enum \`${e}\`.`,EnumInvalidMemberName:({enumName:e,memberName:t,suggestion:r})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${t}\`, consider using \`${r}\`, in enum \`${e}\`.`,EnumNumberMemberNotInitialized:({enumName:e,memberName:t})=>`Number enum members need to be initialized, e.g. \`${t} = 1\` in enum \`${e}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:e})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${e}\`.`,GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` or `typeof` keyword.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:Object.assign({message:"A binding pattern parameter cannot be optional in an implementation signature."},{reasonCode:"OptionalBindingPattern"}),SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:({reservedType:e})=>`Unexpected reserved type ${e}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:e,suggestion:t})=>`\`declare export ${e}\` is not supported. Use \`${t}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function at(e){return"type"===e.importKind||"typeof"===e.importKind}const ot={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"},lt=/\*?\s*@((?:no)?flow)\b/,ct={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},pt=y`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:e})=>`Expected corresponding JSX closing tag for <${e}>.`,MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:({unexpected:e,HTMLEntity:t})=>`Unexpected token \`${e}\`. Did you mean \`${t}\` or \`{'${e}'}\`?`,UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"});function ut(e){return!!e&&("JSXOpeningFragment"===e.type||"JSXClosingFragment"===e.type)}function dt(e){if("JSXIdentifier"===e.type)return e.name;if("JSXNamespacedName"===e.type)return e.namespace.name+":"+e.name.name;if("JSXMemberExpression"===e.type)return dt(e.object)+"."+dt(e.property);throw new Error("Node had unexpected type: "+e.type)}class ft extends me{constructor(...e){super(...e),this.tsNames=new Map}}class ht extends ye{constructor(...e){super(...e),this.importsStack=[]}createScope(e){return this.importsStack.push(new Set),new ft(e)}enter(e){256===e&&this.importsStack.push(new Set),super.enter(e)}exit(){const e=super.exit();return 256===e&&this.importsStack.pop(),e}hasImport(e,t){const r=this.importsStack.length;if(this.importsStack[r-1].has(e))return!0;if(!t&&r>1)for(let t=0;t<r-1;t++)if(this.importsStack[t].has(e))return!0;return!1}declareName(e,t,r){if(4096&t)return this.hasImport(e,!0)&&this.parser.raise(g.VarRedeclaration,r,{identifierName:e}),void this.importsStack[this.importsStack.length-1].add(e);const n=this.currentScope();let s=n.tsNames.get(e)||0;if(1024&t)return this.maybeExportDefined(n,e),void n.tsNames.set(e,16|s);super.declareName(e,t,r),2&t&&(1&t||(this.checkRedeclarationInScope(n,e,t,r),this.maybeExportDefined(n,e)),s|=1),256&t&&(s|=2),512&t&&(s|=4),128&t&&(s|=8),s&&n.tsNames.set(e,s)}isRedeclaredInScope(e,t,r){const n=e.tsNames.get(t);return(2&n)>0?!(256&r)||!!(512&r)!=(4&n)>0:128&r&&(8&n)>0?!!(2&e.names.get(t))&&!!(1&r):!!(2&r&&(1&n)>0)||super.isRedeclaredInScope(e,t,r)}checkLocalExport(e){const{name:t}=e;if(!this.hasImport(t)){for(let e=this.scopeStack.length-1;e>=0;e--){const r=this.scopeStack[e].tsNames.get(t);if((1&r)>0||(16&r)>0)return}super.checkLocalExport(e)}}}const mt=e=>"ParenthesizedExpression"===e.type?mt(e.expression):e;class yt extends nt{toAssignable(e,t=!1){var r,n;let s;switch(("ParenthesizedExpression"===e.type||null!=(r=e.extra)&&r.parenthesized)&&(s=mt(e),t?"Identifier"===s.type?this.expressionScope.recordArrowParameterBindingError(g.InvalidParenthesizedAssignment,e):"MemberExpression"===s.type||this.isOptionalMemberExpression(s)||this.raise(g.InvalidParenthesizedAssignment,e):this.raise(g.InvalidParenthesizedAssignment,e)),e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";for(let r=0,n=e.properties.length,s=n-1;r<n;r++){var i;const n=e.properties[r],a=r===s;this.toAssignableObjectExpressionProp(n,a,t),a&&"RestElement"===n.type&&null!=(i=e.extra)&&i.trailingCommaLoc&&this.raise(g.RestTrailingComma,e.extra.trailingCommaLoc)}break;case"ObjectProperty":{const{key:r,value:n}=e;this.isPrivateName(r)&&this.classScope.usePrivateName(this.getPrivateNameSV(r),r.loc.start),this.toAssignable(n,t);break}case"SpreadElement":throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");case"ArrayExpression":e.type="ArrayPattern",this.toAssignableList(e.elements,null==(n=e.extra)?void 0:n.trailingCommaLoc,t);break;case"AssignmentExpression":"="!==e.operator&&this.raise(g.MissingEqInAssignment,e.left.loc.end),e.type="AssignmentPattern",delete e.operator,this.toAssignable(e.left,t);break;case"ParenthesizedExpression":this.toAssignable(s,t)}}toAssignableObjectExpressionProp(e,t,r){if("ObjectMethod"===e.type)this.raise("get"===e.kind||"set"===e.kind?g.PatternHasAccessor:g.PatternHasMethod,e.key);else if("SpreadElement"===e.type){e.type="RestElement";const n=e.argument;this.checkToRestConversion(n,!1),this.toAssignable(n,r),t||this.raise(g.RestTrailingComma,e)}else this.toAssignable(e,r)}toAssignableList(e,t,r){const n=e.length-1;for(let s=0;s<=n;s++){const i=e[s];if(i){if("SpreadElement"===i.type){i.type="RestElement";const e=i.argument;this.checkToRestConversion(e,!0),this.toAssignable(e,r)}else this.toAssignable(i,r);"RestElement"===i.type&&(s<n?this.raise(g.RestTrailingComma,i):t&&this.raise(g.RestTrailingComma,t))}}}isAssignable(e,t){switch(e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":return!0;case"ObjectExpression":{const t=e.properties.length-1;return e.properties.every(((e,r)=>"ObjectMethod"!==e.type&&(r===t||"SpreadElement"!==e.type)&&this.isAssignable(e)))}case"ObjectProperty":return this.isAssignable(e.value);case"SpreadElement":return this.isAssignable(e.argument);case"ArrayExpression":return e.elements.every((e=>null===e||this.isAssignable(e)));case"AssignmentExpression":return"="===e.operator;case"ParenthesizedExpression":return this.isAssignable(e.expression);case"MemberExpression":case"OptionalMemberExpression":return!t;default:return!1}}toReferencedList(e,t){return e}toReferencedListDeep(e,t){this.toReferencedList(e,t);for(const t of e)"ArrayExpression"===(null==t?void 0:t.type)&&this.toReferencedListDeep(t.elements)}parseSpread(e){const t=this.startNode();return this.next(),t.argument=this.parseMaybeAssignAllowIn(e,void 0),this.finishNode(t,"SpreadElement")}parseRestBinding(){const e=this.startNode();return this.next(),e.argument=this.parseBindingAtom(),this.finishNode(e,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{const e=this.startNode();return this.next(),e.elements=this.parseBindingList(3,93,1),this.finishNode(e,"ArrayPattern")}case 5:return this.parseObjectLike(8,!0)}return this.parseIdentifier()}parseBindingList(e,t,r){const n=1&r,s=[];let i=!0;for(;!this.eat(e);)if(i?i=!1:this.expect(12),n&&this.match(12))s.push(null);else{if(this.eat(e))break;if(this.match(21)){let n=this.parseRestBinding();if((this.hasPlugin("flow")||2&r)&&(n=this.parseFunctionParamType(n)),s.push(n),!this.checkCommaAfterRest(t)){this.expect(e);break}}else{const e=[];for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(g.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)e.push(this.parseDecorator());s.push(this.parseAssignableListItem(r,e))}}return s}parseBindingRestProperty(e){return this.next(),e.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(e,"RestElement")}parseBindingProperty(){const{type:e,startLoc:t}=this.state;if(21===e)return this.parseBindingRestProperty(this.startNode());const r=this.startNode();return 139===e?(this.expectPlugin("destructuringPrivate",t),this.classScope.usePrivateName(this.state.value,t),r.key=this.parsePrivateName()):this.parsePropertyName(r),r.method=!1,this.parseObjPropValue(r,t,!1,!1,!0,!1)}parseAssignableListItem(e,t){const r=this.parseMaybeDefault();(this.hasPlugin("flow")||2&e)&&this.parseFunctionParamType(r);const n=this.parseMaybeDefault(r.loc.start,r);return t.length&&(r.decorators=t),n}parseFunctionParamType(e){return e}parseMaybeDefault(e,t){var r;if(null!=e||(e=this.state.startLoc),t=null!=(r=t)?r:this.parseBindingAtom(),!this.eat(29))return t;const n=this.startNodeAt(e);return n.left=t,n.right=this.parseMaybeAssignAllowIn(),this.finishNode(n,"AssignmentPattern")}isValidLVal(e,t,r){switch(e){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties"}return!1}isOptionalMemberExpression(e){return"OptionalMemberExpression"===e.type}checkLVal(e,t,r=64,n=!1,s=!1,i=!1){var a;const o=e.type;if(this.isObjectMethod(e))return;const l=this.isOptionalMemberExpression(e);if(l||"MemberExpression"===o)return l&&(this.expectPlugin("optionalChainingAssign",e.loc.start),"AssignmentExpression"!==t.type&&this.raise(g.InvalidLhsOptionalChaining,e,{ancestor:t})),void(64!==r&&this.raise(g.InvalidPropertyBindingPattern,e));if("Identifier"===o){this.checkIdentifier(e,r,s);const{name:t}=e;return void(n&&(n.has(t)?this.raise(g.ParamDupe,e):n.add(t)))}const c=this.isValidLVal(o,!(i||null!=(a=e.extra)&&a.parenthesized)&&"AssignmentExpression"===t.type,r);if(!0===c)return;if(!1===c){const n=64===r?g.InvalidLhs:g.InvalidLhsBinding;return void this.raise(n,e,{ancestor:t})}let p,u;"string"==typeof c?(p=c,u="ParenthesizedExpression"===o):[p,u]=c;const d="ArrayPattern"===o||"ObjectPattern"===o?{type:o}:t,f=e[p];if(Array.isArray(f))for(const e of f)e&&this.checkLVal(e,d,r,n,s,u);else f&&this.checkLVal(f,d,r,n,s,u)}checkIdentifier(e,t,r=!1){this.state.strict&&(r?fe(e.name,this.inModule):de(e.name))&&(64===t?this.raise(g.StrictEvalArguments,e,{referenceName:e.name}):this.raise(g.StrictEvalArgumentsBinding,e,{bindingName:e.name})),8192&t&&"let"===e.name&&this.raise(g.LetInLexicalBinding,e),64&t||this.declareNameFromIdentifier(e,t)}declareNameFromIdentifier(e,t){this.scope.declareName(e.name,t,e.loc.start)}checkToRestConversion(e,t){switch(e.type){case"ParenthesizedExpression":this.checkToRestConversion(e.expression,t);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(t)break;default:this.raise(g.InvalidRestAssignmentPattern,e)}}checkCommaAfterRest(e){return!!this.match(12)&&(this.raise(this.lookaheadCharCode()===e?g.RestTrailingComma:g.ElementAfterRest,this.state.startLoc),!0)}}function gt(e){if(!e)throw new Error("Assert fail")}const bt=y`typescript`({AbstractMethodHasImplementation:({methodName:e})=>`Method '${e}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:e})=>`Property '${e}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",ConstructorHasTypeParameters:"Type parameters cannot appear on a constructor declaration.",DeclareAccessor:({kind:e})=>`'declare' is not allowed in ${e}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:e})=>"Accessibility modifier already seen.",DuplicateModifier:({modifier:e})=>`Duplicate modifier: '${e}'.`,EmptyHeritageClauseType:({token:e})=>`'${e}' list cannot be empty.`,EmptyTypeArguments:"Type argument list cannot be empty.",EmptyTypeParameters:"Type parameter list cannot be empty.",ExpectedAmbientAfterExportDeclare:"'export declare' must be followed by an ambient declaration.",ImportAliasHasImportType:"An import alias can not use 'import type'.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` modifier",IncompatibleModifiers:({modifiers:e})=>`'${e[0]}' modifier cannot be used with '${e[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:e})=>`Index signatures cannot have an accessibility modifier ('${e}').`,IndexSignatureHasDeclare:"Index signatures cannot have the 'declare' modifier.",IndexSignatureHasOverride:"'override' modifier cannot appear on an index signature.",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier.",InitializerNotAllowedInAmbientContext:"Initializers are not allowed in ambient contexts.",InvalidModifierOnTypeMember:({modifier:e})=>`'${e}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:e})=>`'${e}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:e})=>`'${e}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifiersOrder:({orderedModifiers:e})=>`'${e[0]}' modifier must precede '${e[1]}' modifier.`,InvalidPropertyAccessAfterInstantiationExpression:"Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",InvalidTupleMemberLabel:"Tuple members must be labeled with a simple identifier.",MissingInterfaceName:"'interface' declarations must be followed by an identifier.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifer:"'abstract' modifier can only appear on a class, method, or property declaration.",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",OverrideNotInSubClass:"This member cannot have an 'override' modifier because its containing class does not extend another class.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:({modifier:e})=>`Private elements cannot have an accessibility modifier ('${e}').`,ReadonlyForMethodSignature:"'readonly' modifier can only appear on a property declaration or index signature.",ReservedArrowTypeParam:"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:e})=>`Single type parameter ${e} should have a trailing comma. Example usage: <${e},>.`,StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:({type:e})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${e}.`});function vt(e){return"private"===e||"public"===e||"protected"===e}function Tt(e){return"in"===e||"out"===e}function xt(e){if("MemberExpression"!==e.type)return!1;const{computed:t,property:r}=e;return(!t||"StringLiteral"===r.type||!("TemplateLiteral"!==r.type||r.expressions.length>0))&&Pt(e.object)}function St(e,t){var r;const{type:n}=e;if(null!=(r=e.extra)&&r.parenthesized)return!1;if(t){if("Literal"===n){const{value:t}=e;if("string"==typeof t||"boolean"==typeof t)return!0}}else if("StringLiteral"===n||"BooleanLiteral"===n)return!0;return!(!Et(e,t)&&!function(e,t){if("UnaryExpression"===e.type){const{operator:r,argument:n}=e;if("-"===r&&Et(n,t))return!0}return!1}(e,t))||"TemplateLiteral"===n&&0===e.expressions.length||!!xt(e)}function Et(e,t){return t?"Literal"===e.type&&("number"==typeof e.value||"bigint"in e):"NumericLiteral"===e.type||"BigIntLiteral"===e.type}function Pt(e){return"Identifier"===e.type||"MemberExpression"===e.type&&!e.computed&&Pt(e.object)}const At=y`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),wt=["minimal","fsharp","hack","smart"],Ct=["^^","@@","^","%","#"],Ot={estree:e=>class extends e{parse(){const e=T(super.parse());return 128&this.optionFlags&&(e.tokens=e.tokens.map(T)),e}parseRegExpLiteral({pattern:e,flags:t}){let r=null;try{r=new RegExp(e,t)}catch(e){}const n=this.estreeParseLiteral(r);return n.regex={pattern:e,flags:t},n}parseBigIntLiteral(e){let t;try{t=BigInt(e)}catch(e){t=null}const r=this.estreeParseLiteral(t);return r.bigint=String(r.value||e),r}parseDecimalLiteral(e){const t=this.estreeParseLiteral(null);return t.decimal=String(t.value||e),t}estreeParseLiteral(e){return this.parseLiteral(e,"Literal")}parseStringLiteral(e){return this.estreeParseLiteral(e)}parseNumericLiteral(e){return this.estreeParseLiteral(e)}parseNullLiteral(){return this.estreeParseLiteral(null)}parseBooleanLiteral(e){return this.estreeParseLiteral(e)}directiveToStmt(e){const t=e.value;delete e.value,t.type="Literal",t.raw=t.extra.raw,t.value=t.extra.expressionValue;const r=e;return r.type="ExpressionStatement",r.expression=t,r.directive=t.extra.rawValue,delete t.extra,r}initFunction(e,t){super.initFunction(e,t),e.expression=!1}checkDeclaration(e){null!=e&&this.isObjectProperty(e)?this.checkDeclaration(e.value):super.checkDeclaration(e)}getObjectOrClassMethodParams(e){return e.value.params}isValidDirective(e){var t;return"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&!(null!=(t=e.expression.extra)&&t.parenthesized)}parseBlockBody(e,t,r,n,s){super.parseBlockBody(e,t,r,n,s);const i=e.directives.map((e=>this.directiveToStmt(e)));e.body=i.concat(e.body),delete e.directives}parsePrivateName(){const e=super.parsePrivateName();return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(e):e}convertPrivateNameToPrivateIdentifier(e){const t=super.getPrivateNameSV(e);return delete e.id,e.name=t,e.type="PrivateIdentifier",e}isPrivateName(e){return this.getPluginOption("estree","classFeatures")?"PrivateIdentifier"===e.type:super.isPrivateName(e)}getPrivateNameSV(e){return this.getPluginOption("estree","classFeatures")?e.name:super.getPrivateNameSV(e)}parseLiteral(e,t){const r=super.parseLiteral(e,t);return r.raw=r.extra.raw,delete r.extra,r}parseFunctionBody(e,t,r=!1){super.parseFunctionBody(e,t,r),e.expression="BlockStatement"!==e.body.type}parseMethod(e,t,r,n,s,i,a=!1){let o=this.startNode();o.kind=e.kind,o=super.parseMethod(o,t,r,n,s,i,a),o.type="FunctionExpression",delete o.kind,e.value=o;const{typeParameters:l}=e;return l&&(delete e.typeParameters,o.typeParameters=l,this.resetStartLocationFromNode(o,l)),"ClassPrivateMethod"===i&&(e.computed=!1),this.finishNode(e,"MethodDefinition")}nameIsConstructor(e){return"Literal"===e.type?"constructor"===e.value:super.nameIsConstructor(e)}parseClassProperty(...e){const t=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")?(t.type="PropertyDefinition",t):t}parseClassPrivateProperty(...e){const t=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")?(t.type="PropertyDefinition",t.computed=!1,t):t}parseObjectMethod(e,t,r,n,s){const i=super.parseObjectMethod(e,t,r,n,s);return i&&(i.type="Property","method"===i.kind&&(i.kind="init"),i.shorthand=!1),i}parseObjectProperty(e,t,r,n){const s=super.parseObjectProperty(e,t,r,n);return s&&(s.kind="init",s.type="Property"),s}isValidLVal(e,t,r){return"Property"===e?"value":super.isValidLVal(e,t,r)}isAssignable(e,t){return null!=e&&this.isObjectProperty(e)?this.isAssignable(e.value,t):super.isAssignable(e,t)}toAssignable(e,t=!1){if(null!=e&&this.isObjectProperty(e)){const{key:r,value:n}=e;this.isPrivateName(r)&&this.classScope.usePrivateName(this.getPrivateNameSV(r),r.loc.start),this.toAssignable(n,t)}else super.toAssignable(e,t)}toAssignableObjectExpressionProp(e,t,r){"Property"!==e.type||"get"!==e.kind&&"set"!==e.kind?"Property"===e.type&&e.method?this.raise(g.PatternHasMethod,e.key):super.toAssignableObjectExpressionProp(e,t,r):this.raise(g.PatternHasAccessor,e.key)}finishCallExpression(e,t){const r=super.finishCallExpression(e,t);var n,s;return"Import"===r.callee.type&&(r.type="ImportExpression",r.source=r.arguments[0],r.options=null!=(n=r.arguments[1])?n:null,r.attributes=null!=(s=r.arguments[1])?s:null,delete r.arguments,delete r.callee),r}toReferencedArguments(e){"ImportExpression"!==e.type&&super.toReferencedArguments(e)}parseExport(e,t){const r=this.state.lastTokStartLoc,n=super.parseExport(e,t);switch(n.type){case"ExportAllDeclaration":n.exported=null;break;case"ExportNamedDeclaration":1===n.specifiers.length&&"ExportNamespaceSpecifier"===n.specifiers[0].type&&(n.type="ExportAllDeclaration",n.exported=n.specifiers[0].exported,delete n.specifiers);case"ExportDefaultDeclaration":{var s;const{declaration:e}=n;"ClassDeclaration"===(null==e?void 0:e.type)&&(null==(s=e.decorators)?void 0:s.length)>0&&e.start===n.start&&this.resetStartLocation(n,r)}}return n}parseSubscript(e,t,r,n){const s=super.parseSubscript(e,t,r,n);if(n.optionalChainMember){if("OptionalMemberExpression"!==s.type&&"OptionalCallExpression"!==s.type||(s.type=s.type.substring(8)),n.stop){const e=this.startNodeAtNode(s);return e.expression=s,this.finishNode(e,"ChainExpression")}}else"MemberExpression"!==s.type&&"CallExpression"!==s.type||(s.optional=!1);return s}isOptionalMemberExpression(e){return"ChainExpression"===e.type?"MemberExpression"===e.expression.type:super.isOptionalMemberExpression(e)}hasPropertyAsPrivateName(e){return"ChainExpression"===e.type&&(e=e.expression),super.hasPropertyAsPrivateName(e)}isObjectProperty(e){return"Property"===e.type&&"init"===e.kind&&!e.method}isObjectMethod(e){return"Property"===e.type&&(e.method||"get"===e.kind||"set"===e.kind)}finishNodeAt(e,t,r){return T(super.finishNodeAt(e,t,r))}resetStartLocation(e,t){super.resetStartLocation(e,t),T(e)}resetEndLocation(e,t=this.state.lastTokEndLoc){super.resetEndLocation(e,t),T(e)}},jsx:e=>class extends e{jsxReadToken(){let e="",t=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(pt.UnterminatedJsxContent,this.state.startLoc);const r=this.input.charCodeAt(this.state.pos);switch(r){case 60:case 123:return this.state.pos===this.state.start?void(60===r&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(143)):super.getTokenFromCode(r)):(e+=this.input.slice(t,this.state.pos),void this.finishToken(142,e));case 38:e+=this.input.slice(t,this.state.pos),e+=this.jsxReadEntity(),t=this.state.pos;break;default:Ae(r)?(e+=this.input.slice(t,this.state.pos),e+=this.jsxReadNewLine(!0),t=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){const t=this.input.charCodeAt(this.state.pos);let r;return++this.state.pos,13===t&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,r=e?"\n":"\r\n"):r=String.fromCharCode(t),++this.state.curLine,this.state.lineStart=this.state.pos,r}jsxReadString(e){let t="",r=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(g.UnterminatedString,this.state.startLoc);const n=this.input.charCodeAt(this.state.pos);if(n===e)break;38===n?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadEntity(),r=this.state.pos):Ae(n)?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadNewLine(!1),r=this.state.pos):++this.state.pos}t+=this.input.slice(r,this.state.pos++),this.finishToken(134,t)}jsxReadEntity(){const e=++this.state.pos;if(35===this.codePointAtPos(this.state.pos)){++this.state.pos;let e=10;120===this.codePointAtPos(this.state.pos)&&(e=16,++this.state.pos);const t=this.readInt(e,void 0,!1,"bail");if(null!==t&&59===this.codePointAtPos(this.state.pos))return++this.state.pos,String.fromCodePoint(t)}else{let t=0,r=!1;for(;t++<10&&this.state.pos<this.length&&!(r=59===this.codePointAtPos(this.state.pos));)++this.state.pos;if(r){const t=this.input.slice(e,this.state.pos),r=ct[t];if(++this.state.pos,r)return r}}return this.state.pos=e,"&"}jsxReadWord(){let e;const t=this.state.pos;do{e=this.input.charCodeAt(++this.state.pos)}while(ae(e)||45===e);this.finishToken(141,this.input.slice(t,this.state.pos))}jsxParseIdentifier(){const e=this.startNode();return this.match(141)?e.name=this.state.value:H(this.state.type)?e.name=Y(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){const e=this.state.startLoc,t=this.jsxParseIdentifier();if(!this.eat(14))return t;const r=this.startNodeAt(e);return r.namespace=t,r.name=this.jsxParseIdentifier(),this.finishNode(r,"JSXNamespacedName")}jsxParseElementName(){const e=this.state.startLoc;let t=this.jsxParseNamespacedName();if("JSXNamespacedName"===t.type)return t;for(;this.eat(16);){const r=this.startNodeAt(e);r.object=t,r.property=this.jsxParseIdentifier(),t=this.finishNode(r,"JSXMemberExpression")}return t}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(S.brace),this.next(),e=this.jsxParseExpressionContainer(e,S.j_oTag),"JSXEmptyExpression"===e.expression.type&&this.raise(pt.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(pt.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){const e=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(e,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(e){return this.next(),e.expression=this.parseExpression(),this.setContext(S.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,t){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{const t=this.parseExpression();e.expression=t}return this.setContext(t),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){const e=this.startNode();return this.match(5)?(this.setContext(S.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(S.j_oTag),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsxParseNamespacedName(),e.value=this.eat(29)?this.jsxParseAttributeValue():null,this.finishNode(e,"JSXAttribute"))}jsxParseOpeningElementAt(e){const t=this.startNodeAt(e);return this.eat(144)?this.finishNode(t,"JSXOpeningFragment"):(t.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(t))}jsxParseOpeningElementAfterName(e){const t=[];for(;!this.match(56)&&!this.match(144);)t.push(this.jsxParseAttribute());return e.attributes=t,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){const t=this.startNodeAt(e);return this.eat(144)?this.finishNode(t,"JSXClosingFragment"):(t.name=this.jsxParseElementName(),this.expect(144),this.finishNode(t,"JSXClosingElement"))}jsxParseElementAt(e){const t=this.startNodeAt(e),r=[],n=this.jsxParseOpeningElementAt(e);let s=null;if(!n.selfClosing){e:for(;;)switch(this.state.type){case 143:if(e=this.state.startLoc,this.next(),this.eat(56)){s=this.jsxParseClosingElementAt(e);break e}r.push(this.jsxParseElementAt(e));break;case 142:r.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{const e=this.startNode();this.setContext(S.brace),this.next(),this.match(21)?r.push(this.jsxParseSpreadChild(e)):r.push(this.jsxParseExpressionContainer(e,S.j_expr));break}default:this.unexpected()}ut(n)&&!ut(s)&&null!==s?this.raise(pt.MissingClosingTagFragment,s):!ut(n)&&ut(s)?this.raise(pt.MissingClosingTagElement,s,{openingTagName:dt(n.name)}):ut(n)||ut(s)||dt(s.name)!==dt(n.name)&&this.raise(pt.MissingClosingTagElement,s,{openingTagName:dt(n.name)})}if(ut(n)?(t.openingFragment=n,t.closingFragment=s):(t.openingElement=n,t.closingElement=s),t.children=r,this.match(47))throw this.raise(pt.UnwrappedAdjacentJSXElements,this.state.startLoc);return ut(n)?this.finishNode(t,"JSXFragment"):this.finishNode(t,"JSXElement")}jsxParseElement(){const e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){const{context:t}=this.state;t[t.length-1]=e}parseExprAtom(e){return this.match(143)?this.jsxParseElement():this.match(47)&&33!==this.input.charCodeAt(this.state.pos)?(this.replaceToken(143),this.jsxParseElement()):super.parseExprAtom(e)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(e){const t=this.curContext();if(t!==S.j_expr){if(t===S.j_oTag||t===S.j_cTag){if(ie(e))return void this.jsxReadWord();if(62===e)return++this.state.pos,void this.finishToken(144);if((34===e||39===e)&&t===S.j_oTag)return void this.jsxReadString(e)}if(60===e&&this.state.canStartJSXElement&&33!==this.input.charCodeAt(this.state.pos+1))return++this.state.pos,void this.finishToken(143);super.getTokenFromCode(e)}else this.jsxReadToken()}updateContext(e){const{context:t,type:r}=this.state;if(56===r&&143===e)t.splice(-2,2,S.j_cTag),this.state.canStartJSXElement=!1;else if(143===r)t.push(S.j_oTag);else if(144===r){const r=t[t.length-1];r===S.j_oTag&&56===e||r===S.j_cTag?(t.pop(),this.state.canStartJSXElement=t[t.length-1]===S.j_expr):(this.setContext(S.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=M[r]}},flow:e=>class extends e{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return be}shouldParseTypes(){return this.getPluginOption("flow","all")||"flow"===this.flowPragma}finishToken(e,t){134!==e&&13!==e&&28!==e&&void 0===this.flowPragma&&(this.flowPragma=null),super.finishToken(e,t)}addComment(e){if(void 0===this.flowPragma){const t=lt.exec(e.value);if(t)if("flow"===t[1])this.flowPragma="flow";else{if("noflow"!==t[1])throw new Error("Unexpected flow pragma");this.flowPragma="noflow"}}super.addComment(e)}flowParseTypeInitialiser(e){const t=this.state.inType;this.state.inType=!0,this.expect(e||14);const r=this.flowParseType();return this.state.inType=t,r}flowParsePredicate(){const e=this.startNode(),t=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>t.index+1&&this.raise(it.UnexpectedSpaceBetweenModuloChecks,t),this.eat(10)?(e.value=super.parseExpression(),this.expect(11),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(){const e=this.state.inType;this.state.inType=!0,this.expect(14);let t=null,r=null;return this.match(54)?(this.state.inType=e,r=this.flowParsePredicate()):(t=this.flowParseType(),this.state.inType=e,this.match(54)&&(r=this.flowParsePredicate())),[t,r]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();const t=e.id=this.parseIdentifier(),r=this.startNode(),n=this.startNode();this.match(47)?r.typeParameters=this.flowParseTypeParameterDeclaration():r.typeParameters=null,this.expect(10);const s=this.flowParseFunctionTypeParams();return r.params=s.params,r.rest=s.rest,r.this=s._this,this.expect(11),[r.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),n.typeAnnotation=this.finishNode(r,"FunctionTypeAnnotation"),t.typeAnnotation=this.finishNode(n,"TypeAnnotation"),this.resetEndLocation(t),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,t){return this.match(80)?this.flowParseDeclareClass(e):this.match(68)?this.flowParseDeclareFunction(e):this.match(74)?this.flowParseDeclareVariable(e):this.eatContextual(127)?this.match(16)?this.flowParseDeclareModuleExports(e):(t&&this.raise(it.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e)):this.isContextual(130)?this.flowParseDeclareTypeAlias(e):this.isContextual(131)?this.flowParseDeclareOpaqueType(e):this.isContextual(129)?this.flowParseDeclareInterface(e):this.match(82)?this.flowParseDeclareExportDeclaration(e,t):void this.unexpected()}flowParseDeclareVariable(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(!0),this.scope.declareName(e.id.name,5,e.id.loc.start),this.semicolon(),this.finishNode(e,"DeclareVariable")}flowParseDeclareModule(e){this.scope.enter(0),this.match(134)?e.id=super.parseExprAtom():e.id=this.parseIdentifier();const t=e.body=this.startNode(),r=t.body=[];for(this.expect(5);!this.match(8);){let e=this.startNode();this.match(83)?(this.next(),this.isContextual(130)||this.match(87)||this.raise(it.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),super.parseImport(e)):(this.expectContextual(125,it.UnsupportedStatementInDeclareModule),e=this.flowParseDeclare(e,!0)),r.push(e)}this.scope.exit(),this.expect(8),this.finishNode(t,"BlockStatement");let n=null,s=!1;return r.forEach((e=>{!function(e){return"DeclareExportAllDeclaration"===e.type||"DeclareExportDeclaration"===e.type&&(!e.declaration||"TypeAlias"!==e.declaration.type&&"InterfaceDeclaration"!==e.declaration.type)}(e)?"DeclareModuleExports"===e.type&&(s&&this.raise(it.DuplicateDeclareModuleExports,e),"ES"===n&&this.raise(it.AmbiguousDeclareModuleKind,e),n="CommonJS",s=!0):("CommonJS"===n&&this.raise(it.AmbiguousDeclareModuleKind,e),n="ES")})),e.kind=n||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,t){if(this.expect(82),this.eat(65))return this.match(68)||this.match(80)?e.declaration=this.flowParseDeclare(this.startNode()):(e.declaration=this.flowParseType(),this.semicolon()),e.default=!0,this.finishNode(e,"DeclareExportDeclaration");if(this.match(75)||this.isLet()||(this.isContextual(130)||this.isContextual(129))&&!t){const e=this.state.value;throw this.raise(it.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:e,suggestion:ot[e]})}return this.match(74)||this.match(68)||this.match(80)||this.isContextual(131)?(e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration")):this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131)?("ExportNamedDeclaration"===(e=this.parseExport(e,null)).type&&(e.type="ExportDeclaration",e.default=!1,delete e.exportKind),e.type="Declare"+e.type,e):void this.unexpected()}flowParseDeclareModuleExports(e){return this.next(),this.expectContextual(111),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")}flowParseDeclareTypeAlias(e){this.next();const t=this.flowParseTypeAlias(e);return t.type="DeclareTypeAlias",t}flowParseDeclareOpaqueType(e){this.next();const t=this.flowParseOpaqueType(e,!0);return t.type="DeclareOpaqueType",t}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,t){if(e.id=this.flowParseRestrictedIdentifier(!t,!0),this.scope.declareName(e.id.name,t?17:8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],this.eat(81))do{e.extends.push(this.flowParseInterfaceExtends())}while(!t&&this.eat(12));if(t){if(e.implements=[],e.mixins=[],this.eatContextual(117))do{e.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(12));if(this.eatContextual(113))do{e.implements.push(this.flowParseInterfaceExtends())}while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:t,allowExact:!1,allowSpread:!1,allowProto:t,allowInexact:!1})}flowParseInterfaceExtends(){const e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.match(47)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")}flowParseInterface(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")}checkNotUnderscore(e){"_"===e&&this.raise(it.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(e,t,r){st.has(e)&&this.raise(r?it.AssignReservedType:it.UnexpectedReservedType,t,{reservedType:e})}flowParseRestrictedIdentifier(e,t){return this.checkReservedType(this.state.value,this.state.startLoc,t),this.parseIdentifier(e)}flowParseTypeAlias(e){return e.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(29),this.semicolon(),this.finishNode(e,"TypeAlias")}flowParseOpaqueType(e,t){return this.expectContextual(130),e.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(14)&&(e.supertype=this.flowParseTypeInitialiser(14)),e.impltype=null,t||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")}flowParseTypeParameter(e=!1){const t=this.state.startLoc,r=this.startNode(),n=this.flowParseVariance(),s=this.flowParseTypeAnnotatableIdentifier();return r.name=s.name,r.variance=n,r.bound=s.typeAnnotation,this.match(29)?(this.eat(29),r.default=this.flowParseType()):e&&this.raise(it.MissingTypeParamDefault,t),this.finishNode(r,"TypeParameter")}flowParseTypeParameterDeclaration(){const e=this.state.inType,t=this.startNode();t.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let r=!1;do{const e=this.flowParseTypeParameter(r);t.params.push(e),e.default&&(r=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(t,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()===S.brace)return e();{const t=this.state.context;this.state.context=[t[0]];try{return e()}finally{this.state.context=t}}}flowParseTypeParameterInstantiationInExpression(){if(47===this.reScan_lt())return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){const e=this.startNode(),t=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext((()=>{this.expect(47);const t=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.match(48);)e.params.push(this.flowParseType()),this.match(48)||this.expect(12);this.state.noAnonFunctionType=t})),this.state.inType=t,this.state.inType||this.curContext()!==S.brace||this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(47!==this.reScan_lt())return;const e=this.startNode(),t=this.state.inType;for(e.params=[],this.state.inType=!0,this.expect(47);!this.match(48);)e.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(48)||this.expect(12);return this.expect(48),this.state.inType=t,this.finishNode(e,"TypeParameterInstantiation")}flowParseInterfaceType(){const e=this.startNode();if(this.expectContextual(129),e.extends=[],this.eat(81))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(12));return e.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(e,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(135)||this.match(134)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(e,t,r){return e.static=t,14===this.lookahead().type?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(3),e.value=this.flowParseTypeInitialiser(),e.variance=r,this.finishNode(e,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(e,t){return e.static=t,e.id=this.flowParseObjectPropertyKey(),this.expect(3),this.expect(3),this.match(47)||this.match(10)?(e.method=!0,e.optional=!1,e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start))):(e.method=!1,this.eat(17)&&(e.optional=!0),e.value=this.flowParseTypeInitialiser()),this.finishNode(e,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(e){for(e.params=[],e.rest=null,e.typeParameters=null,e.this=null,this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(10),this.match(78)&&(e.this=this.flowParseFunctionTypeParam(!0),e.this.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.params.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(e.rest=this.flowParseFunctionTypeParam(!1)),this.expect(11),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(e,t){const r=this.startNode();return e.static=t,e.value=this.flowParseObjectTypeMethodish(r),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:t,allowSpread:r,allowProto:n,allowInexact:s}){const i=this.state.inType;this.state.inType=!0;const a=this.startNode();let o,l;a.callProperties=[],a.properties=[],a.indexers=[],a.internalSlots=[];let c=!1;for(t&&this.match(6)?(this.expect(6),o=9,l=!0):(this.expect(5),o=8,l=!1),a.exact=l;!this.match(o);){let t=!1,i=null,o=null;const p=this.startNode();if(n&&this.isContextual(118)){const t=this.lookahead();14!==t.type&&17!==t.type&&(this.next(),i=this.state.startLoc,e=!1)}if(e&&this.isContextual(106)){const e=this.lookahead();14!==e.type&&17!==e.type&&(this.next(),t=!0)}const u=this.flowParseVariance();if(this.eat(0))null!=i&&this.unexpected(i),this.eat(0)?(u&&this.unexpected(u.loc.start),a.internalSlots.push(this.flowParseObjectTypeInternalSlot(p,t))):a.indexers.push(this.flowParseObjectTypeIndexer(p,t,u));else if(this.match(10)||this.match(47))null!=i&&this.unexpected(i),u&&this.unexpected(u.loc.start),a.callProperties.push(this.flowParseObjectTypeCallProperty(p,t));else{let e="init";(this.isContextual(99)||this.isContextual(104))&&K(this.lookahead().type)&&(e=this.state.value,this.next());const n=this.flowParseObjectTypeProperty(p,t,i,u,e,r,null!=s?s:!l);null===n?(c=!0,o=this.state.lastTokStartLoc):a.properties.push(n)}this.flowObjectTypeSemicolon(),!o||this.match(8)||this.match(9)||this.raise(it.UnexpectedExplicitInexactInObject,o)}this.expect(o),r&&(a.inexact=c);const p=this.finishNode(a,"ObjectTypeAnnotation");return this.state.inType=i,p}flowParseObjectTypeProperty(e,t,r,n,s,i,a){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(i?a||this.raise(it.InexactInsideExact,this.state.lastTokStartLoc):this.raise(it.InexactInsideNonObject,this.state.lastTokStartLoc),n&&this.raise(it.InexactVariance,n),null):(i||this.raise(it.UnexpectedSpreadType,this.state.lastTokStartLoc),null!=r&&this.unexpected(r),n&&this.raise(it.SpreadVariance,n),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=t,e.proto=null!=r,e.kind=s;let a=!1;return this.match(47)||this.match(10)?(e.method=!0,null!=r&&this.unexpected(r),n&&this.unexpected(n.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),"get"!==s&&"set"!==s||this.flowCheckGetterSetterParams(e),!i&&"constructor"===e.key.name&&e.value.this&&this.raise(it.ThisParamBannedInConstructor,e.value.this)):("init"!==s&&this.unexpected(),e.method=!1,this.eat(17)&&(a=!0),e.value=this.flowParseTypeInitialiser(),e.variance=n),e.optional=a,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){const t="get"===e.kind?0:1,r=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise("get"===e.kind?it.GetterMayNotHaveThisParam:it.SetterMayNotHaveThisParam,e.value.this),r!==t&&this.raise("get"===e.kind?g.BadGetterArity:g.BadSetterArity,e),"set"===e.kind&&e.value.rest&&this.raise(g.BadSetterRestParameter,e)}flowObjectTypeSemicolon(){this.eat(13)||this.eat(12)||this.match(8)||this.match(9)||this.unexpected()}flowParseQualifiedTypeIdentifier(e,t){null!=e||(e=this.state.startLoc);let r=t||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){const t=this.startNodeAt(e);t.qualification=r,t.id=this.flowParseRestrictedIdentifier(!0),r=this.finishNode(t,"QualifiedTypeIdentifier")}return r}flowParseGenericType(e,t){const r=this.startNodeAt(e);return r.typeParameters=null,r.id=this.flowParseQualifiedTypeIdentifier(e,t),this.match(47)&&(r.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(r,"GenericTypeAnnotation")}flowParseTypeofType(){const e=this.startNode();return this.expect(87),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")}flowParseTupleType(){const e=this.startNode();for(e.types=[],this.expect(0);this.state.pos<this.length&&!this.match(3)&&(e.types.push(this.flowParseType()),!this.match(3));)this.expect(12);return this.expect(3),this.finishNode(e,"TupleTypeAnnotation")}flowParseFunctionTypeParam(e){let t=null,r=!1,n=null;const s=this.startNode(),i=this.lookahead(),a=78===this.state.type;return 14===i.type||17===i.type?(a&&!e&&this.raise(it.ThisParamMustBeFirst,s),t=this.parseIdentifier(a),this.eat(17)&&(r=!0,a&&this.raise(it.ThisParamMayNotBeOptional,s)),n=this.flowParseTypeInitialiser()):n=this.flowParseType(),s.name=t,s.optional=r,s.typeAnnotation=n,this.finishNode(s,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){const t=this.startNodeAt(e.loc.start);return t.name=null,t.optional=!1,t.typeAnnotation=e,this.finishNode(t,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let t=null,r=null;for(this.match(78)&&(r=this.flowParseFunctionTypeParam(!0),r.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(t=this.flowParseFunctionTypeParam(!1)),{params:e,rest:t,_this:r}}flowIdentToTypeAnnotation(e,t,r){switch(r.name){case"any":return this.finishNode(t,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(t,"BooleanTypeAnnotation");case"mixed":return this.finishNode(t,"MixedTypeAnnotation");case"empty":return this.finishNode(t,"EmptyTypeAnnotation");case"number":return this.finishNode(t,"NumberTypeAnnotation");case"string":return this.finishNode(t,"StringTypeAnnotation");case"symbol":return this.finishNode(t,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(r.name),this.flowParseGenericType(e,r)}}flowParsePrimaryType(){const e=this.state.startLoc,t=this.startNode();let r,n,s=!1;const i=this.state.noAnonFunctionType;switch(this.state.type){case 5:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case 6:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case 0:return this.state.noAnonFunctionType=!1,n=this.flowParseTupleType(),this.state.noAnonFunctionType=i,n;case 47:{const e=this.startNode();return e.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),r=this.flowParseFunctionTypeParams(),e.params=r.params,e.rest=r.rest,e.this=r._this,this.expect(11),this.expect(19),e.returnType=this.flowParseType(),this.finishNode(e,"FunctionTypeAnnotation")}case 10:{const e=this.startNode();if(this.next(),!this.match(11)&&!this.match(21))if(q(this.state.type)||this.match(78)){const e=this.lookahead().type;s=17!==e&&14!==e}else s=!0;if(s){if(this.state.noAnonFunctionType=!1,n=this.flowParseType(),this.state.noAnonFunctionType=i,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&19===this.lookahead().type))return this.expect(11),n;this.eat(12)}return r=n?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(n)]):this.flowParseFunctionTypeParams(),e.params=r.params,e.rest=r.rest,e.this=r._this,this.expect(11),this.expect(19),e.returnType=this.flowParseType(),e.typeParameters=null,this.finishNode(e,"FunctionTypeAnnotation")}case 134:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 85:case 86:return t.value=this.match(85),this.next(),this.finishNode(t,"BooleanLiteralTypeAnnotation");case 53:if("-"===this.state.value){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",t);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",t);throw this.raise(it.UnexpectedSubtractionOperand,this.state.startLoc)}return void this.unexpected();case 135:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 136:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 88:return this.next(),this.finishNode(t,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(t,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(t,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(t,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(H(this.state.type)){const e=Y(this.state.type);return this.next(),super.createIdentifier(t,e)}if(q(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,t,this.parseIdentifier())}this.unexpected()}flowParsePostfixType(){const e=this.state.startLoc;let t=this.flowParsePrimaryType(),r=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){const n=this.startNodeAt(e),s=this.eat(18);r=r||s,this.expect(0),!s&&this.match(3)?(n.elementType=t,this.next(),t=this.finishNode(n,"ArrayTypeAnnotation")):(n.objectType=t,n.indexType=this.flowParseType(),this.expect(3),r?(n.optional=s,t=this.finishNode(n,"OptionalIndexedAccessType")):t=this.finishNode(n,"IndexedAccessType"))}return t}flowParsePrefixType(){const e=this.startNode();return this.eat(17)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){const e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(19)){const t=this.startNodeAt(e.loc.start);return t.params=[this.reinterpretTypeAsFunctionTypeParam(e)],t.rest=null,t.this=null,t.returnType=this.flowParseType(),t.typeParameters=null,this.finishNode(t,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){const e=this.startNode();this.eat(45);const t=this.flowParseAnonFunctionWithoutParens();for(e.types=[t];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){const e=this.startNode();this.eat(43);const t=this.flowParseIntersectionType();for(e.types=[t];this.eat(43);)e.types.push(this.flowParseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){const e=this.state.inType;this.state.inType=!0;const t=this.flowParseUnionType();return this.state.inType=e,t}flowParseTypeOrImplicitInstantiation(){if(132===this.state.type&&"_"===this.state.value){const e=this.state.startLoc,t=this.parseIdentifier();return this.flowParseGenericType(e,t)}return this.flowParseType()}flowParseTypeAnnotation(){const e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(e){const t=e?this.parseIdentifier():this.flowParseRestrictedIdentifier();return this.match(14)&&(t.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(t)),t}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}flowParseVariance(){let e=null;return this.match(53)?(e=this.startNode(),"+"===this.state.value?e.kind="plus":e.kind="minus",this.next(),this.finishNode(e,"Variance")):e}parseFunctionBody(e,t,r=!1){t?this.forwardNoArrowParamsConversionAt(e,(()=>super.parseFunctionBody(e,!0,r))):super.parseFunctionBody(e,!1,r)}parseFunctionBodyAndFinish(e,t,r=!1){if(this.match(14)){const t=this.startNode();[t.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=t.typeAnnotation?this.finishNode(t,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,t,r)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){if(W(this.lookahead().type)){const e=this.startNode();return this.next(),this.flowParseInterface(e)}}else if(this.isContextual(126)){const e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}const t=super.parseStatementLike(e);return void 0!==this.flowPragma||this.isValidDirective(t)||(this.flowPragma=null),t}parseExpressionStatement(e,t,r){if("Identifier"===t.type)if("declare"===t.name){if(this.match(80)||q(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(q(this.state.type)){if("interface"===t.name)return this.flowParseInterface(e);if("type"===t.name)return this.flowParseTypeAlias(e);if("opaque"===t.name)return this.flowParseOpaqueType(e,!1)}return super.parseExpressionStatement(e,t,r)}shouldParseExportDeclaration(){const{type:e}=this.state;return 126===e||G(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){const{type:e}=this.state;return 126===e||G(e)?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(126)){const e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDefaultExpression()}parseConditional(e,t,r){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){const t=this.lookaheadCharCode();if(44===t||61===t||58===t||41===t)return this.setOptionalParametersError(r),e}this.expect(17);const n=this.state.clone(),s=this.state.noArrowAt,i=this.startNodeAt(t);let{consequent:a,failed:o}=this.tryParseConditionalConsequent(),[l,c]=this.getArrowLikeExpressions(a);if(o||c.length>0){const e=[...s];if(c.length>0){this.state=n,this.state.noArrowAt=e;for(let t=0;t<c.length;t++)e.push(c[t].start);({consequent:a,failed:o}=this.tryParseConditionalConsequent()),[l,c]=this.getArrowLikeExpressions(a)}o&&l.length>1&&this.raise(it.AmbiguousConditionalArrow,n.startLoc),o&&1===l.length&&(this.state=n,e.push(l[0].start),this.state.noArrowAt=e,({consequent:a,failed:o}=this.tryParseConditionalConsequent()))}return this.getArrowLikeExpressions(a,!0),this.state.noArrowAt=s,this.expect(14),i.test=e,i.consequent=a,i.alternate=this.forwardNoArrowParamsConversionAt(i,(()=>this.parseMaybeAssign(void 0,void 0))),this.finishNode(i,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);const e=this.parseMaybeAssignAllowIn(),t=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:t}}getArrowLikeExpressions(e,t){const r=[e],n=[];for(;0!==r.length;){const e=r.pop();"ArrowFunctionExpression"===e.type&&"BlockStatement"!==e.body.type?(e.typeParameters||!e.returnType?this.finishArrowValidation(e):n.push(e),r.push(e.body)):"ConditionalExpression"===e.type&&(r.push(e.consequent),r.push(e.alternate))}return t?(n.forEach((e=>this.finishArrowValidation(e))),[n,[]]):function(e,t){const r=[],n=[];for(let s=0;s<e.length;s++)(t(e[s])?r:n).push(e[s]);return[r,n]}(n,(e=>e.params.every((e=>this.isAssignable(e,!0)))))}finishArrowValidation(e){var t;this.toAssignableList(e.params,null==(t=e.extra)?void 0:t.trailingCommaLoc,!1),this.scope.enter(6),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,t){let r;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),r=t(),this.state.noArrowParamsConversionAt.pop()):r=t(),r}parseParenItem(e,t){const r=super.parseParenItem(e,t);if(this.eat(17)&&(r.optional=!0,this.resetEndLocation(e)),this.match(14)){const e=this.startNodeAt(t);return e.expression=r,e.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e,"TypeCastExpression")}return r}assertModuleNodeAllowed(e){"ImportDeclaration"===e.type&&("type"===e.importKind||"typeof"===e.importKind)||"ExportNamedDeclaration"===e.type&&"type"===e.exportKind||"ExportAllDeclaration"===e.type&&"type"===e.exportKind||super.assertModuleNodeAllowed(e)}parseExportDeclaration(e){if(this.isContextual(130)){e.exportKind="type";const t=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(t)}if(this.isContextual(131)){e.exportKind="type";const t=this.startNode();return this.next(),this.flowParseOpaqueType(t,!1)}if(this.isContextual(129)){e.exportKind="type";const t=this.startNode();return this.next(),this.flowParseInterface(t)}if(this.isContextual(126)){e.exportKind="value";const t=this.startNode();return this.next(),this.flowParseEnumDeclaration(t)}return super.parseExportDeclaration(e)}eatExportStar(e){return!!super.eatExportStar(e)||!(!this.isContextual(130)||55!==this.lookahead().type)&&(e.exportKind="type",this.next(),this.next(),!0)}maybeParseExportNamespaceSpecifier(e){const{startLoc:t}=this.state,r=super.maybeParseExportNamespaceSpecifier(e);return r&&"type"===e.exportKind&&this.unexpected(t),r}parseClassId(e,t,r){super.parseClassId(e,t,r),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,t,r){const{startLoc:n}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,t))return;t.declare=!0}super.parseClassMember(e,t,r),t.declare&&("ClassProperty"!==t.type&&"ClassPrivateProperty"!==t.type&&"PropertyDefinition"!==t.type?this.raise(it.DeclareClassElement,n):t.value&&this.raise(it.DeclareClassFieldInitializer,t.value))}isIterator(e){return"iterator"===e||"asyncIterator"===e}readIterator(){const e=super.readWord1(),t="@@"+e;this.isIterator(e)&&this.state.inType||this.raise(g.InvalidIdentifier,this.state.curPosition(),{identifierName:t}),this.finishToken(132,t)}getTokenFromCode(e){const t=this.input.charCodeAt(this.state.pos+1);123===e&&124===t?this.finishOp(6,2):!this.state.inType||62!==e&&60!==e?this.state.inType&&63===e?46===t?this.finishOp(18,2):this.finishOp(17,1):function(e,t,r){return 64===e&&64===t&&ie(r)}(e,t,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e):this.finishOp(62===e?48:47,1)}isAssignable(e,t){return"TypeCastExpression"===e.type?this.isAssignable(e.expression,t):super.isAssignable(e,t)}toAssignable(e,t=!1){t||"AssignmentExpression"!==e.type||"TypeCastExpression"!==e.left.type||(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,t)}toAssignableList(e,t,r){for(let t=0;t<e.length;t++){const r=e[t];"TypeCastExpression"===(null==r?void 0:r.type)&&(e[t]=this.typeCastToParameter(r))}super.toAssignableList(e,t,r)}toReferencedList(e,t){for(let n=0;n<e.length;n++){var r;const s=e[n];!s||"TypeCastExpression"!==s.type||null!=(r=s.extra)&&r.parenthesized||!(e.length>1)&&t||this.raise(it.TypeCastInPattern,s.typeAnnotation)}return e}parseArrayLike(e,t,r,n){const s=super.parseArrayLike(e,t,r,n);return t&&!this.state.maybeInArrowParameters&&this.toReferencedList(s.elements),s}isValidLVal(e,t,r){return"TypeCastExpression"===e||super.isValidLVal(e,t,r)}parseClassProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(e)}parseClassPrivateProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(e){return!this.match(14)&&super.isNonstaticConstructor(e)}pushClassMethod(e,t,r,n,s,i){if(t.variance&&this.unexpected(t.variance.loc.start),delete t.variance,this.match(47)&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,t,r,n,s,i),t.params&&s){const e=t.params;e.length>0&&this.isThisParam(e[0])&&this.raise(it.ThisParamBannedInConstructor,t)}else if("MethodDefinition"===t.type&&s&&t.value.params){const e=t.value.params;e.length>0&&this.isThisParam(e[0])&&this.raise(it.ThisParamBannedInConstructor,t)}}pushClassPrivateMethod(e,t,r,n){t.variance&&this.unexpected(t.variance.loc.start),delete t.variance,this.match(47)&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,t,r,n)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();const t=e.implements=[];do{const e=this.startNode();e.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,t.push(this.finishNode(e,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);const t=this.getObjectOrClassMethodParams(e);if(t.length>0){const r=t[0];this.isThisParam(r)&&"get"===e.kind?this.raise(it.GetterMayNotHaveThisParam,r):this.isThisParam(r)&&this.raise(it.SetterMayNotHaveThisParam,r)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,t,r,n,s,i,a){let o;e.variance&&this.unexpected(e.variance.loc.start),delete e.variance,this.match(47)&&!i&&(o=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());const l=super.parseObjPropValue(e,t,r,n,s,i,a);return o&&((l.value||l).typeParameters=o),l}parseFunctionParamType(e){return this.eat(17)&&("Identifier"!==e.type&&this.raise(it.PatternIsOptional,e),this.isThisParam(e)&&this.raise(it.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(it.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(it.ThisParamNoDefault,e),this.resetEndLocation(e),e}parseMaybeDefault(e,t){const r=super.parseMaybeDefault(e,t);return"AssignmentPattern"===r.type&&r.typeAnnotation&&r.right.start<r.typeAnnotation.start&&this.raise(it.TypeBeforeInitializer,r.typeAnnotation),r}checkImportReflection(e){super.checkImportReflection(e),e.module&&"value"!==e.importKind&&this.raise(it.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,t,r){t.local=at(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(t,r))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;const t=this.lookaheadCharCode();return 123===t||42===t}return!e&&this.isContextual(87)}applyImportPhase(e,t,r,n){if(super.applyImportPhase(e,t,r,n),t){if(!r&&this.match(65))return;e.exportKind="type"===r?r:"value"}else"type"===r&&this.match(55)&&this.unexpected(),e.importKind="type"===r||"typeof"===r?r:"value"}parseImportSpecifier(e,t,r,n,s){const i=e.imported;let a=null;"Identifier"===i.type&&("type"===i.name?a="type":"typeof"===i.name&&(a="typeof"));let o=!1;if(this.isContextual(93)&&!this.isLookaheadContextual("as")){const t=this.parseIdentifier(!0);null===a||W(this.state.type)?(e.imported=i,e.importKind=null,e.local=this.parseIdentifier()):(e.imported=t,e.importKind=a,e.local=rt(t))}else{if(null!==a&&W(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=a;else{if(t)throw this.raise(g.ImportBindingIsString,e,{importName:i.value});e.imported=i,e.importKind=null}this.eatContextual(93)?e.local=this.parseIdentifier():(o=!0,e.local=rt(e.imported))}const l=at(e);return r&&l&&this.raise(it.ImportTypeShorthandOnlyInPureImport,e),(r||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),!o||r||l||this.checkReservedWord(e.local.name,e.loc.start,!0,!0),this.finishImportSpecifier(e,"ImportSpecifier")}parseBindingAtom(){return 78===this.state.type?this.parseIdentifier(!0):super.parseBindingAtom()}parseFunctionParams(e,t){const r=e.kind;"get"!==r&&"set"!==r&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,t)}parseVarId(e,t){super.parseVarId(e,t),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,t){if(this.match(14)){const t=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=t}return super.parseAsyncArrowFromCallExpression(e,t)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,t){var r;let n,s=null;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(s=this.state.clone(),n=this.tryParse((()=>super.parseMaybeAssign(e,t)),s),!n.error)return n.node;const{context:r}=this.state,i=r[r.length-1];i!==S.j_oTag&&i!==S.j_expr||r.pop()}if(null!=(r=n)&&r.error||this.match(47)){var i,a;let r;s=s||this.state.clone();const o=this.tryParse((n=>{var s;r=this.flowParseTypeParameterDeclaration();const i=this.forwardNoArrowParamsConversionAt(r,(()=>{const n=super.parseMaybeAssign(e,t);return this.resetStartLocationFromNode(n,r),n}));null!=(s=i.extra)&&s.parenthesized&&n();const a=this.maybeUnwrapTypeCastExpression(i);return"ArrowFunctionExpression"!==a.type&&n(),a.typeParameters=r,this.resetStartLocationFromNode(a,r),i}),s);let l=null;if(o.node&&"ArrowFunctionExpression"===this.maybeUnwrapTypeCastExpression(o.node).type){if(!o.error&&!o.aborted)return o.node.async&&this.raise(it.UnexpectedTypeParameterBeforeAsyncArrowFunction,r),o.node;l=o.node}if(null!=(i=n)&&i.node)return this.state=n.failState,n.node;if(l)return this.state=o.failState,l;if(null!=(a=n)&&a.thrown)throw n.error;if(o.thrown)throw o.error;throw this.raise(it.UnexpectedTokenAfterTypeParameter,r)}return super.parseMaybeAssign(e,t)}parseArrow(e){if(this.match(14)){const t=this.tryParse((()=>{const t=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;const r=this.startNode();return[r.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=t,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),r}));if(t.thrown)return null;t.error&&(this.state=t.failState),e.returnType=t.node.typeAnnotation?this.finishNode(t.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,t){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=t:super.setArrowFunctionParameters(e,t)}checkParams(e,t,r,n=!0){if(!r||!this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))){for(let t=0;t<e.params.length;t++)this.isThisParam(e.params[t])&&t>0&&this.raise(it.ThisParamMustBeFirst,e.params[t]);super.checkParams(e,t,r,n)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,t,r){if("Identifier"===e.type&&"async"===e.name&&this.state.noArrowAt.includes(t.index)){this.next();const r=this.startNodeAt(t);r.callee=e,r.arguments=super.parseCallExpressionArguments(11),e=this.finishNode(r,"CallExpression")}else if("Identifier"===e.type&&"async"===e.name&&this.match(47)){const n=this.state.clone(),s=this.tryParse((e=>this.parseAsyncArrowWithTypeParameters(t)||e()),n);if(!s.error&&!s.aborted)return s.node;const i=this.tryParse((()=>super.parseSubscripts(e,t,r)),n);if(i.node&&!i.error)return i.node;if(s.node)return this.state=s.failState,s.node;if(i.node)return this.state=i.failState,i.node;throw s.error||i.error}return super.parseSubscripts(e,t,r)}parseSubscript(e,t,r,n){if(this.match(18)&&this.isLookaheadToken_lt()){if(n.optionalChainMember=!0,r)return n.stop=!0,e;this.next();const s=this.startNodeAt(t);return s.callee=e,s.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),s.arguments=this.parseCallExpressionArguments(11),s.optional=!0,this.finishCallExpression(s,!0)}if(!r&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){const r=this.startNodeAt(t);r.callee=e;const s=this.tryParse((()=>(r.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),r.arguments=super.parseCallExpressionArguments(11),n.optionalChainMember&&(r.optional=!1),this.finishCallExpression(r,n.optionalChainMember))));if(s.node)return s.error&&(this.state=s.failState),s.node}return super.parseSubscript(e,t,r,n)}parseNewCallee(e){super.parseNewCallee(e);let t=null;this.shouldParseTypes()&&this.match(47)&&(t=this.tryParse((()=>this.flowParseTypeParameterInstantiationCallOrNew())).node),e.typeArguments=t}parseAsyncArrowWithTypeParameters(e){const t=this.startNodeAt(e);if(this.parseFunctionParams(t,!1),this.parseArrow(t))return super.parseArrowExpression(t,void 0,!0)}readToken_mult_modulo(e){const t=this.input.charCodeAt(this.state.pos+1);if(42===e&&47===t&&this.state.hasFlowComment)return this.state.hasFlowComment=!1,this.state.pos+=2,void this.nextToken();super.readToken_mult_modulo(e)}readToken_pipe_amp(e){const t=this.input.charCodeAt(this.state.pos+1);124!==e||125!==t?super.readToken_pipe_amp(e):this.finishOp(9,2)}parseTopLevel(e,t){const r=super.parseTopLevel(e,t);return this.state.hasFlowComment&&this.raise(it.UnterminatedFlowComment,this.state.curPosition()),r}skipBlockComment(){if(!this.hasPlugin("flowComments")||!this.skipFlowComment())return super.skipBlockComment(this.state.hasFlowComment?"*-/":"*/");{if(this.state.hasFlowComment)throw this.raise(it.NestedFlowComment,this.state.startLoc);this.hasFlowCommentCompletion();const e=this.skipFlowComment();e&&(this.state.pos+=e,this.state.hasFlowComment=!0)}}skipFlowComment(){const{pos:e}=this.state;let t=2;for(;[32,9].includes(this.input.charCodeAt(e+t));)t++;const r=this.input.charCodeAt(t+e),n=this.input.charCodeAt(t+e+1);return 58===r&&58===n?t+2:"flow-include"===this.input.slice(t+e,t+e+12)?t+12:58===r&&58!==n&&t}hasFlowCommentCompletion(){if(-1===this.input.indexOf("*/",this.state.pos))throw this.raise(g.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:t,memberName:r}){this.raise(it.EnumBooleanMemberNotInitialized,e,{memberName:r,enumName:t})}flowEnumErrorInvalidMemberInitializer(e,t){return this.raise(t.explicitType?"symbol"===t.explicitType?it.EnumInvalidMemberInitializerSymbolType:it.EnumInvalidMemberInitializerPrimaryType:it.EnumInvalidMemberInitializerUnknownType,e,t)}flowEnumErrorNumberMemberNotInitialized(e,t){this.raise(it.EnumNumberMemberNotInitialized,e,t)}flowEnumErrorStringMemberInconsistentlyInitialized(e,t){this.raise(it.EnumStringMemberInconsistentlyInitialized,e,t)}flowEnumMemberInit(){const e=this.state.startLoc,t=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{const r=this.parseNumericLiteral(this.state.value);return t()?{type:"number",loc:r.loc.start,value:r}:{type:"invalid",loc:e}}case 134:{const r=this.parseStringLiteral(this.state.value);return t()?{type:"string",loc:r.loc.start,value:r}:{type:"invalid",loc:e}}case 85:case 86:{const r=this.parseBooleanLiteral(this.match(85));return t()?{type:"boolean",loc:r.loc.start,value:r}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){const e=this.state.startLoc;return{id:this.parseIdentifier(!0),init:this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e}}}flowEnumCheckExplicitTypeMismatch(e,t,r){const{explicitType:n}=t;null!==n&&n!==r&&this.flowEnumErrorInvalidMemberInitializer(e,t)}flowEnumMembers({enumName:e,explicitType:t}){const r=new Set,n={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]};let s=!1;for(;!this.match(8);){if(this.eat(21)){s=!0;break}const i=this.startNode(),{id:a,init:o}=this.flowEnumMemberRaw(),l=a.name;if(""===l)continue;/^[a-z]/.test(l)&&this.raise(it.EnumInvalidMemberName,a,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:e}),r.has(l)&&this.raise(it.EnumDuplicateMemberName,a,{memberName:l,enumName:e}),r.add(l);const c={enumName:e,explicitType:t,memberName:l};switch(i.id=a,o.type){case"boolean":this.flowEnumCheckExplicitTypeMismatch(o.loc,c,"boolean"),i.init=o.value,n.booleanMembers.push(this.finishNode(i,"EnumBooleanMember"));break;case"number":this.flowEnumCheckExplicitTypeMismatch(o.loc,c,"number"),i.init=o.value,n.numberMembers.push(this.finishNode(i,"EnumNumberMember"));break;case"string":this.flowEnumCheckExplicitTypeMismatch(o.loc,c,"string"),i.init=o.value,n.stringMembers.push(this.finishNode(i,"EnumStringMember"));break;case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(o.loc,c);case"none":switch(t){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(o.loc,c);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(o.loc,c);break;default:n.defaultedMembers.push(this.finishNode(i,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:n,hasUnknownMembers:s}}flowEnumStringMembers(e,t,{enumName:r}){if(0===e.length)return t;if(0===t.length)return e;if(t.length>e.length){for(const t of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(t,{enumName:r});return t}for(const e of t)this.flowEnumErrorStringMemberInconsistentlyInitialized(e,{enumName:r});return e}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!q(this.state.type))throw this.raise(it.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});const{value:t}=this.state;return this.next(),"boolean"!==t&&"number"!==t&&"string"!==t&&"symbol"!==t&&this.raise(it.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:t}),t}flowEnumBody(e,t){const r=t.name,n=t.loc.start,s=this.flowEnumParseExplicitType({enumName:r});this.expect(5);const{members:i,hasUnknownMembers:a}=this.flowEnumMembers({enumName:r,explicitType:s});switch(e.hasUnknownMembers=a,s){case"boolean":return e.explicitType=!0,e.members=i.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody");case"number":return e.explicitType=!0,e.members=i.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody");case"string":return e.explicitType=!0,e.members=this.flowEnumStringMembers(i.stringMembers,i.defaultedMembers,{enumName:r}),this.expect(8),this.finishNode(e,"EnumStringBody");case"symbol":return e.members=i.defaultedMembers,this.expect(8),this.finishNode(e,"EnumSymbolBody");default:{const t=()=>(e.members=[],this.expect(8),this.finishNode(e,"EnumStringBody"));e.explicitType=!1;const s=i.booleanMembers.length,a=i.numberMembers.length,o=i.stringMembers.length,l=i.defaultedMembers.length;if(s||a||o||l){if(s||a){if(!a&&!o&&s>=l){for(const e of i.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(e.loc.start,{enumName:r,memberName:e.id.name});return e.members=i.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody")}if(!s&&!o&&a>=l){for(const e of i.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(e.loc.start,{enumName:r,memberName:e.id.name});return e.members=i.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}return this.raise(it.EnumInconsistentMemberValues,n,{enumName:r}),t()}return e.members=this.flowEnumStringMembers(i.stringMembers,i.defaultedMembers,{enumName:r}),this.expect(8),this.finishNode(e,"EnumStringBody")}return t()}}}flowParseEnumDeclaration(e){const t=this.parseIdentifier();return e.id=t,e.body=this.flowEnumBody(this.startNode(),t),this.finishNode(e,"EnumDeclaration")}jsxParseOpeningElementAfterName(e){return this.shouldParseTypes()&&(this.match(47)||this.match(51))&&(e.typeArguments=this.flowParseTypeParameterInstantiationInExpression()),super.jsxParseOpeningElementAfterName(e)}isLookaheadToken_lt(){const e=this.nextTokenStart();if(60===this.input.charCodeAt(e)){const t=this.input.charCodeAt(e+1);return 60!==t&&61!==t}return!1}reScan_lt_gt(){const{type:e}=this.state;47===e?(this.state.pos-=1,this.readToken_lt()):48===e&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){const{type:e}=this.state;return 51===e?(this.state.pos-=2,this.finishOp(47,1),47):e}maybeUnwrapTypeCastExpression(e){return"TypeCastExpression"===e.type?e.expression:e}},typescript:e=>class extends e{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:bt.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:bt.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:bt.InvalidModifierOnTypeParameter})}getScopeHandler(){return ht}tsIsIdentifier(){return q(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(139)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){return this.next(),!this.hasPrecedingLineBreak()&&this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){return this.match(106)?(this.next(),this.tsTokenCanFollowModifier()):this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(e,t){if(!q(this.state.type)&&58!==this.state.type&&75!==this.state.type)return;const r=this.state.value;if(e.includes(r)){if(t&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return r}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:t,stopOnStartOfClassStaticBlock:r,errorTemplate:n=bt.InvalidModifierOnTypeMember},s){const i=(e,t,r,n)=>{t===r&&s[n]&&this.raise(bt.InvalidModifiersOrder,e,{orderedModifiers:[r,n]})},a=(e,t,r,n)=>{(s[r]&&t===n||s[n]&&t===r)&&this.raise(bt.IncompatibleModifiers,e,{modifiers:[r,n]})};for(;;){const{startLoc:o}=this.state,l=this.tsParseModifier(e.concat(null!=t?t:[]),r);if(!l)break;vt(l)?s.accessibility?this.raise(bt.DuplicateAccessibilityModifier,o,{modifier:l}):(i(o,l,l,"override"),i(o,l,l,"static"),i(o,l,l,"readonly"),s.accessibility=l):Tt(l)?(s[l]&&this.raise(bt.DuplicateModifier,o,{modifier:l}),s[l]=!0,i(o,l,"in","out")):(hasOwnProperty.call(s,l)?this.raise(bt.DuplicateModifier,o,{modifier:l}):(i(o,l,"static","readonly"),i(o,l,"static","override"),i(o,l,"override","readonly"),i(o,l,"abstract","override"),a(o,l,"declare","override"),a(o,l,"static","abstract")),s[l]=!0),null!=t&&t.includes(l)&&this.raise(n,o,{modifier:l})}}tsIsListTerminator(e){switch(e){case"EnumMembers":case"TypeMembers":return this.match(8);case"HeritageClauseElement":return this.match(5);case"TupleElementTypes":return this.match(3);case"TypeParametersOrArguments":return this.match(48)}}tsParseList(e,t){const r=[];for(;!this.tsIsListTerminator(e);)r.push(t());return r}tsParseDelimitedList(e,t,r){return function(e){if(null==e)throw new Error(`Unexpected ${e} value.`);return e}(this.tsParseDelimitedListWorker(e,t,!0,r))}tsParseDelimitedListWorker(e,t,r,n){const s=[];let i=-1;for(;!this.tsIsListTerminator(e);){i=-1;const n=t();if(null==n)return;if(s.push(n),!this.eat(12)){if(this.tsIsListTerminator(e))break;return void(r&&this.expect(12))}i=this.state.lastTokStartLoc.index}return n&&(n.value=i),s}tsParseBracketedList(e,t,r,n,s){n||(r?this.expect(0):this.expect(47));const i=this.tsParseDelimitedList(e,t,s);return r?this.expect(3):this.expect(48),i}tsParseImportType(){const e=this.startNode();return this.expect(83),this.expect(10),this.match(134)?e.argument=this.parseStringLiteral(this.state.value):(this.raise(bt.UnsupportedImportTypeArgument,this.state.startLoc),e.argument=super.parseExprAtom()),this.eat(12)&&!this.match(11)?(e.options=super.parseMaybeAssignAllowIn(),this.eat(12)):e.options=null,this.expect(11),this.eat(16)&&(e.qualifier=this.tsParseEntityName(3)),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSImportType")}tsParseEntityName(e){let t;if(1&e&&this.match(78))if(2&e)t=this.parseIdentifier(!0);else{const e=this.startNode();this.next(),t=this.finishNode(e,"ThisExpression")}else t=this.parseIdentifier(!!(1&e));for(;this.eat(16);){const r=this.startNodeAtNode(t);r.left=t,r.right=this.parseIdentifier(!!(1&e)),t=this.finishNode(r,"TSQualifiedName")}return t}tsParseTypeReference(){const e=this.startNode();return e.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeReference")}tsParseThisTypePredicate(e){this.next();const t=this.startNodeAtNode(e);return t.parameterName=e,t.typeAnnotation=this.tsParseTypeAnnotation(!1),t.asserts=!1,this.finishNode(t,"TSTypePredicate")}tsParseThisTypeNode(){const e=this.startNode();return this.next(),this.finishNode(e,"TSThisType")}tsParseTypeQuery(){const e=this.startNode();return this.expect(87),this.match(83)?e.exprName=this.tsParseImportType():e.exprName=this.tsParseEntityName(3),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeQuery")}tsParseTypeParameter(e){const t=this.startNode();return e(t),t.name=this.tsParseTypeParameterName(),t.constraint=this.tsEatThenParseType(81),t.default=this.tsEatThenParseType(29),this.finishNode(t,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){const t=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();const r={value:-1};return t.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,r),0===t.params.length&&this.raise(bt.EmptyTypeParameters,t),-1!==r.value&&this.addExtra(t,"trailingComma",r.value),this.finishNode(t,"TSTypeParameterDeclaration")}tsFillSignature(e,t){const r=19===e;t.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),t.parameters=this.tsParseBindingListForSignature(),(r||this.match(e))&&(t.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){const e=super.parseBindingList(11,41,2);for(const t of e){const{type:e}=t;"AssignmentPattern"!==e&&"TSParameterProperty"!==e||this.raise(bt.UnsupportedSignatureParameterKind,t,{type:e})}return e}tsParseTypeMemberSemicolon(){this.eat(12)||this.isLineTerminator()||this.expect(13)}tsParseSignatureMember(e,t){return this.tsFillSignature(14,t),this.tsParseTypeMemberSemicolon(),this.finishNode(t,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),!!q(this.state.type)&&(this.next(),this.match(14))}tsTryParseIndexSignature(e){if(!this.match(0)||!this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))return;this.expect(0);const t=this.parseIdentifier();t.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(t),this.expect(3),e.parameters=[t];const r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,t){this.eat(17)&&(e.optional=!0);const r=e;if(this.match(10)||this.match(47)){t&&this.raise(bt.ReadonlyForMethodSignature,e);const n=r;n.kind&&this.match(47)&&this.raise(bt.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,n),this.tsParseTypeMemberSemicolon();const s="parameters",i="typeAnnotation";if("get"===n.kind)n[s].length>0&&(this.raise(g.BadGetterArity,this.state.curPosition()),this.isThisParam(n[s][0])&&this.raise(bt.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if("set"===n.kind){if(1!==n[s].length)this.raise(g.BadSetterArity,this.state.curPosition());else{const e=n[s][0];this.isThisParam(e)&&this.raise(bt.AccessorCannotDeclareThisParameter,this.state.curPosition()),"Identifier"===e.type&&e.optional&&this.raise(bt.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),"RestElement"===e.type&&this.raise(bt.SetAccessorCannotHaveRestParameter,this.state.curPosition())}n[i]&&this.raise(bt.SetAccessorCannotHaveReturnType,n[i])}else n.kind="method";return this.finishNode(n,"TSMethodSignature")}{const e=r;t&&(e.readonly=!0);const n=this.tsTryParseTypeAnnotation();return n&&(e.typeAnnotation=n),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSPropertySignature")}}tsParseTypeMember(){const e=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",e);if(this.match(77)){const t=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",e):(e.key=this.createIdentifier(t,"new"),this.tsParsePropertyOrMethodSignature(e,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},e);return this.tsTryParseIndexSignature(e)||(super.parsePropertyName(e),e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||!this.tsTokenCanFollowModifier()||(e.kind=e.key.name,super.parsePropertyName(e)),this.tsParsePropertyOrMethodSignature(e,!!e.readonly))}tsParseTypeLiteral(){const e=this.startNode();return e.members=this.tsParseObjectTypeMembers(),this.finishNode(e,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(5);const e=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(8),e}tsIsStartOfMappedType(){return this.next(),this.eat(53)?this.isContextual(122):(this.isContextual(122)&&this.next(),!!this.match(0)&&(this.next(),!!this.tsIsIdentifier()&&(this.next(),this.match(58))))}tsParseMappedType(){const e=this.startNode();this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(e.readonly=!0),this.expect(0);{const t=this.startNode();t.name=this.tsParseTypeParameterName(),t.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(t,"TSTypeParameter")}return e.nameType=this.eatContextual(93)?this.tsParseType():null,this.expect(3),this.match(53)?(e.optional=this.state.value,this.next(),this.expect(17)):this.eat(17)&&(e.optional=!0),e.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(8),this.finishNode(e,"TSMappedType")}tsParseTupleType(){const e=this.startNode();e.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let t=!1;return e.elementTypes.forEach((e=>{const{type:r}=e;!t||"TSRestType"===r||"TSOptionalType"===r||"TSNamedTupleMember"===r&&e.optional||this.raise(bt.OptionalTypeBeforeRequired,e),t||(t="TSNamedTupleMember"===r&&e.optional||"TSOptionalType"===r)})),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){const e=this.state.startLoc,t=this.eat(21),{startLoc:r}=this.state;let n,s,i,a;const o=W(this.state.type)?this.lookaheadCharCode():null;if(58===o)n=!0,i=!1,s=this.parseIdentifier(!0),this.expect(14),a=this.tsParseType();else if(63===o){i=!0;const e=this.state.value,t=this.tsParseNonArrayType();58===this.lookaheadCharCode()?(n=!0,s=this.createIdentifier(this.startNodeAt(r),e),this.expect(17),this.expect(14),a=this.tsParseType()):(n=!1,a=t,this.expect(17))}else a=this.tsParseType(),i=this.eat(17),n=this.eat(14);if(n){let e;s?(e=this.startNodeAt(r),e.optional=i,e.label=s,e.elementType=a,this.eat(17)&&(e.optional=!0,this.raise(bt.TupleOptionalAfterType,this.state.lastTokStartLoc))):(e=this.startNodeAt(r),e.optional=i,this.raise(bt.InvalidTupleMemberLabel,a),e.label=a,e.elementType=this.tsParseType()),a=this.finishNode(e,"TSNamedTupleMember")}else if(i){const e=this.startNodeAt(r);e.typeAnnotation=a,a=this.finishNode(e,"TSOptionalType")}if(t){const t=this.startNodeAt(e);t.typeAnnotation=a,a=this.finishNode(t,"TSRestType")}return a}tsParseParenthesizedType(){const e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")}tsParseFunctionOrConstructorType(e,t){const r=this.startNode();return"TSConstructorType"===e&&(r.abstract=!!t,t&&this.next(),this.next()),this.tsInAllowConditionalTypesContext((()=>this.tsFillSignature(19,r))),this.finishNode(r,e)}tsParseLiteralTypeNode(){const e=this.startNode();switch(this.state.type){case 135:case 136:case 134:case 85:case 86:e.literal=super.parseExprAtom();break;default:this.unexpected()}return this.finishNode(e,"TSLiteralType")}tsParseTemplateLiteralType(){{const e=this.startNode();return e.literal=super.parseTemplate(!1),this.finishNode(e,"TSLiteralType")}}parseTemplateSubstitution(){return this.state.inType?this.tsParseType():super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){const e=this.tsParseThisTypeNode();return this.isContextual(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e}tsParseNonArrayType(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if("-"===this.state.value){const e=this.startNode(),t=this.lookahead();return 135!==t.type&&136!==t.type&&this.unexpected(),e.literal=this.parseMaybeUnary(),this.finishNode(e,"TSLiteralType")}break;case 78:return this.tsParseThisTypeOrThisTypePredicate();case 87:return this.tsParseTypeQuery();case 83:return this.tsParseImportType();case 5:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 10:return this.tsParseParenthesizedType();case 25:case 24:return this.tsParseTemplateLiteralType();default:{const{type:e}=this.state;if(q(e)||88===e||84===e){const t=88===e?"TSVoidKeyword":84===e?"TSNullKeyword":function(e){switch(e){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}(this.state.value);if(void 0!==t&&46!==this.lookaheadCharCode()){const e=this.startNode();return this.next(),this.finishNode(e,t)}return this.tsParseTypeReference()}}}this.unexpected()}tsParseArrayTypeOrHigher(){const{startLoc:e}=this.state;let t=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){const r=this.startNodeAt(e);r.elementType=t,this.expect(3),t=this.finishNode(r,"TSArrayType")}else{const r=this.startNodeAt(e);r.objectType=t,r.indexType=this.tsParseType(),this.expect(3),t=this.finishNode(r,"TSIndexedAccessType")}return t}tsParseTypeOperator(){const e=this.startNode(),t=this.state.value;return this.next(),e.operator=t,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),"readonly"===t&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(bt.UnexpectedReadonly,e)}}tsParseInferType(){const e=this.startNode();this.expectContextual(115);const t=this.startNode();return t.name=this.tsParseTypeParameterName(),t.constraint=this.tsTryParse((()=>this.tsParseConstraintForInferType())),e.typeParameter=this.finishNode(t,"TSTypeParameter"),this.finishNode(e,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(81)){const e=this.tsInDisallowConditionalTypesContext((()=>this.tsParseType()));if(this.state.inDisallowConditionalTypesContext||!this.match(17))return e}}tsParseTypeOperatorOrHigher(){var e;return(e=this.state.type)>=121&&e<=123&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext((()=>this.tsParseArrayTypeOrHigher()))}tsParseUnionOrIntersectionType(e,t,r){const n=this.startNode(),s=this.eat(r),i=[];do{i.push(t())}while(this.eat(r));return 1!==i.length||s?(n.types=i,this.finishNode(n,e)):i[0]}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),45)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),43)}tsIsStartOfFunctionType(){return!!this.match(47)||this.match(10)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(q(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){const{errors:e}=this.state,t=e.length;try{return this.parseObjectLike(8,!0),e.length===t}catch(e){return!1}}if(this.match(0)){this.next();const{errors:e}=this.state,t=e.length;try{return super.parseBindingList(3,93,1),e.length===t}catch(e){return!1}}return!1}tsIsUnambiguouslyStartOfFunctionType(){if(this.next(),this.match(11)||this.match(21))return!0;if(this.tsSkipParameterStart()){if(this.match(14)||this.match(12)||this.match(17)||this.match(29))return!0;if(this.match(11)&&(this.next(),this.match(19)))return!0}return!1}tsParseTypeOrTypePredicateAnnotation(e){return this.tsInType((()=>{const t=this.startNode();this.expect(e);const r=this.startNode(),n=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(n&&this.match(78)){let e=this.tsParseThisTypeOrThisTypePredicate();return"TSThisType"===e.type?(r.parameterName=e,r.asserts=!0,r.typeAnnotation=null,e=this.finishNode(r,"TSTypePredicate")):(this.resetStartLocationFromNode(e,r),e.asserts=!0),t.typeAnnotation=e,this.finishNode(t,"TSTypeAnnotation")}const s=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!s)return n?(r.parameterName=this.parseIdentifier(),r.asserts=n,r.typeAnnotation=null,t.typeAnnotation=this.finishNode(r,"TSTypePredicate"),this.finishNode(t,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,t);const i=this.tsParseTypeAnnotation(!1);return r.parameterName=s,r.typeAnnotation=i,r.asserts=n,t.typeAnnotation=this.finishNode(r,"TSTypePredicate"),this.finishNode(t,"TSTypeAnnotation")}))}tsTryParseTypeOrTypePredicateAnnotation(){if(this.match(14))return this.tsParseTypeOrTypePredicateAnnotation(14)}tsTryParseTypeAnnotation(){if(this.match(14))return this.tsParseTypeAnnotation()}tsTryParseType(){return this.tsEatThenParseType(14)}tsParseTypePredicatePrefix(){const e=this.parseIdentifier();if(this.isContextual(116)&&!this.hasPrecedingLineBreak())return this.next(),e}tsParseTypePredicateAsserts(){if(109!==this.state.type)return!1;const e=this.state.containsEsc;return this.next(),!(!q(this.state.type)&&!this.match(78)||(e&&this.raise(g.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),0))}tsParseTypeAnnotation(e=!0,t=this.startNode()){return this.tsInType((()=>{e&&this.expect(14),t.typeAnnotation=this.tsParseType()})),this.finishNode(t,"TSTypeAnnotation")}tsParseType(){gt(this.state.inType);const e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;const t=this.startNodeAtNode(e);return t.checkType=e,t.extendsType=this.tsInDisallowConditionalTypesContext((()=>this.tsParseNonConditionalType())),this.expect(17),t.trueType=this.tsInAllowConditionalTypesContext((()=>this.tsParseType())),this.expect(14),t.falseType=this.tsInAllowConditionalTypesContext((()=>this.tsParseType())),this.finishNode(t,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(124)&&77===this.lookahead().type}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(77)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(bt.ReservedTypeAssertion,this.state.startLoc);const e=this.startNode();return e.typeAnnotation=this.tsInType((()=>(this.next(),this.match(75)?this.tsParseTypeReference():this.tsParseType()))),this.expect(48),e.expression=this.parseMaybeUnary(),this.finishNode(e,"TSTypeAssertion")}tsParseHeritageClause(e){const t=this.state.startLoc,r=this.tsParseDelimitedList("HeritageClauseElement",(()=>{const e=this.startNode();return e.expression=this.tsParseEntityName(3),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSExpressionWithTypeArguments")}));return r.length||this.raise(bt.EmptyHeritageClauseType,t,{token:e}),r}tsParseInterfaceDeclaration(e,t={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),t.declare&&(e.declare=!0),q(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(bt.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));const r=this.startNode();return r.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(r,"TSInterfaceBody"),this.finishNode(e,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(e){return e.id=this.parseIdentifier(),this.checkIdentifier(e.id,2),e.typeAnnotation=this.tsInType((()=>{if(e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutModifiers),this.expect(29),this.isContextual(114)&&16!==this.lookahead().type){const e=this.startNode();return this.next(),this.finishNode(e,"TSIntrinsicKeyword")}return this.tsParseType()})),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()===S.brace)return e();{const t=this.state.context;this.state.context=[t[0]];try{return e()}finally{this.state.context=t}}}tsInType(e){const t=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=t}}tsInDisallowConditionalTypesContext(e){const t=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=t}}tsInAllowConditionalTypesContext(e){const t=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=t}}tsEatThenParseType(e){if(this.match(e))return this.tsNextThenParseType()}tsExpectThenParseType(e){return this.tsInType((()=>(this.expect(e),this.tsParseType())))}tsNextThenParseType(){return this.tsInType((()=>(this.next(),this.tsParseType())))}tsParseEnumMember(){const e=this.startNode();return e.id=this.match(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(e.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(e,"TSEnumMember")}tsParseEnumDeclaration(e,t={}){return t.const&&(e.const=!0),t.declare&&(e.declare=!0),this.expectContextual(126),e.id=this.parseIdentifier(),this.checkIdentifier(e.id,e.const?8971:8459),this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumDeclaration")}tsParseEnumBody(){const e=this.startNode();return this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumBody")}tsParseModuleBlock(){const e=this.startNode();return this.scope.enter(0),this.expect(5),super.parseBlockOrModuleBlockBody(e.body=[],void 0,!0,8),this.scope.exit(),this.finishNode(e,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(e,t=!1){if(e.id=this.parseIdentifier(),t||this.checkIdentifier(e.id,1024),this.eat(16)){const t=this.startNode();this.tsParseModuleOrNamespaceDeclaration(t,!0),e.body=t}else this.scope.enter(256),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(e){return this.isContextual(112)?(e.kind="global",e.global=!0,e.id=this.parseIdentifier()):this.match(134)?(e.kind="module",e.id=super.parseStringLiteral(this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(256),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(e,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(e,t,r){e.isExport=r||!1,e.id=t||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);const n=this.tsParseModuleReference();return"type"===e.importKind&&"TSExternalModuleReference"!==n.type&&this.raise(bt.ImportAliasHasImportType,n),e.moduleReference=n,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&40===this.lookaheadCharCode()}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){const e=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),e.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(e,"TSExternalModuleReference")}tsLookAhead(e){const t=this.state.clone(),r=e();return this.state=t,r}tsTryParseAndCatch(e){const t=this.tryParse((t=>e()||t()));if(!t.aborted&&t.node)return t.error&&(this.state=t.failState),t.node}tsTryParse(e){const t=this.state.clone(),r=e();if(void 0!==r&&!1!==r)return r;this.state=t}tsTryParseDeclare(e){if(this.isLineTerminator())return;let t,r=this.state.type;return this.isContextual(100)&&(r=74,t="let"),this.tsInAmbientContext((()=>{switch(r){case 68:return e.declare=!0,super.parseFunctionStatement(e,!1,!1);case 80:return e.declare=!0,this.parseClass(e,!0,!1);case 126:return this.tsParseEnumDeclaration(e,{declare:!0});case 112:return this.tsParseAmbientExternalModuleDeclaration(e);case 75:case 74:return this.match(75)&&this.isLookaheadContextual("enum")?(this.expect(75),this.tsParseEnumDeclaration(e,{const:!0,declare:!0})):(e.declare=!0,this.parseVarStatement(e,t||this.state.value,!0));case 129:{const t=this.tsParseInterfaceDeclaration(e,{declare:!0});if(t)return t}default:if(q(r))return this.tsParseDeclaration(e,this.state.value,!0,null)}}))}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.value,!0,null)}tsParseExpressionStatement(e,t,r){switch(t.name){case"declare":{const t=this.tsTryParseDeclare(e);return t&&(t.declare=!0),t}case"global":if(this.match(5)){this.scope.enter(256),this.prodParam.enter(0);const r=e;return r.kind="global",e.global=!0,r.id=t,r.body=this.tsParseModuleBlock(),this.scope.exit(),this.prodParam.exit(),this.finishNode(r,"TSModuleDeclaration")}break;default:return this.tsParseDeclaration(e,t.name,!1,r)}}tsParseDeclaration(e,t,r,n){switch(t){case"abstract":if(this.tsCheckLineTerminator(r)&&(this.match(80)||q(this.state.type)))return this.tsParseAbstractDeclaration(e,n);break;case"module":if(this.tsCheckLineTerminator(r)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(q(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case"namespace":if(this.tsCheckLineTerminator(r)&&q(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case"type":if(this.tsCheckLineTerminator(r)&&q(this.state.type))return this.tsParseTypeAliasDeclaration(e)}}tsCheckLineTerminator(e){return e?!this.hasFollowingLineBreak()&&(this.next(),!0):!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(e){if(!this.match(47))return;const t=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;const r=this.tsTryParseAndCatch((()=>{const t=this.startNodeAt(e);return t.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(t),t.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),t}));return this.state.maybeInArrowParameters=t,r?super.parseArrowExpression(r,null,!0):void 0}tsParseTypeArgumentsInExpression(){if(47===this.reScan_lt())return this.tsParseTypeArguments()}tsParseTypeArguments(){const e=this.startNode();return e.params=this.tsInType((()=>this.tsInTopLevelContext((()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))))),0===e.params.length?this.raise(bt.EmptyTypeArguments,e):this.state.inType||this.curContext()!==S.brace||this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return(e=this.state.type)>=124&&e<=130;var e}isExportDefaultSpecifier(){return!this.tsIsDeclarationStart()&&super.isExportDefaultSpecifier()}parseAssignableListItem(e,t){const r=this.state.startLoc,n={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},n);const s=n.accessibility,i=n.override,a=n.readonly;4&e||!(s||a||i)||this.raise(bt.UnexpectedParameterModifier,r);const o=this.parseMaybeDefault();2&e&&this.parseFunctionParamType(o);const l=this.parseMaybeDefault(o.loc.start,o);if(s||a||i){const e=this.startNodeAt(r);return t.length&&(e.decorators=t),s&&(e.accessibility=s),a&&(e.readonly=a),i&&(e.override=i),"Identifier"!==l.type&&"AssignmentPattern"!==l.type&&this.raise(bt.UnsupportedParameterPropertyKind,e),e.parameter=l,this.finishNode(e,"TSParameterProperty")}return t.length&&(o.decorators=t),l}isSimpleParameter(e){return"TSParameterProperty"===e.type&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(const t of e.params)"Identifier"!==t.type&&t.optional&&!this.state.isAmbientContext&&this.raise(bt.PatternIsOptional,t)}setArrowFunctionParameters(e,t,r){super.setArrowFunctionParameters(e,t,r),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,t,r=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));const n="FunctionDeclaration"===t?"TSDeclareFunction":"ClassMethod"===t||"ClassPrivateMethod"===t?"TSDeclareMethod":void 0;return n&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,n):"TSDeclareFunction"===n&&this.state.isAmbientContext&&(this.raise(bt.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,n,r):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,t,r))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach((e=>{"TSTypeCastExpression"===(null==e?void 0:e.type)&&this.raise(bt.UnexpectedTypeAnnotation,e.typeAnnotation)}))}toReferencedList(e,t){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,t,r,n){const s=super.parseArrayLike(e,t,r,n);return"ArrayExpression"===s.type&&this.tsCheckForInvalidTypeCasts(s.elements),s}parseSubscript(e,t,r,n){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();const r=this.startNodeAt(t);return r.expression=e,this.finishNode(r,"TSNonNullExpression")}let s=!1;if(this.match(18)&&60===this.lookaheadCharCode()){if(r)return n.stop=!0,e;n.optionalChainMember=s=!0,this.next()}if(this.match(47)||this.match(51)){let i;const a=this.tsTryParseAndCatch((()=>{if(!r&&this.atPossibleAsyncArrow(e)){const e=this.tsTryParseGenericAsyncArrowFunction(t);if(e)return e}const a=this.tsParseTypeArgumentsInExpression();if(!a)return;if(s&&!this.match(10))return void(i=this.state.curPosition());if(z(this.state.type)){const r=super.parseTaggedTemplateExpression(e,t,n);return r.typeParameters=a,r}if(!r&&this.eat(10)){const r=this.startNodeAt(t);return r.callee=e,r.arguments=this.parseCallExpressionArguments(11),this.tsCheckForInvalidTypeCasts(r.arguments),r.typeParameters=a,n.optionalChainMember&&(r.optional=s),this.finishCallExpression(r,n.optionalChainMember)}const o=this.state.type;if(48===o||52===o||10!==o&&$(o)&&!this.hasPrecedingLineBreak())return;const l=this.startNodeAt(t);return l.expression=e,l.typeParameters=a,this.finishNode(l,"TSInstantiationExpression")}));if(i&&this.unexpected(i,10),a)return"TSInstantiationExpression"===a.type&&(this.match(16)||this.match(18)&&40!==this.lookaheadCharCode())&&this.raise(bt.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),a}return super.parseSubscript(e,t,r,n)}parseNewCallee(e){var t;super.parseNewCallee(e);const{callee:r}=e;"TSInstantiationExpression"!==r.type||null!=(t=r.extra)&&t.parenthesized||(e.typeParameters=r.typeParameters,e.callee=r.expression)}parseExprOp(e,t,r){let n;if(J(58)>r&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(n=this.isContextual(120)))){const s=this.startNodeAt(t);return s.expression=e,s.typeAnnotation=this.tsInType((()=>(this.next(),this.match(75)?(n&&this.raise(g.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType()))),this.finishNode(s,n?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(s,t,r)}return super.parseExprOp(e,t,r)}checkReservedWord(e,t,r,n){this.state.isAmbientContext||super.checkReservedWord(e,t,r,n)}checkImportReflection(e){super.checkImportReflection(e),e.module&&"value"!==e.importKind&&this.raise(bt.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){const t=this.lookaheadCharCode();return e?123===t||42===t:61!==t}return!e&&this.isContextual(87)}applyImportPhase(e,t,r,n){super.applyImportPhase(e,t,r,n),t?e.exportKind="type"===r?"type":"value":e.importKind="type"===r||"typeof"===r?r:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let t;if(q(this.state.type)&&61===this.lookaheadCharCode())return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){const r=this.parseMaybeImportPhase(e,!1);if(61===this.lookaheadCharCode())return this.tsParseImportEqualsDeclaration(e,r);t=super.parseImportSpecifiersAndAfter(e,r)}else t=super.parseImport(e);return"type"===t.importKind&&t.specifiers.length>1&&"ImportDefaultSpecifier"===t.specifiers[0].type&&this.raise(bt.TypeImportCannotSpecifyDefaultAndNamed,t),t}parseExport(e,t){if(this.match(83)){const t=e;this.next();let r=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?r=this.parseMaybeImportPhase(t,!1):t.importKind="value",this.tsParseImportEqualsDeclaration(t,r,!0)}if(this.eat(29)){const t=e;return t.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(t,"TSExportAssignment")}if(this.eatContextual(93)){const t=e;return this.expectContextual(128),t.id=this.parseIdentifier(),this.semicolon(),this.finishNode(t,"TSNamespaceExportDeclaration")}return super.parseExport(e,t)}isAbstractClass(){return this.isContextual(124)&&80===this.lookahead().type}parseExportDefaultExpression(){if(this.isAbstractClass()){const e=this.startNode();return this.next(),e.abstract=!0,this.parseClass(e,!0,!0)}if(this.match(129)){const e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseExportDefaultExpression()}parseVarStatement(e,t,r=!1){const{isAmbientContext:n}=this.state,s=super.parseVarStatement(e,t,r||n);if(!n)return s;for(const{id:e,init:r}of s.declarations)r&&("const"!==t||e.typeAnnotation?this.raise(bt.InitializerNotAllowedInAmbientContext,r):St(r,this.hasPlugin("estree"))||this.raise(bt.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,r));return s}parseStatementContent(e,t){if(this.match(75)&&this.isLookaheadContextual("enum")){const e=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(e,{const:!0})}if(this.isContextual(126))return this.tsParseEnumDeclaration(this.startNode());if(this.isContextual(129)){const e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseStatementContent(e,t)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,t){return t.some((t=>vt(t)?e.accessibility===t:!!e[t]))}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&123===this.lookaheadCharCode()}parseClassMember(e,t,r){const n=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:n,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:bt.InvalidModifierOnTypeParameterPositions},t);const s=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(t,n)&&this.raise(bt.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,t)):this.parseClassMemberWithIsStatic(e,t,r,!!t.static)};t.declare?this.tsInAmbientContext(s):s()}parseClassMemberWithIsStatic(e,t,r,n){const s=this.tsTryParseIndexSignature(t);if(s)return e.body.push(s),t.abstract&&this.raise(bt.IndexSignatureHasAbstract,t),t.accessibility&&this.raise(bt.IndexSignatureHasAccessibility,t,{modifier:t.accessibility}),t.declare&&this.raise(bt.IndexSignatureHasDeclare,t),void(t.override&&this.raise(bt.IndexSignatureHasOverride,t));!this.state.inAbstractClass&&t.abstract&&this.raise(bt.NonAbstractClassHasAbstractMethod,t),t.override&&(r.hadSuperClass||this.raise(bt.OverrideNotInSubClass,t)),super.parseClassMemberWithIsStatic(e,t,r,n)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(bt.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(bt.ClassMethodHasDeclare,e)}parseExpressionStatement(e,t,r){return("Identifier"===t.type?this.tsParseExpressionStatement(e,t,r):void 0)||super.parseExpressionStatement(e,t,r)}shouldParseExportDeclaration(){return!!this.tsIsDeclarationStart()||super.shouldParseExportDeclaration()}parseConditional(e,t,r){if(!this.state.maybeInArrowParameters||!this.match(17))return super.parseConditional(e,t,r);const n=this.tryParse((()=>super.parseConditional(e,t)));return n.node?(n.error&&(this.state=n.failState),n.node):(n.error&&super.setOptionalParametersError(r,n.error),e)}parseParenItem(e,t){const r=super.parseParenItem(e,t);if(this.eat(17)&&(r.optional=!0,this.resetEndLocation(e)),this.match(14)){const r=this.startNodeAt(t);return r.expression=e,r.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(r,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext((()=>this.parseExportDeclaration(e)));const t=this.state.startLoc,r=this.eatContextual(125);if(r&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(bt.ExpectedAmbientAfterExportDeclare,this.state.startLoc);const n=q(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return n?(("TSInterfaceDeclaration"===n.type||"TSTypeAliasDeclaration"===n.type||r)&&(e.exportKind="type"),r&&"TSImportEqualsDeclaration"!==n.type&&(this.resetStartLocation(n,t),n.declare=!0),n):null}parseClassId(e,t,r,n){if((!t||r)&&this.isContextual(113))return;super.parseClassId(e,t,r,e.declare?1024:8331);const s=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);s&&(e.typeParameters=s)}parseClassPropertyAnnotation(e){e.optional||(this.eat(35)?e.definite=!0:this.eat(17)&&(e.optional=!0));const t=this.tsTryParseTypeAnnotation();t&&(e.typeAnnotation=t)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&(!e.readonly||e.typeAnnotation)&&this.match(29)&&this.raise(bt.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){const{key:t}=e;this.raise(bt.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:"Identifier"!==t.type||e.computed?`[${this.input.slice(this.offsetToSourcePos(t.start),this.offsetToSourcePos(t.end))}]`:t.name})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(bt.PrivateElementHasAbstract,e),e.accessibility&&this.raise(bt.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(bt.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,t,r,n,s,i){const a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&s&&this.raise(bt.ConstructorHasTypeParameters,a);const{declare:o=!1,kind:l}=t;!o||"get"!==l&&"set"!==l||this.raise(bt.DeclareAccessor,t,{kind:l}),a&&(t.typeParameters=a),super.pushClassMethod(e,t,r,n,s,i)}pushClassPrivateMethod(e,t,r,n){const s=this.tsTryParseTypeParameters(this.tsParseConstModifier);s&&(t.typeParameters=s),super.pushClassPrivateMethod(e,t,r,n)}declareClassPrivateMethodInScope(e,t){"TSDeclareMethod"!==e.type&&("MethodDefinition"!==e.type||hasOwnProperty.call(e.value,"body"))&&super.declareClassPrivateMethodInScope(e,t)}parseClassSuper(e){super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression()),this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,t,r,n,s,i,a){const o=this.tsTryParseTypeParameters(this.tsParseConstModifier);return o&&(e.typeParameters=o),super.parseObjPropValue(e,t,r,n,s,i,a)}parseFunctionParams(e,t){const r=this.tsTryParseTypeParameters(this.tsParseConstModifier);r&&(e.typeParameters=r),super.parseFunctionParams(e,t)}parseVarId(e,t){super.parseVarId(e,t),"Identifier"===e.id.type&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(e.definite=!0);const r=this.tsTryParseTypeAnnotation();r&&(e.id.typeAnnotation=r,this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,t){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,t)}parseMaybeAssign(e,t){var r,n,s,i,a;let o,l,c,p;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(o=this.state.clone(),l=this.tryParse((()=>super.parseMaybeAssign(e,t)),o),!l.error)return l.node;const{context:r}=this.state,n=r[r.length-1];n!==S.j_oTag&&n!==S.j_expr||r.pop()}if(!(null!=(r=l)&&r.error||this.match(47)))return super.parseMaybeAssign(e,t);o&&o!==this.state||(o=this.state.clone());const u=this.tryParse((r=>{var n,s;p=this.tsParseTypeParameters(this.tsParseConstModifier);const i=super.parseMaybeAssign(e,t);return("ArrowFunctionExpression"!==i.type||null!=(n=i.extra)&&n.parenthesized)&&r(),0!==(null==(s=p)?void 0:s.params.length)&&this.resetStartLocationFromNode(i,p),i.typeParameters=p,i}),o);if(!u.error&&!u.aborted)return p&&this.reportReservedArrowTypeParam(p),u.node;if(!l&&(gt(!this.hasPlugin("jsx")),c=this.tryParse((()=>super.parseMaybeAssign(e,t)),o),!c.error))return c.node;if(null!=(n=l)&&n.node)return this.state=l.failState,l.node;if(u.node)return this.state=u.failState,p&&this.reportReservedArrowTypeParam(p),u.node;if(null!=(s=c)&&s.node)return this.state=c.failState,c.node;throw(null==(i=l)?void 0:i.error)||u.error||(null==(a=c)?void 0:a.error)}reportReservedArrowTypeParam(e){var t;1!==e.params.length||e.params[0].constraint||null!=(t=e.extra)&&t.trailingComma||!this.getPluginOption("typescript","disallowAmbiguousJSXLike")||this.raise(bt.ReservedArrowTypeParam,e)}parseMaybeUnary(e,t){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,t)}parseArrow(e){if(this.match(14)){const t=this.tryParse((e=>{const t=this.tsParseTypeOrTypePredicateAnnotation(14);return!this.canInsertSemicolon()&&this.match(19)||e(),t}));if(t.aborted)return;t.thrown||(t.error&&(this.state=t.failState),e.returnType=t.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);const t=this.tsTryParseTypeAnnotation();return t&&(e.typeAnnotation=t),this.resetEndLocation(e),e}isAssignable(e,t){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,t);case"TSParameterProperty":return!0;default:return super.isAssignable(e,t)}}toAssignable(e,t=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,t);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":t?this.expressionScope.recordArrowParameterBindingError(bt.UnexpectedTypeCastInParameter,e):this.raise(bt.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,t);break;case"AssignmentExpression":t||"TSTypeCastExpression"!==e.left.type||(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,t)}}toAssignableParenthesizedExpression(e,t){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,t);break;default:super.toAssignable(e,t)}}checkToRestConversion(e,t){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,t)}}isValidLVal(e,t,r){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":case"TSInstantiationExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(64!==r||!t)&&["expression",!0];default:return super.isValidLVal(e,t,r)}}parseBindingAtom(){return 78===this.state.type?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,t){if(this.match(47)||this.match(51)){const r=this.tsParseTypeArgumentsInExpression();if(this.match(10)){const n=super.parseMaybeDecoratorArguments(e,t);return n.typeParameters=r,n}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,t)}checkCommaAfterRest(e){return this.state.isAmbientContext&&this.match(12)&&this.lookaheadCharCode()===e?(this.next(),!1):super.checkCommaAfterRest(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(35)||this.match(14)||super.isClassProperty()}parseMaybeDefault(e,t){const r=super.parseMaybeDefault(e,t);return"AssignmentPattern"===r.type&&r.typeAnnotation&&r.right.start<r.typeAnnotation.start&&this.raise(bt.TypeAnnotationAfterAssign,r.typeAnnotation),r}getTokenFromCode(e){if(this.state.inType){if(62===e)return void this.finishOp(48,1);if(60===e)return void this.finishOp(47,1)}super.getTokenFromCode(e)}reScan_lt_gt(){const{type:e}=this.state;47===e?(this.state.pos-=1,this.readToken_lt()):48===e&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){const{type:e}=this.state;return 51===e?(this.state.pos-=2,this.finishOp(47,1),47):e}toAssignableList(e,t,r){for(let t=0;t<e.length;t++){const r=e[t];"TSTypeCastExpression"===(null==r?void 0:r.type)&&(e[t]=this.typeCastToParameter(r))}super.toAssignableList(e,t,r)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}shouldParseArrow(e){return this.match(14)?e.every((e=>this.isAssignable(e,!0))):super.shouldParseArrow(e)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(e){if(this.match(47)||this.match(51)){const t=this.tsTryParseAndCatch((()=>this.tsParseTypeArgumentsInExpression()));t&&(e.typeParameters=t)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){const t=super.getGetterSetterExpectedParamCount(e),r=this.getObjectOrClassMethodParams(e)[0];return r&&this.isThisParam(r)?t+1:t}parseCatchClauseParam(){const e=super.parseCatchClauseParam(),t=this.tsTryParseTypeAnnotation();return t&&(e.typeAnnotation=t,this.resetEndLocation(e)),e}tsInAmbientContext(e){const{isAmbientContext:t,strict:r}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=t,this.state.strict=r}}parseClass(e,t,r){const n=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,t,r)}finally{this.state.inAbstractClass=n}}tsParseAbstractDeclaration(e,t){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(t,this.parseClass(e,!0,!1));if(this.isContextual(129)){if(!this.hasFollowingLineBreak())return e.abstract=!0,this.raise(bt.NonClassMethodPropertyHasAbstractModifer,e),this.tsParseInterfaceDeclaration(e)}else this.unexpected(null,80)}parseMethod(e,t,r,n,s,i,a){const o=super.parseMethod(e,t,r,n,s,i,a);if(o.abstract&&(this.hasPlugin("estree")?o.value:o).body){const{key:e}=o;this.raise(bt.AbstractMethodHasImplementation,o,{methodName:"Identifier"!==e.type||o.computed?`[${this.input.slice(this.offsetToSourcePos(e.start),this.offsetToSourcePos(e.end))}]`:e.name})}return o}tsParseTypeParameterName(){return this.parseIdentifier().name}shouldParseAsAmbientContext(){return!!this.getPluginOption("typescript","dts")}parse(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.parse()}getExpression(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.getExpression()}parseExportSpecifier(e,t,r,n){return!t&&n?(this.parseTypeOnlyImportExportSpecifier(e,!1,r),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,t,r,n))}parseImportSpecifier(e,t,r,n,s){return!t&&n?(this.parseTypeOnlyImportExportSpecifier(e,!0,r),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,t,r,n,r?4098:4096))}parseTypeOnlyImportExportSpecifier(e,t,r){const n=t?"imported":"local",s=t?"local":"exported";let i,a=e[n],o=!1,l=!0;const c=a.loc.start;if(this.isContextual(93)){const e=this.parseIdentifier();if(this.isContextual(93)){const r=this.parseIdentifier();W(this.state.type)?(o=!0,a=e,i=t?this.parseIdentifier():this.parseModuleExportName(),l=!1):(i=r,l=!1)}else W(this.state.type)?(l=!1,i=t?this.parseIdentifier():this.parseModuleExportName()):(o=!0,a=e)}else W(this.state.type)&&(o=!0,t?(a=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(a.name,a.loc.start,!0,!0)):a=this.parseModuleExportName());o&&r&&this.raise(t?bt.TypeModifierIsUsedInTypeImports:bt.TypeModifierIsUsedInTypeExports,c),e[n]=a,e[s]=i,e[t?"importKind":"exportKind"]=o?"type":"value",l&&this.eatContextual(93)&&(e[s]=t?this.parseIdentifier():this.parseModuleExportName()),e[s]||(e[s]=rt(e[n])),t&&this.checkIdentifier(e[s],o?4098:4096)}},v8intrinsic:e=>class extends e{parseV8Intrinsic(){if(this.match(54)){const e=this.state.startLoc,t=this.startNode();if(this.next(),q(this.state.type)){const e=this.parseIdentifierName(),r=this.createIdentifier(t,e);if(r.type="V8IntrinsicIdentifier",this.match(10))return r}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},placeholders:e=>class extends e{parsePlaceholder(e){if(this.match(133)){const t=this.startNode();return this.next(),this.assertNoSpace(),t.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(t,e)}}finishPlaceholder(e,t){let r=e;return r.expectedNode&&r.type||(r=this.finishNode(r,"Placeholder")),r.expectedNode=t,r}getTokenFromCode(e){37===e&&37===this.input.charCodeAt(this.state.pos+1)?this.finishOp(133,2):super.getTokenFromCode(e)}parseExprAtom(e){return this.parsePlaceholder("Expression")||super.parseExprAtom(e)}parseIdentifier(e){return this.parsePlaceholder("Identifier")||super.parseIdentifier(e)}checkReservedWord(e,t,r,n){void 0!==e&&super.checkReservedWord(e,t,r,n)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,t,r){return"Placeholder"===e||super.isValidLVal(e,t,r)}toAssignable(e,t){e&&"Placeholder"===e.type&&"Expression"===e.expectedNode?e.expectedNode="Pattern":super.toAssignable(e,t)}chStartsBindingIdentifier(e,t){return!!super.chStartsBindingIdentifier(e,t)||133===this.lookahead().type}verifyBreakContinue(e,t){e.label&&"Placeholder"===e.label.type||super.verifyBreakContinue(e,t)}parseExpressionStatement(e,t){var r;if("Placeholder"!==t.type||null!=(r=t.extra)&&r.parenthesized)return super.parseExpressionStatement(e,t);if(this.match(14)){const r=e;return r.label=this.finishPlaceholder(t,"Identifier"),this.next(),r.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(r,"LabeledStatement")}this.semicolon();const n=e;return n.name=t.name,this.finishPlaceholder(n,"Statement")}parseBlock(e,t,r){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,t,r)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,t,r){const n=t?"ClassDeclaration":"ClassExpression";this.next();const s=this.state.strict,i=this.parsePlaceholder("Identifier");if(i){if(!(this.match(81)||this.match(133)||this.match(5))){if(r||!t)return e.id=null,e.body=this.finishPlaceholder(i,"ClassBody"),this.finishNode(e,n);throw this.raise(At.ClassNameIsRequired,this.state.startLoc)}e.id=i}else this.parseClassId(e,t,r);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,s),this.finishNode(e,n)}parseExport(e,t){const r=this.parsePlaceholder("Identifier");if(!r)return super.parseExport(e,t);const n=e;if(!this.isContextual(98)&&!this.match(12))return n.specifiers=[],n.source=null,n.declaration=this.finishPlaceholder(r,"Declaration"),this.finishNode(n,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");const s=this.startNode();return s.exported=r,n.specifiers=[this.finishNode(s,"ExportDefaultSpecifier")],super.parseExport(n,t)}isExportDefaultSpecifier(){if(this.match(65)){const e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Y(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,t){var r;return!(null==(r=e.specifiers)||!r.length)||super.maybeParseExportDefaultSpecifier(e,t)}checkExport(e){const{specifiers:t}=e;null!=t&&t.length&&(e.specifiers=t.filter((e=>"Placeholder"===e.exported.type))),super.checkExport(e),e.specifiers=t}parseImport(e){const t=this.parsePlaceholder("Identifier");if(!t)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(t,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");const r=this.startNodeAtNode(t);return r.local=t,e.specifiers.push(this.finishNode(r,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(e)||this.parseNamedImportSpecifiers(e)),this.expectContextual(98),e.source=this.parseImportSource(),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(At.UnexpectedSpace,this.state.lastTokEndLoc)}}},It=Object.keys(Ot);class Nt extends yt{checkProto(e,t,r,n){if("SpreadElement"===e.type||this.isObjectMethod(e)||e.computed||e.shorthand)return;const s=e.key;if("__proto__"===("Identifier"===s.type?s.name:s.value)){if(t)return void this.raise(g.RecordNoProto,s);r.used&&(n?null===n.doubleProtoLoc&&(n.doubleProtoLoc=s.loc.start):this.raise(g.DuplicateProto,s)),r.used=!0}}shouldExitDescending(e,t){return"ArrowFunctionExpression"===e.type&&this.offsetToSourcePos(e.start)===t}getExpression(){this.enterInitialScopes(),this.nextToken();const e=this.parseExpression();return this.match(140)||this.unexpected(),this.finalizeRemainingComments(),e.comments=this.comments,e.errors=this.state.errors,128&this.optionFlags&&(e.tokens=this.tokens),e}parseExpression(e,t){return e?this.disallowInAnd((()=>this.parseExpressionBase(t))):this.allowInAnd((()=>this.parseExpressionBase(t)))}parseExpressionBase(e){const t=this.state.startLoc,r=this.parseMaybeAssign(e);if(this.match(12)){const n=this.startNodeAt(t);for(n.expressions=[r];this.eat(12);)n.expressions.push(this.parseMaybeAssign(e));return this.toReferencedList(n.expressions),this.finishNode(n,"SequenceExpression")}return r}parseMaybeAssignDisallowIn(e,t){return this.disallowInAnd((()=>this.parseMaybeAssign(e,t)))}parseMaybeAssignAllowIn(e,t){return this.allowInAnd((()=>this.parseMaybeAssign(e,t)))}setOptionalParametersError(e,t){var r;e.optionalParametersLoc=null!=(r=null==t?void 0:t.loc)?r:this.state.startLoc}parseMaybeAssign(e,t){const r=this.state.startLoc;if(this.isContextual(108)&&this.prodParam.hasYield){let e=this.parseYield();return t&&(e=t.call(this,e,r)),e}let n;e?n=!1:(e=new Ze,n=!0);const{type:s}=this.state;(10===s||q(s))&&(this.state.potentialArrowAt=this.state.start);let i=this.parseMaybeConditional(e);if(t&&(i=t.call(this,i,r)),(a=this.state.type)>=29&&a<=33){const t=this.startNodeAt(r),n=this.state.value;if(t.operator=n,this.match(29)){this.toAssignable(i,!0),t.left=i;const n=r.index;null!=e.doubleProtoLoc&&e.doubleProtoLoc.index>=n&&(e.doubleProtoLoc=null),null!=e.shorthandAssignLoc&&e.shorthandAssignLoc.index>=n&&(e.shorthandAssignLoc=null),null!=e.privateKeyLoc&&e.privateKeyLoc.index>=n&&(this.checkDestructuringPrivate(e),e.privateKeyLoc=null)}else t.left=i;return this.next(),t.right=this.parseMaybeAssign(),this.checkLVal(i,this.finishNode(t,"AssignmentExpression")),t}var a;return n&&this.checkExpressionErrors(e,!0),i}parseMaybeConditional(e){const t=this.state.startLoc,r=this.state.potentialArrowAt,n=this.parseExprOps(e);return this.shouldExitDescending(n,r)?n:this.parseConditional(n,t,e)}parseConditional(e,t,r){if(this.eat(17)){const r=this.startNodeAt(t);return r.test=e,r.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),r.alternate=this.parseMaybeAssign(),this.finishNode(r,"ConditionalExpression")}return e}parseMaybeUnaryOrPrivate(e){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(e)}parseExprOps(e){const t=this.state.startLoc,r=this.state.potentialArrowAt,n=this.parseMaybeUnaryOrPrivate(e);return this.shouldExitDescending(n,r)?n:this.parseExprOp(n,t,-1)}parseExprOp(e,t,r){if(this.isPrivateName(e)){const t=this.getPrivateNameSV(e);(r>=J(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(g.PrivateInExpectedIn,e,{identifierName:t}),this.classScope.usePrivateName(t,e.loc.start)}const n=this.state.type;if((s=n)>=39&&s<=59&&(this.prodParam.hasIn||!this.match(58))){let s=J(n);if(s>r){if(39===n){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return e;this.checkPipelineAtInfixOperator(e,t)}const i=this.startNodeAt(t);i.left=e,i.operator=this.state.value;const a=41===n||42===n,o=40===n;if(o&&(s=J(42)),this.next(),39===n&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&96===this.state.type&&this.prodParam.hasAwait)throw this.raise(g.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);i.right=this.parseExprOpRightExpr(n,s);const l=this.finishNode(i,a||o?"LogicalExpression":"BinaryExpression"),c=this.state.type;if(o&&(41===c||42===c)||a&&40===c)throw this.raise(g.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(l,t,r)}}var s;return e}parseExprOpRightExpr(e,t){const r=this.state.startLoc;if(39===e){switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext((()=>this.parseHackPipeBody()));case"fsharp":return this.withSoloAwaitPermittingContext((()=>this.parseFSharpPipelineBody(t)))}if("smart"===this.getPluginOption("pipelineOperator","proposal"))return this.withTopicBindingContext((()=>{if(this.prodParam.hasYield&&this.isContextual(108))throw this.raise(g.PipeBodyIsTighter,this.state.startLoc);return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(e,t),r)}))}return this.parseExprOpBaseRightExpr(e,t)}parseExprOpBaseRightExpr(e,t){const r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,57===e?t-1:t)}parseHackPipeBody(){var e;const{startLoc:t}=this.state,r=this.parseMaybeAssign();return!u.has(r.type)||null!=(e=r.extra)&&e.parenthesized||this.raise(g.PipeUnparenthesizedBody,t,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(g.PipeTopicUnused,t),r}checkExponentialAfterUnary(e){this.match(57)&&this.raise(g.UnexpectedTokenUnaryExponentiation,e.argument)}parseMaybeUnary(e,t){const r=this.state.startLoc,n=this.isContextual(96);if(n&&this.recordAwaitIfAllowed()){this.next();const e=this.parseAwait(r);return t||this.checkExponentialAfterUnary(e),e}const s=this.match(34),i=this.startNode();if(a=this.state.type,F[a]){i.operator=this.state.value,i.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");const r=this.match(89);if(this.next(),i.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(e,!0),this.state.strict&&r){const e=i.argument;"Identifier"===e.type?this.raise(g.StrictDelete,i):this.hasPropertyAsPrivateName(e)&&this.raise(g.DeletePrivateField,i)}if(!s)return t||this.checkExponentialAfterUnary(i),this.finishNode(i,"UnaryExpression")}var a;const o=this.parseUpdate(i,s,e);if(n){const{type:e}=this.state;if((this.hasPlugin("v8intrinsic")?$(e):$(e)&&!this.match(54))&&!this.isAmbiguousAwait())return this.raiseOverwrite(g.AwaitNotInAsyncContext,r),this.parseAwait(r)}return o}parseUpdate(e,t,r){if(t){const t=e;return this.checkLVal(t.argument,this.finishNode(t,"UpdateExpression")),e}const n=this.state.startLoc;let s=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return s;for(;34===this.state.type&&!this.canInsertSemicolon();){const e=this.startNodeAt(n);e.operator=this.state.value,e.prefix=!1,e.argument=s,this.next(),this.checkLVal(s,s=this.finishNode(e,"UpdateExpression"))}return s}parseExprSubscripts(e){const t=this.state.startLoc,r=this.state.potentialArrowAt,n=this.parseExprAtom(e);return this.shouldExitDescending(n,r)?n:this.parseSubscripts(n,t)}parseSubscripts(e,t,r){const n={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(e),stop:!1};do{e=this.parseSubscript(e,t,r,n),n.maybeAsyncArrow=!1}while(!n.stop);return e}parseSubscript(e,t,r,n){const{type:s}=this.state;if(!r&&15===s)return this.parseBind(e,t,r,n);if(z(s))return this.parseTaggedTemplateExpression(e,t,n);let i=!1;if(18===s){if(r&&(this.raise(g.OptionalChainingNoNew,this.state.startLoc),40===this.lookaheadCharCode()))return n.stop=!0,e;n.optionalChainMember=i=!0,this.next()}if(!r&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(e,t,n,i);{const r=this.eat(0);return r||i||this.eat(16)?this.parseMember(e,t,n,r,i):(n.stop=!0,e)}}parseMember(e,t,r,n,s){const i=this.startNodeAt(t);return i.object=e,i.computed=n,n?(i.property=this.parseExpression(),this.expect(3)):this.match(139)?("Super"===e.type&&this.raise(g.SuperPrivateField,t),this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),r.optionalChainMember?(i.optional=s,this.finishNode(i,"OptionalMemberExpression")):this.finishNode(i,"MemberExpression")}parseBind(e,t,r,n){const s=this.startNodeAt(t);return s.object=e,this.next(),s.callee=this.parseNoCallExpr(),n.stop=!0,this.parseSubscripts(this.finishNode(s,"BindExpression"),t,r)}parseCoverCallAndAsyncArrowHead(e,t,r,n){const s=this.state.maybeInArrowParameters;let i=null;this.state.maybeInArrowParameters=!0,this.next();const a=this.startNodeAt(t);a.callee=e;const{maybeAsyncArrow:o,optionalChainMember:l}=r;o&&(this.expressionScope.enter(new He(2)),i=new Ze),l&&(a.optional=n),a.arguments=n?this.parseCallExpressionArguments(11):this.parseCallExpressionArguments(11,"Super"!==e.type,a,i);let c=this.finishCallExpression(a,l);return o&&this.shouldParseAsyncArrow()&&!n?(r.stop=!0,this.checkDestructuringPrivate(i),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),c=this.parseAsyncArrowFromCallExpression(this.startNodeAt(t),c)):(o&&(this.checkExpressionErrors(i,!0),this.expressionScope.exit()),this.toReferencedArguments(c)),this.state.maybeInArrowParameters=s,c}toReferencedArguments(e,t){this.toReferencedListDeep(e.arguments,t)}parseTaggedTemplateExpression(e,t,r){const n=this.startNodeAt(t);return n.tag=e,n.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(g.OptionalChainingNoTemplate,t),this.finishNode(n,"TaggedTemplateExpression")}atPossibleAsyncArrow(e){return"Identifier"===e.type&&"async"===e.name&&this.state.lastTokEndLoc.index===e.end&&!this.canInsertSemicolon()&&e.end-e.start==5&&this.offsetToSourcePos(e.start)===this.state.potentialArrowAt}finishCallExpression(e,t){if("Import"===e.callee.type)if(0===e.arguments.length||e.arguments.length>2)this.raise(g.ImportCallArity,e);else for(const t of e.arguments)"SpreadElement"===t.type&&this.raise(g.ImportCallSpreadArgument,t);return this.finishNode(e,t?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(e,t,r,n){const s=[];let i=!0;const a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(e);){if(i)i=!1;else if(this.expect(12),this.match(e)){r&&this.addTrailingCommaExtraToNode(r),this.next();break}s.push(this.parseExprListItem(!1,n,t))}return this.state.inFSharpPipelineDirectBody=a,s}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(e,t){var r;return this.resetPreviousNodeTrailingComments(t),this.expect(19),this.parseArrowExpression(e,t.arguments,!0,null==(r=t.extra)?void 0:r.trailingCommaLoc),t.innerComments&&xe(e,t.innerComments),t.callee.trailingComments&&xe(e,t.callee.trailingComments),e}parseNoCallExpr(){const e=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),e,!0)}parseExprAtom(e){let t,r=null;const{type:n}=this.state;switch(n){case 79:return this.parseSuper();case 83:return t=this.startNode(),this.next(),this.match(16)?this.parseImportMetaProperty(t):this.match(10)?256&this.optionFlags?this.parseImportCall(t):this.finishNode(t,"Import"):(this.raise(g.UnsupportedImport,this.state.lastTokStartLoc),this.finishNode(t,"Import"));case 78:return t=this.startNode(),this.next(),this.finishNode(t,"ThisExpression");case 90:return this.parseDo(this.startNode(),!1);case 56:case 31:return this.readRegexp(),this.parseRegExpLiteral(this.state.value);case 135:return this.parseNumericLiteral(this.state.value);case 136:return this.parseBigIntLiteral(this.state.value);case 134:return this.parseStringLiteral(this.state.value);case 84:return this.parseNullLiteral();case 85:return this.parseBooleanLiteral(!0);case 86:return this.parseBooleanLiteral(!1);case 10:{const e=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(e)}case 2:case 1:return this.parseArrayLike(2===this.state.type?4:3,!1,!0);case 0:return this.parseArrayLike(3,!0,!1,e);case 6:case 7:return this.parseObjectLike(6===this.state.type?9:8,!1,!0);case 5:return this.parseObjectLike(8,!1,!1,e);case 68:return this.parseFunctionOrFunctionSent();case 26:r=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(r,this.startNode()),!1);case 77:return this.parseNewOrNewTarget();case 25:case 24:return this.parseTemplate(!1);case 15:{t=this.startNode(),this.next(),t.object=null;const e=t.callee=this.parseNoCallExpr();if("MemberExpression"===e.type)return this.finishNode(t,"BindExpression");throw this.raise(g.UnsupportedBind,e)}case 139:return this.raise(g.PrivateInExpectedIn,this.state.startLoc,{identifierName:this.state.value}),this.parsePrivateName();case 33:return this.parseTopicReferenceThenEqualsSign(54,"%");case 32:return this.parseTopicReferenceThenEqualsSign(44,"^");case 37:case 38:return this.parseTopicReference("hack");case 44:case 54:case 27:{const e=this.getPluginOption("pipelineOperator","proposal");if(e)return this.parseTopicReference(e);this.unexpected();break}case 47:{const e=this.input.codePointAt(this.nextTokenStart());ie(e)||62===e?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected();break}default:if(137===n)return this.parseDecimalLiteral(this.state.value);if(q(n)){if(this.isContextual(127)&&123===this.lookaheadInLineCharCode())return this.parseModuleExpression();const e=this.state.potentialArrowAt===this.state.start,t=this.state.containsEsc,r=this.parseIdentifier();if(!t&&"async"===r.name&&!this.canInsertSemicolon()){const{type:e}=this.state;if(68===e)return this.resetPreviousNodeTrailingComments(r),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(r));if(q(e))return 61===this.lookaheadCharCode()?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(r)):r;if(90===e)return this.resetPreviousNodeTrailingComments(r),this.parseDo(this.startNodeAtNode(r),!0)}return e&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(r),[r],!1)):r}this.unexpected()}}parseTopicReferenceThenEqualsSign(e,t){const r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.state.type=e,this.state.value=t,this.state.pos--,this.state.end--,this.state.endLoc=i(this.state.endLoc,-1),this.parseTopicReference(r);this.unexpected()}parseTopicReference(e){const t=this.startNode(),r=this.state.startLoc,n=this.state.type;return this.next(),this.finishTopicReference(t,r,e,n)}finishTopicReference(e,t,r,n){if(this.testTopicReferenceConfiguration(r,t,n))return"hack"===r?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(g.PipeTopicUnbound,t),this.registerTopicReference(),this.finishNode(e,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(g.PrimaryTopicNotAllowed,t),this.registerTopicReference(),this.finishNode(e,"PipelinePrimaryTopicReference"));throw this.raise(g.PipeTopicUnconfiguredToken,t,{token:Y(n)})}testTopicReferenceConfiguration(e,t,r){switch(e){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Y(r)}]);case"smart":return 27===r;default:throw this.raise(g.PipeTopicRequiresHackPipes,t)}}parseAsyncArrowUnaryFunction(e){this.prodParam.enter(Xe(!0,this.prodParam.hasYield));const t=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(g.LineTerminatorBeforeArrow,this.state.curPosition()),this.expect(19),this.parseArrowExpression(e,t,!0)}parseDo(e,t){this.expectPlugin("doExpressions"),t&&this.expectPlugin("asyncDoExpressions"),e.async=t,this.next();const r=this.state.labels;return this.state.labels=[],t?(this.prodParam.enter(2),e.body=this.parseBlock(),this.prodParam.exit()):e.body=this.parseBlock(),this.state.labels=r,this.finishNode(e,"DoExpression")}parseSuper(){const e=this.startNode();return this.next(),!this.match(10)||this.scope.allowDirectSuper||16&this.optionFlags?this.scope.allowSuper||16&this.optionFlags||this.raise(g.UnexpectedSuper,e):this.raise(g.SuperNotAllowed,e),this.match(10)||this.match(0)||this.match(16)||this.raise(g.UnsupportedSuper,e),this.finishNode(e,"Super")}parsePrivateName(){const e=this.startNode(),t=this.startNodeAt(i(this.state.startLoc,1)),r=this.state.value;return this.next(),e.id=this.createIdentifier(t,r),this.finishNode(e,"PrivateName")}parseFunctionOrFunctionSent(){const e=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(16)){const t=this.createIdentifier(this.startNodeAtNode(e),"function");return this.next(),this.match(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(e,t,"sent")}return this.parseFunction(e)}parseMetaProperty(e,t,r){e.meta=t;const n=this.state.containsEsc;return e.property=this.parseIdentifier(!0),(e.property.name!==r||n)&&this.raise(g.UnsupportedMetaProperty,e.property,{target:t.name,onlyValidPropertyName:r}),this.finishNode(e,"MetaProperty")}parseImportMetaProperty(e){const t=this.createIdentifier(this.startNodeAtNode(e),"import");if(this.next(),this.isContextual(101))this.inModule||this.raise(g.ImportMetaOutsideModule,t),this.sawUnambiguousESM=!0;else if(this.isContextual(105)||this.isContextual(97)){const t=this.isContextual(105);if(this.expectPlugin(t?"sourcePhaseImports":"deferredImportEvaluation"),!(256&this.optionFlags))throw this.raise(g.DynamicImportPhaseRequiresImportExpressions,this.state.startLoc,{phase:this.state.value});return this.next(),e.phase=t?"source":"defer",this.parseImportCall(e)}return this.parseMetaProperty(e,t,"meta")}parseLiteralAtNode(e,t,r){return this.addExtra(r,"rawValue",e),this.addExtra(r,"raw",this.input.slice(this.offsetToSourcePos(r.start),this.state.end)),r.value=e,this.next(),this.finishNode(r,t)}parseLiteral(e,t){const r=this.startNode();return this.parseLiteralAtNode(e,t,r)}parseStringLiteral(e){return this.parseLiteral(e,"StringLiteral")}parseNumericLiteral(e){return this.parseLiteral(e,"NumericLiteral")}parseBigIntLiteral(e){return this.parseLiteral(e,"BigIntLiteral")}parseDecimalLiteral(e){return this.parseLiteral(e,"DecimalLiteral")}parseRegExpLiteral(e){const t=this.startNode();return this.addExtra(t,"raw",this.input.slice(this.offsetToSourcePos(t.start),this.state.end)),t.pattern=e.pattern,t.flags=e.flags,this.next(),this.finishNode(t,"RegExpLiteral")}parseBooleanLiteral(e){const t=this.startNode();return t.value=e,this.next(),this.finishNode(t,"BooleanLiteral")}parseNullLiteral(){const e=this.startNode();return this.next(),this.finishNode(e,"NullLiteral")}parseParenAndDistinguishExpression(e){const t=this.state.startLoc;let r;this.next(),this.expressionScope.enter(new He(1));const n=this.state.maybeInArrowParameters,s=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;const i=this.state.startLoc,a=[],o=new Ze;let l,c,p=!0;for(;!this.match(11);){if(p)p=!1;else if(this.expect(12,null===o.optionalParametersLoc?null:o.optionalParametersLoc),this.match(11)){c=this.state.startLoc;break}if(this.match(21)){const e=this.state.startLoc;if(l=this.state.startLoc,a.push(this.parseParenItem(this.parseRestBinding(),e)),!this.checkCommaAfterRest(41))break}else a.push(this.parseMaybeAssignAllowIn(o,this.parseParenItem))}const u=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=n,this.state.inFSharpPipelineDirectBody=s;let d=this.startNodeAt(t);return e&&this.shouldParseArrow(a)&&(d=this.parseArrow(d))?(this.checkDestructuringPrivate(o),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(d,a,!1),d):(this.expressionScope.exit(),a.length||this.unexpected(this.state.lastTokStartLoc),c&&this.unexpected(c),l&&this.unexpected(l),this.checkExpressionErrors(o,!0),this.toReferencedListDeep(a,!0),a.length>1?(r=this.startNodeAt(i),r.expressions=a,this.finishNode(r,"SequenceExpression"),this.resetEndLocation(r,u)):r=a[0],this.wrapParenthesis(t,r))}wrapParenthesis(e,t){if(!(512&this.optionFlags))return this.addExtra(t,"parenthesized",!0),this.addExtra(t,"parenStart",e.index),this.takeSurroundingComments(t,e.index,this.state.lastTokEndLoc.index),t;const r=this.startNodeAt(e);return r.expression=t,this.finishNode(r,"ParenthesizedExpression")}shouldParseArrow(e){return!this.canInsertSemicolon()}parseArrow(e){if(this.eat(19))return e}parseParenItem(e,t){return e}parseNewOrNewTarget(){const e=this.startNode();if(this.next(),this.match(16)){const t=this.createIdentifier(this.startNodeAtNode(e),"new");this.next();const r=this.parseMetaProperty(e,t,"target");return this.scope.inNonArrowFunction||this.scope.inClass||4&this.optionFlags||this.raise(g.UnexpectedNewTarget,r),r}return this.parseNew(e)}parseNew(e){if(this.parseNewCallee(e),this.eat(10)){const t=this.parseExprList(11);this.toReferencedList(t),e.arguments=t}else e.arguments=[];return this.finishNode(e,"NewExpression")}parseNewCallee(e){const t=this.match(83),r=this.parseNoCallExpr();e.callee=r,!t||"Import"!==r.type&&"ImportExpression"!==r.type||this.raise(g.ImportCallNotNewExpression,r)}parseTemplateElement(e){const{start:t,startLoc:r,end:n,value:s}=this.state,a=t+1,o=this.startNodeAt(i(r,1));null===s&&(e||this.raise(g.InvalidEscapeSequenceTemplate,i(this.state.firstInvalidTemplateEscapePos,1)));const l=this.match(24),c=l?-1:-2,p=n+c;o.value={raw:this.input.slice(a,p).replace(/\r\n?/g,"\n"),cooked:null===s?null:s.slice(1,c)},o.tail=l,this.next();const u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,i(this.state.lastTokEndLoc,c)),u}parseTemplate(e){const t=this.startNode();let r=this.parseTemplateElement(e);const n=[r],s=[];for(;!r.tail;)s.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),n.push(r=this.parseTemplateElement(e));return t.expressions=s,t.quasis=n,this.finishNode(t,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(e,t,r,n){r&&this.expectPlugin("recordAndTuple");const s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;const i=Object.create(null);let a=!0;const o=this.startNode();for(o.properties=[],this.next();!this.match(e);){if(a)a=!1;else if(this.expect(12),this.match(e)){this.addTrailingCommaExtraToNode(o);break}let s;t?s=this.parseBindingProperty():(s=this.parsePropertyDefinition(n),this.checkProto(s,r,i,n)),r&&!this.isObjectProperty(s)&&"SpreadElement"!==s.type&&this.raise(g.InvalidRecordProperty,s),s.shorthand&&this.addExtra(s,"shorthand",!0),o.properties.push(s)}this.next(),this.state.inFSharpPipelineDirectBody=s;let l="ObjectExpression";return t?l="ObjectPattern":r&&(l="RecordExpression"),this.finishNode(o,l)}addTrailingCommaExtraToNode(e){this.addExtra(e,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(e,"trailingCommaLoc",this.state.lastTokStartLoc,!1)}maybeAsyncOrAccessorProp(e){return!e.computed&&"Identifier"===e.key.type&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))}parsePropertyDefinition(e){let t=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(g.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)t.push(this.parseDecorator());const r=this.startNode();let n,s=!1,i=!1;if(this.match(21))return t.length&&this.unexpected(),this.parseSpread();t.length&&(r.decorators=t,t=[]),r.method=!1,e&&(n=this.state.startLoc);let a=this.eat(55);this.parsePropertyNamePrefixOperator(r);const o=this.state.containsEsc;if(this.parsePropertyName(r,e),!a&&!o&&this.maybeAsyncOrAccessorProp(r)){const{key:e}=r,t=e.name;"async"!==t||this.hasPrecedingLineBreak()||(s=!0,this.resetPreviousNodeTrailingComments(e),a=this.eat(55),this.parsePropertyName(r)),"get"!==t&&"set"!==t||(i=!0,this.resetPreviousNodeTrailingComments(e),r.kind=t,this.match(55)&&(a=!0,this.raise(g.AccessorIsGenerator,this.state.curPosition(),{kind:t}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,n,a,s,!1,i,e)}getGetterSetterExpectedParamCount(e){return"get"===e.kind?0:1}getObjectOrClassMethodParams(e){return e.params}checkGetterSetterParams(e){var t;const r=this.getGetterSetterExpectedParamCount(e),n=this.getObjectOrClassMethodParams(e);n.length!==r&&this.raise("get"===e.kind?g.BadGetterArity:g.BadSetterArity,e),"set"===e.kind&&"RestElement"===(null==(t=n[n.length-1])?void 0:t.type)&&this.raise(g.BadSetterRestParameter,e)}parseObjectMethod(e,t,r,n,s){if(s){const r=this.parseMethod(e,t,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(r),r}if(r||t||this.match(10))return n&&this.unexpected(),e.kind="method",e.method=!0,this.parseMethod(e,t,r,!1,!1,"ObjectMethod")}parseObjectProperty(e,t,r,n){if(e.shorthand=!1,this.eat(14))return e.value=r?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowIn(n),this.finishNode(e,"ObjectProperty");if(!e.computed&&"Identifier"===e.key.type){if(this.checkReservedWord(e.key.name,e.key.loc.start,!0,!1),r)e.value=this.parseMaybeDefault(t,rt(e.key));else if(this.match(29)){const r=this.state.startLoc;null!=n?null===n.shorthandAssignLoc&&(n.shorthandAssignLoc=r):this.raise(g.InvalidCoverInitializedName,r),e.value=this.parseMaybeDefault(t,rt(e.key))}else e.value=rt(e.key);return e.shorthand=!0,this.finishNode(e,"ObjectProperty")}}parseObjPropValue(e,t,r,n,s,i,a){const o=this.parseObjectMethod(e,r,n,s,i)||this.parseObjectProperty(e,t,s,a);return o||this.unexpected(),o}parsePropertyName(e,t){if(this.eat(0))e.computed=!0,e.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{const{type:r,value:n}=this.state;let s;if(W(r))s=this.parseIdentifier(!0);else switch(r){case 135:s=this.parseNumericLiteral(n);break;case 134:s=this.parseStringLiteral(n);break;case 136:s=this.parseBigIntLiteral(n);break;case 139:{const e=this.state.startLoc;null!=t?null===t.privateKeyLoc&&(t.privateKeyLoc=e):this.raise(g.UnexpectedPrivateField,e),s=this.parsePrivateName();break}default:if(137===r){s=this.parseDecimalLiteral(n);break}this.unexpected()}e.key=s,139!==r&&(e.computed=!1)}}initFunction(e,t){e.id=null,e.generator=!1,e.async=t}parseMethod(e,t,r,n,s,i,a=!1){this.initFunction(e,r),e.generator=t,this.scope.enter(18|(a?64:0)|(s?32:0)),this.prodParam.enter(Xe(r,e.generator)),this.parseFunctionParams(e,n);const o=this.parseFunctionBodyAndFinish(e,i,!0);return this.prodParam.exit(),this.scope.exit(),o}parseArrayLike(e,t,r,n){r&&this.expectPlugin("recordAndTuple");const s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;const i=this.startNode();return this.next(),i.elements=this.parseExprList(e,!r,n,i),this.state.inFSharpPipelineDirectBody=s,this.finishNode(i,r?"TupleExpression":"ArrayExpression")}parseArrowExpression(e,t,r,n){this.scope.enter(6);let s=Xe(r,!1);!this.match(5)&&this.prodParam.hasIn&&(s|=8),this.prodParam.enter(s),this.initFunction(e,r);const i=this.state.maybeInArrowParameters;return t&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(e,t,n)),this.state.maybeInArrowParameters=!1,this.parseFunctionBody(e,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=i,this.finishNode(e,"ArrowFunctionExpression")}setArrowFunctionParameters(e,t,r){this.toAssignableList(t,r,!1),e.params=t}parseFunctionBodyAndFinish(e,t,r=!1){return this.parseFunctionBody(e,!1,r),this.finishNode(e,t)}parseFunctionBody(e,t,r=!1){const n=t&&!this.match(5);if(this.expressionScope.enter(Je()),n)e.body=this.parseMaybeAssign(),this.checkParams(e,!1,t,!1);else{const n=this.state.strict,s=this.state.labels;this.state.labels=[],this.prodParam.enter(4|this.prodParam.currentFlags()),e.body=this.parseBlock(!0,!1,(s=>{const i=!this.isSimpleParamList(e.params);s&&i&&this.raise(g.IllegalLanguageModeDirective,"method"!==e.kind&&"constructor"!==e.kind||!e.key?e:e.key.loc.end);const a=!n&&this.state.strict;this.checkParams(e,!(this.state.strict||t||r||i),t,a),this.state.strict&&e.id&&this.checkIdentifier(e.id,65,a)})),this.prodParam.exit(),this.state.labels=s}this.expressionScope.exit()}isSimpleParameter(e){return"Identifier"===e.type}isSimpleParamList(e){for(let t=0,r=e.length;t<r;t++)if(!this.isSimpleParameter(e[t]))return!1;return!0}checkParams(e,t,r,n=!0){const s=!t&&new Set,i={type:"FormalParameters"};for(const t of e.params)this.checkLVal(t,i,5,s,n)}parseExprList(e,t,r,n){const s=[];let i=!0;for(;!this.eat(e);){if(i)i=!1;else if(this.expect(12),this.match(e)){n&&this.addTrailingCommaExtraToNode(n),this.next();break}s.push(this.parseExprListItem(t,r))}return s}parseExprListItem(e,t,r){let n;if(this.match(12))e||this.raise(g.UnexpectedToken,this.state.curPosition(),{unexpected:","}),n=null;else if(this.match(21)){const e=this.state.startLoc;n=this.parseParenItem(this.parseSpread(t),e)}else if(this.match(17)){this.expectPlugin("partialApplication"),r||this.raise(g.UnexpectedArgumentPlaceholder,this.state.startLoc);const e=this.startNode();this.next(),n=this.finishNode(e,"ArgumentPlaceholder")}else n=this.parseMaybeAssignAllowIn(t,this.parseParenItem);return n}parseIdentifier(e){const t=this.startNode(),r=this.parseIdentifierName(e);return this.createIdentifier(t,r)}createIdentifier(e,t){return e.name=t,e.loc.identifierName=t,this.finishNode(e,"Identifier")}parseIdentifierName(e){let t;const{startLoc:r,type:n}=this.state;W(n)?t=this.state.value:this.unexpected();const s=n<=92;return e?s&&this.replaceToken(132):this.checkReservedWord(t,r,s,!1),this.next(),t}checkReservedWord(e,t,r,n){if(!(e.length>10)&&function(e){return he.has(e)}(e))if(r&&function(e){return oe.has(e)}(e))this.raise(g.UnexpectedKeyword,t,{keyword:e});else if((this.state.strict?n?fe:ue:pe)(e,this.inModule))this.raise(g.UnexpectedReservedWord,t,{reservedWord:e});else if("yield"===e){if(this.prodParam.hasYield)return void this.raise(g.YieldBindingIdentifier,t)}else if("await"===e){if(this.prodParam.hasAwait)return void this.raise(g.AwaitBindingIdentifier,t);if(this.scope.inStaticBlock)return void this.raise(g.AwaitBindingIdentifierInStaticBlock,t);this.expressionScope.recordAsyncArrowParametersError(t)}else if("arguments"===e&&this.scope.inClassAndNotInNonArrowFunction)return void this.raise(g.ArgumentsInClass,t)}recordAwaitIfAllowed(){const e=this.prodParam.hasAwait||1&this.optionFlags&&!this.scope.inFunction;return e&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),e}parseAwait(e){const t=this.startNodeAt(e);return this.expressionScope.recordParameterInitializerError(g.AwaitExpressionFormalParameter,t),this.eat(55)&&this.raise(g.ObsoleteAwaitStar,t),this.scope.inFunction||1&this.optionFlags||(this.isAmbiguousAwait()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(t.argument=this.parseMaybeUnary(null,!0)),this.finishNode(t,"AwaitExpression")}isAmbiguousAwait(){if(this.hasPrecedingLineBreak())return!0;const{type:e}=this.state;return 53===e||10===e||0===e||z(e)||102===e&&!this.state.containsEsc||138===e||56===e||this.hasPlugin("v8intrinsic")&&54===e}parseYield(){const e=this.startNode();this.expressionScope.recordParameterInitializerError(g.YieldInParameter,e),this.next();let t=!1,r=null;if(!this.hasPrecedingLineBreak())switch(t=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!t)break;default:r=this.parseMaybeAssign()}return e.delegate=t,e.argument=r,this.finishNode(e,"YieldExpression")}parseImportCall(e){if(this.next(),e.source=this.parseMaybeAssignAllowIn(),e.options=null,this.eat(12)&&!this.match(11)&&(e.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&!this.match(11))){do{this.parseMaybeAssignAllowIn()}while(this.eat(12)&&!this.match(11));this.raise(g.ImportCallArity,e)}return this.expect(11),this.finishNode(e,"ImportExpression")}checkPipelineAtInfixOperator(e,t){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&"SequenceExpression"===e.type&&this.raise(g.PipelineHeadSequenceExpression,t)}parseSmartPipelineBodyInStyle(e,t){if(this.isSimpleReference(e)){const r=this.startNodeAt(t);return r.callee=e,this.finishNode(r,"PipelineBareFunction")}{const r=this.startNodeAt(t);return this.checkSmartPipeTopicBodyEarlyErrors(t),r.expression=e,this.finishNode(r,"PipelineTopicExpression")}}isSimpleReference(e){switch(e.type){case"MemberExpression":return!e.computed&&this.isSimpleReference(e.object);case"Identifier":return!0;default:return!1}}checkSmartPipeTopicBodyEarlyErrors(e){if(this.match(19))throw this.raise(g.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(g.PipelineTopicUnused,e)}withTopicBindingContext(e){const t=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return e()}finally{this.state.topicContext=t}}withSmartMixTopicForbiddingContext(e){if(!this.hasPlugin(["pipelineOperator",{proposal:"smart"}]))return e();{const t=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return e()}finally{this.state.topicContext=t}}}withSoloAwaitPermittingContext(e){const t=this.state.soloAwait;this.state.soloAwait=!0;try{return e()}finally{this.state.soloAwait=t}}allowInAnd(e){const t=this.prodParam.currentFlags();if(8&~t){this.prodParam.enter(8|t);try{return e()}finally{this.prodParam.exit()}}return e()}disallowInAnd(e){const t=this.prodParam.currentFlags();if(8&t){this.prodParam.enter(-9&t);try{return e()}finally{this.prodParam.exit()}}return e()}registerTopicReference(){this.state.topicContext.maxTopicIndex=0}topicReferenceIsAllowedInCurrentContext(){return this.state.topicContext.maxNumOfResolvableTopics>=1}topicReferenceWasUsedInCurrentContext(){return null!=this.state.topicContext.maxTopicIndex&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(e){const t=this.state.startLoc;this.state.potentialArrowAt=this.state.start;const r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;const n=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),t,e);return this.state.inFSharpPipelineDirectBody=r,n}parseModuleExpression(){this.expectPlugin("moduleBlocks");const e=this.startNode();this.next(),this.match(5)||this.unexpected(null,5);const t=this.startNodeAt(this.state.endLoc);this.next();const r=this.initializeScopes(!0);this.enterInitialScopes();try{e.body=this.parseProgram(t,8,"module")}finally{r()}return this.finishNode(e,"ModuleExpression")}parsePropertyNamePrefixOperator(e){}}const kt={kind:1},_t={kind:2},Dt=/[\uD800-\uDFFF]/u,jt=/in(?:stanceof)?/y;class Bt extends Nt{parseTopLevel(e,t){return e.program=this.parseProgram(t),e.comments=this.comments,128&this.optionFlags&&(e.tokens=function(e,t,r){for(let n=0;n<e.length;n++){const s=e[n],{type:a}=s;if("number"==typeof a){if(139===a){const{loc:t,start:r,value:a,end:o}=s,l=r+1,c=i(t.start,1);e.splice(n,1,new qe({type:X(27),value:"#",start:r,end:l,startLoc:t.start,endLoc:c}),new qe({type:X(132),value:a,start:l,end:o,startLoc:c,endLoc:t.end})),n++;continue}if(z(a)){const{loc:o,start:l,value:c,end:p}=s,u=l+1,d=i(o.start,1);let f,h,m,y,g;f=96===t.charCodeAt(l-r)?new qe({type:X(22),value:"`",start:l,end:u,startLoc:o.start,endLoc:d}):new qe({type:X(8),value:"}",start:l,end:u,startLoc:o.start,endLoc:d}),24===a?(m=p-1,y=i(o.end,-1),h=null===c?null:c.slice(1,-1),g=new qe({type:X(22),value:"`",start:m,end:p,startLoc:y,endLoc:o.end})):(m=p-2,y=i(o.end,-2),h=null===c?null:c.slice(1,-2),g=new qe({type:X(23),value:"${",start:m,end:p,startLoc:y,endLoc:o.end})),e.splice(n,1,f,new qe({type:X(20),value:h,start:u,end:m,startLoc:d,endLoc:y}),g),n+=2;continue}s.type=X(a)}}return e}(this.tokens,this.input,this.startIndex)),this.finishNode(e,"File")}parseProgram(e,t=140,r=this.options.sourceType){if(e.sourceType=r,e.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(e,!0,!0,t),this.inModule){if(!(32&this.optionFlags)&&this.scope.undefinedExports.size>0)for(const[e,t]of Array.from(this.scope.undefinedExports))this.raise(g.ModuleExportUndefined,t,{localName:e});this.addExtra(e,"topLevelAwait",this.state.hasTopLevelAwait)}let n;return n=140===t?this.finishNode(e,"Program"):this.finishNodeAt(e,"Program",i(this.state.startLoc,-1)),n}stmtToDirective(e){const t=e;t.type="Directive",t.value=t.expression,delete t.expression;const r=t.value,n=r.value,s=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),i=r.value=s.slice(1,-1);return this.addExtra(r,"raw",s),this.addExtra(r,"rawValue",i),this.addExtra(r,"expressionValue",n),r.type="DirectiveLiteral",t}parseInterpreterDirective(){if(!this.match(28))return null;const e=this.startNode();return e.value=this.state.value,this.next(),this.finishNode(e,"InterpreterDirective")}isLet(){return!!this.isContextual(100)&&this.hasFollowingBindingAtom()}chStartsBindingIdentifier(e,t){if(ie(e)){if(jt.lastIndex=t,jt.test(this.input)){const e=this.codePointAtPos(jt.lastIndex);if(!ae(e)&&92!==e)return!1}return!0}return 92===e}chStartsBindingPattern(e){return 91===e||123===e}hasFollowingBindingAtom(){const e=this.nextTokenStart(),t=this.codePointAtPos(e);return this.chStartsBindingPattern(t)||this.chStartsBindingIdentifier(t,e)}hasInLineFollowingBindingIdentifierOrBrace(){const e=this.nextTokenInLineStart(),t=this.codePointAtPos(e);return 123===t||this.chStartsBindingIdentifier(t,e)}startsUsingForOf(){const{type:e,containsEsc:t}=this.lookahead();return!(102===e&&!t)&&(q(e)&&!this.hasFollowingLineBreak()?(this.expectPlugin("explicitResourceManagement"),!0):void 0)}startsAwaitUsing(){let e=this.nextTokenInLineStart();if(this.isUnparsedContextual(e,"using")){e=this.nextTokenInLineStartSince(e+5);const t=this.codePointAtPos(e);if(this.chStartsBindingIdentifier(t,e))return this.expectPlugin("explicitResourceManagement"),!0}return!1}parseModuleItem(){return this.parseStatementLike(15)}parseStatementListItem(){return this.parseStatementLike(6|(!this.options.annexB||this.state.strict?0:8))}parseStatementOrSloppyAnnexBFunctionDeclaration(e=!1){let t=0;return this.options.annexB&&!this.state.strict&&(t|=4,e&&(t|=8)),this.parseStatementLike(t)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(e){let t=null;return this.match(26)&&(t=this.parseDecorators(!0)),this.parseStatementContent(e,t)}parseStatementContent(e,t){const r=this.state.type,n=this.startNode(),s=!!(2&e),i=!!(4&e),a=1&e;switch(r){case 60:return this.parseBreakContinueStatement(n,!0);case 63:return this.parseBreakContinueStatement(n,!1);case 64:return this.parseDebuggerStatement(n);case 90:return this.parseDoWhileStatement(n);case 91:return this.parseForStatement(n);case 68:if(46===this.lookaheadCharCode())break;return i||this.raise(this.state.strict?g.StrictFunction:this.options.annexB?g.SloppyFunctionAnnexB:g.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(n,!1,!s&&i);case 80:return s||this.unexpected(),this.parseClass(this.maybeTakeDecorators(t,n),!0);case 69:return this.parseIfStatement(n);case 70:return this.parseReturnStatement(n);case 71:return this.parseSwitchStatement(n);case 72:return this.parseThrowStatement(n);case 73:return this.parseTryStatement(n);case 96:if(!this.state.containsEsc&&this.startsAwaitUsing())return this.recordAwaitIfAllowed()?s||this.raise(g.UnexpectedLexicalDeclaration,n):this.raise(g.AwaitUsingNotInAsyncContext,n),this.next(),this.parseVarStatement(n,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.expectPlugin("explicitResourceManagement"),!this.scope.inModule&&this.scope.inTopLevel?this.raise(g.UnexpectedUsingDeclaration,this.state.startLoc):s||this.raise(g.UnexpectedLexicalDeclaration,this.state.startLoc),this.parseVarStatement(n,"using");case 100:{if(this.state.containsEsc)break;const e=this.nextTokenStart(),t=this.codePointAtPos(e);if(91!==t){if(!s&&this.hasFollowingLineBreak())break;if(!this.chStartsBindingIdentifier(t,e)&&123!==t)break}}case 75:s||this.raise(g.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{const e=this.state.value;return this.parseVarStatement(n,e)}case 92:return this.parseWhileStatement(n);case 76:return this.parseWithStatement(n);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(n);case 83:{const e=this.lookaheadCharCode();if(40===e||46===e)break}case 82:{let e;return 8&this.optionFlags||a||this.raise(g.UnexpectedImportExport,this.state.startLoc),this.next(),83===r?(e=this.parseImport(n),"ImportDeclaration"!==e.type||e.importKind&&"value"!==e.importKind||(this.sawUnambiguousESM=!0)):(e=this.parseExport(n,t),("ExportNamedDeclaration"!==e.type||e.exportKind&&"value"!==e.exportKind)&&("ExportAllDeclaration"!==e.type||e.exportKind&&"value"!==e.exportKind)&&"ExportDefaultDeclaration"!==e.type||(this.sawUnambiguousESM=!0)),this.assertModuleNodeAllowed(e),e}default:if(this.isAsyncFunction())return s||this.raise(g.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(n,!0,!s&&i)}const o=this.state.value,l=this.parseExpression();return q(r)&&"Identifier"===l.type&&this.eat(14)?this.parseLabeledStatement(n,o,l,e):this.parseExpressionStatement(n,l,t)}assertModuleNodeAllowed(e){8&this.optionFlags||this.inModule||this.raise(g.ImportOutsideModule,e)}decoratorsEnabledBeforeExport(){return!!this.hasPlugin("decorators-legacy")||this.hasPlugin("decorators")&&!1!==this.getPluginOption("decorators","decoratorsBeforeExport")}maybeTakeDecorators(e,t,r){var n;return e&&(null!=(n=t.decorators)&&n.length?("boolean"!=typeof this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(g.DecoratorsBeforeAfterExport,t.decorators[0]),t.decorators.unshift(...e)):t.decorators=e,this.resetStartLocationFromNode(t,e[0]),r&&this.resetStartLocationFromNode(r,t)),t}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(e){const t=[];do{t.push(this.parseDecorator())}while(this.match(26));if(this.match(82))e||this.unexpected(),this.decoratorsEnabledBeforeExport()||this.raise(g.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(g.UnexpectedLeadingDecorator,this.state.startLoc);return t}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);const e=this.startNode();if(this.next(),this.hasPlugin("decorators")){const t=this.state.startLoc;let r;if(this.match(10)){const t=this.state.startLoc;this.next(),r=this.parseExpression(),this.expect(11),r=this.wrapParenthesis(t,r);const n=this.state.startLoc;e.expression=this.parseMaybeDecoratorArguments(r,t),!1===this.getPluginOption("decorators","allowCallParenthesized")&&e.expression!==r&&this.raise(g.DecoratorArgumentsOutsideParentheses,n)}else{for(r=this.parseIdentifier(!1);this.eat(16);){const e=this.startNodeAt(t);e.object=r,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),e.property=this.parsePrivateName()):e.property=this.parseIdentifier(!0),e.computed=!1,r=this.finishNode(e,"MemberExpression")}e.expression=this.parseMaybeDecoratorArguments(r,t)}}else e.expression=this.parseExprSubscripts();return this.finishNode(e,"Decorator")}parseMaybeDecoratorArguments(e,t){if(this.eat(10)){const r=this.startNodeAt(t);return r.callee=e,r.arguments=this.parseCallExpressionArguments(11),this.toReferencedList(r.arguments),this.finishNode(r,"CallExpression")}return e}parseBreakContinueStatement(e,t){return this.next(),this.isLineTerminator()?e.label=null:(e.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(e,t),this.finishNode(e,t?"BreakStatement":"ContinueStatement")}verifyBreakContinue(e,t){let r;for(r=0;r<this.state.labels.length;++r){const n=this.state.labels[r];if(null==e.label||n.name===e.label.name){if(null!=n.kind&&(t||1===n.kind))break;if(e.label&&t)break}}if(r===this.state.labels.length){const r=t?"BreakStatement":"ContinueStatement";this.raise(g.IllegalBreakContinue,e,{type:r})}}parseDebuggerStatement(e){return this.next(),this.semicolon(),this.finishNode(e,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);const e=this.parseExpression();return this.expect(11),e}parseDoWhileStatement(e){return this.next(),this.state.labels.push(kt),e.body=this.withSmartMixTopicForbiddingContext((()=>this.parseStatement())),this.state.labels.pop(),this.expect(92),e.test=this.parseHeaderExpression(),this.eat(13),this.finishNode(e,"DoWhileStatement")}parseForStatement(e){this.next(),this.state.labels.push(kt);let t=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(t=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return null!==t&&this.unexpected(t),this.parseFor(e,null);const r=this.isContextual(100);{const n=this.isContextual(96)&&this.startsAwaitUsing(),s=n||this.isContextual(107)&&this.startsUsingForOf(),i=r&&this.hasFollowingBindingAtom()||s;if(this.match(74)||this.match(75)||i){const r=this.startNode();let i;n?(i="await using",this.recordAwaitIfAllowed()||this.raise(g.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):i=this.state.value,this.next(),this.parseVar(r,!0,i);const a=this.finishNode(r,"VariableDeclaration"),o=this.match(58);return o&&s&&this.raise(g.ForInUsing,a),(o||this.isContextual(102))&&1===a.declarations.length?this.parseForIn(e,a,t):(null!==t&&this.unexpected(t),this.parseFor(e,a))}}const n=this.isContextual(95),s=new Ze,i=this.parseExpression(!0,s),a=this.isContextual(102);if(a&&(r&&this.raise(g.ForOfLet,i),null===t&&n&&"Identifier"===i.type&&this.raise(g.ForOfAsync,i)),a||this.match(58)){this.checkDestructuringPrivate(s),this.toAssignable(i,!0);const r=a?"ForOfStatement":"ForInStatement";return this.checkLVal(i,{type:r}),this.parseForIn(e,i,t)}return this.checkExpressionErrors(s,!0),null!==t&&this.unexpected(t),this.parseFor(e,i)}parseFunctionStatement(e,t,r){return this.next(),this.parseFunction(e,1|(r?2:0)|(t?8:0))}parseIfStatement(e){return this.next(),e.test=this.parseHeaderExpression(),e.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration(),e.alternate=this.eat(66)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null,this.finishNode(e,"IfStatement")}parseReturnStatement(e){return this.prodParam.hasReturn||2&this.optionFlags||this.raise(g.IllegalReturn,this.state.startLoc),this.next(),this.isLineTerminator()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")}parseSwitchStatement(e){this.next(),e.discriminant=this.parseHeaderExpression();const t=e.cases=[];let r;this.expect(5),this.state.labels.push(_t),this.scope.enter(0);for(let e;!this.match(8);)if(this.match(61)||this.match(65)){const n=this.match(61);r&&this.finishNode(r,"SwitchCase"),t.push(r=this.startNode()),r.consequent=[],this.next(),n?r.test=this.parseExpression():(e&&this.raise(g.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),e=!0,r.test=null),this.expect(14)}else r?r.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),r&&this.finishNode(r,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(e,"SwitchStatement")}parseThrowStatement(e){return this.next(),this.hasPrecedingLineBreak()&&this.raise(g.NewlineAfterThrow,this.state.lastTokEndLoc),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")}parseCatchClauseParam(){const e=this.parseBindingAtom();return this.scope.enter(this.options.annexB&&"Identifier"===e.type?8:0),this.checkLVal(e,{type:"CatchClause"},9),e}parseTryStatement(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.match(62)){const t=this.startNode();this.next(),this.match(10)?(this.expect(10),t.param=this.parseCatchClauseParam(),this.expect(11)):(t.param=null,this.scope.enter(0)),t.body=this.withSmartMixTopicForbiddingContext((()=>this.parseBlock(!1,!1))),this.scope.exit(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(67)?this.parseBlock():null,e.handler||e.finalizer||this.raise(g.NoCatchOrFinally,e),this.finishNode(e,"TryStatement")}parseVarStatement(e,t,r=!1){return this.next(),this.parseVar(e,!1,t,r),this.semicolon(),this.finishNode(e,"VariableDeclaration")}parseWhileStatement(e){return this.next(),e.test=this.parseHeaderExpression(),this.state.labels.push(kt),e.body=this.withSmartMixTopicForbiddingContext((()=>this.parseStatement())),this.state.labels.pop(),this.finishNode(e,"WhileStatement")}parseWithStatement(e){return this.state.strict&&this.raise(g.StrictWith,this.state.startLoc),this.next(),e.object=this.parseHeaderExpression(),e.body=this.withSmartMixTopicForbiddingContext((()=>this.parseStatement())),this.finishNode(e,"WithStatement")}parseEmptyStatement(e){return this.next(),this.finishNode(e,"EmptyStatement")}parseLabeledStatement(e,t,r,n){for(const e of this.state.labels)e.name===t&&this.raise(g.LabelRedeclaration,r,{labelName:t});const s=(i=this.state.type)>=90&&i<=92?1:this.match(71)?2:null;var i;for(let t=this.state.labels.length-1;t>=0;t--){const r=this.state.labels[t];if(r.statementStart!==e.start)break;r.statementStart=this.sourceToOffsetPos(this.state.start),r.kind=s}return this.state.labels.push({name:t,kind:s,statementStart:this.sourceToOffsetPos(this.state.start)}),e.body=8&n?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")}parseExpressionStatement(e,t,r){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")}parseBlock(e=!1,t=!0,r){const n=this.startNode();return e&&this.state.strictErrors.clear(),this.expect(5),t&&this.scope.enter(0),this.parseBlockBody(n,e,!1,8,r),t&&this.scope.exit(),this.finishNode(n,"BlockStatement")}isValidDirective(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized}parseBlockBody(e,t,r,n,s){const i=e.body=[],a=e.directives=[];this.parseBlockOrModuleBlockBody(i,t?a:void 0,r,n,s)}parseBlockOrModuleBlockBody(e,t,r,n,s){const i=this.state.strict;let a=!1,o=!1;for(;!this.match(n);){const n=r?this.parseModuleItem():this.parseStatementListItem();if(t&&!o){if(this.isValidDirective(n)){const e=this.stmtToDirective(n);t.push(e),a||"use strict"!==e.value.value||(a=!0,this.setStrict(!0));continue}o=!0,this.state.strictErrors.clear()}e.push(n)}null==s||s.call(this,a),i||this.setStrict(!1),this.next()}parseFor(e,t){return e.init=t,this.semicolon(!1),e.test=this.match(13)?null:this.parseExpression(),this.semicolon(!1),e.update=this.match(11)?null:this.parseExpression(),this.expect(11),e.body=this.withSmartMixTopicForbiddingContext((()=>this.parseStatement())),this.scope.exit(),this.state.labels.pop(),this.finishNode(e,"ForStatement")}parseForIn(e,t,r){const n=this.match(58);return this.next(),n?null!==r&&this.unexpected(r):e.await=null!==r,"VariableDeclaration"!==t.type||null==t.declarations[0].init||n&&this.options.annexB&&!this.state.strict&&"var"===t.kind&&"Identifier"===t.declarations[0].id.type||this.raise(g.ForInOfLoopInitializer,t,{type:n?"ForInStatement":"ForOfStatement"}),"AssignmentPattern"===t.type&&this.raise(g.InvalidLhs,t,{ancestor:{type:"ForStatement"}}),e.left=t,e.right=n?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),e.body=this.withSmartMixTopicForbiddingContext((()=>this.parseStatement())),this.scope.exit(),this.state.labels.pop(),this.finishNode(e,n?"ForInStatement":"ForOfStatement")}parseVar(e,t,r,n=!1){const s=e.declarations=[];for(e.kind=r;;){const e=this.startNode();if(this.parseVarId(e,r),e.init=this.eat(29)?t?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,null!==e.init||n||("Identifier"===e.id.type||t&&(this.match(58)||this.isContextual(102))?"const"!==r&&"using"!==r&&"await using"!==r||this.match(58)||this.isContextual(102)||this.raise(g.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r}):this.raise(g.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"})),s.push(this.finishNode(e,"VariableDeclarator")),!this.eat(12))break}return e}parseVarId(e,t){const r=this.parseBindingAtom();"using"!==t&&"await using"!==t||"ArrayPattern"!==r.type&&"ObjectPattern"!==r.type||this.raise(g.UsingDeclarationHasBindingPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},"var"===t?5:8201),e.id=r}parseAsyncFunctionExpression(e){return this.parseFunction(e,8)}parseFunction(e,t=0){const r=2&t,n=!!(1&t),s=n&&!(4&t),i=!!(8&t);this.initFunction(e,i),this.match(55)&&(r&&this.raise(g.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),e.generator=!0),n&&(e.id=this.parseFunctionId(s));const a=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(2),this.prodParam.enter(Xe(i,e.generator)),n||(e.id=this.parseFunctionId()),this.parseFunctionParams(e,!1),this.withSmartMixTopicForbiddingContext((()=>{this.parseFunctionBodyAndFinish(e,n?"FunctionDeclaration":"FunctionExpression")})),this.prodParam.exit(),this.scope.exit(),n&&!r&&this.registerFunctionStatementId(e),this.state.maybeInArrowParameters=a,e}parseFunctionId(e){return e||q(this.state.type)?this.parseIdentifier():null}parseFunctionParams(e,t){this.expect(10),this.expressionScope.enter(new Ge(3)),e.params=this.parseBindingList(11,41,2|(t?4:0)),this.expressionScope.exit()}registerFunctionStatementId(e){e.id&&this.scope.declareName(e.id.name,!this.options.annexB||this.state.strict||e.generator||e.async?this.scope.treatFunctionsAsVar?5:8201:17,e.id.loc.start)}parseClass(e,t,r){this.next();const n=this.state.strict;return this.state.strict=!0,this.parseClassId(e,t,r),this.parseClassSuper(e),e.body=this.parseClassBody(!!e.superClass,n),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(29)||this.match(13)||this.match(8)}isClassMethod(){return this.match(10)}nameIsConstructor(e){return"Identifier"===e.type&&"constructor"===e.name||"StringLiteral"===e.type&&"constructor"===e.value}isNonstaticConstructor(e){return!e.computed&&!e.static&&this.nameIsConstructor(e.key)}parseClassBody(e,t){this.classScope.enter();const r={hadConstructor:!1,hadSuperClass:e};let n=[];const s=this.startNode();if(s.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext((()=>{for(;!this.match(8);){if(this.eat(13)){if(n.length>0)throw this.raise(g.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){n.push(this.parseDecorator());continue}const e=this.startNode();n.length&&(e.decorators=n,this.resetStartLocationFromNode(e,n[0]),n=[]),this.parseClassMember(s,e,r),"constructor"===e.kind&&e.decorators&&e.decorators.length>0&&this.raise(g.DecoratorConstructor,e)}})),this.state.strict=t,this.next(),n.length)throw this.raise(g.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(s,"ClassBody")}parseClassMemberFromModifier(e,t){const r=this.parseIdentifier(!0);if(this.isClassMethod()){const n=t;return n.kind="method",n.computed=!1,n.key=r,n.static=!1,this.pushClassMethod(e,n,!1,!1,!1,!1),!0}if(this.isClassProperty()){const n=t;return n.computed=!1,n.key=r,n.static=!1,e.body.push(this.parseClassProperty(n)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(e,t,r){const n=this.isContextual(106);if(n){if(this.parseClassMemberFromModifier(e,t))return;if(this.eat(5))return void this.parseClassStaticBlock(e,t)}this.parseClassMemberWithIsStatic(e,t,r,n)}parseClassMemberWithIsStatic(e,t,r,n){const s=t,i=t,a=t,o=t,l=t,c=s,p=s;if(t.static=n,this.parsePropertyNamePrefixOperator(t),this.eat(55)){c.kind="method";const t=this.match(139);return this.parseClassElementName(c),t?void this.pushClassPrivateMethod(e,i,!0,!1):(this.isNonstaticConstructor(s)&&this.raise(g.ConstructorIsGenerator,s.key),void this.pushClassMethod(e,s,!0,!1,!1,!1))}const u=!this.state.containsEsc&&q(this.state.type),d=this.parseClassElementName(t),f=u?d.name:null,h=this.isPrivateName(d),m=this.state.startLoc;if(this.parsePostMemberNameModifiers(p),this.isClassMethod()){if(c.kind="method",h)return void this.pushClassPrivateMethod(e,i,!1,!1);const n=this.isNonstaticConstructor(s);let a=!1;n&&(s.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(g.DuplicateConstructor,d),n&&this.hasPlugin("typescript")&&t.override&&this.raise(g.OverrideOnConstructor,d),r.hadConstructor=!0,a=r.hadSuperClass),this.pushClassMethod(e,s,!1,!1,n,a)}else if(this.isClassProperty())h?this.pushClassPrivateProperty(e,o):this.pushClassProperty(e,a);else if("async"!==f||this.isLineTerminator())if("get"!==f&&"set"!==f||this.match(55)&&this.isLineTerminator())if("accessor"!==f||this.isLineTerminator())this.isLineTerminator()?h?this.pushClassPrivateProperty(e,o):this.pushClassProperty(e,a):this.unexpected();else{this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(d);const t=this.match(139);this.parseClassElementName(a),this.pushClassAccessorProperty(e,l,t)}else{this.resetPreviousNodeTrailingComments(d),c.kind=f;const t=this.match(139);this.parseClassElementName(s),t?this.pushClassPrivateMethod(e,i,!1,!1):(this.isNonstaticConstructor(s)&&this.raise(g.ConstructorIsAccessor,s.key),this.pushClassMethod(e,s,!1,!1,!1,!1)),this.checkGetterSetterParams(s)}else{this.resetPreviousNodeTrailingComments(d);const t=this.eat(55);p.optional&&this.unexpected(m),c.kind="method";const r=this.match(139);this.parseClassElementName(c),this.parsePostMemberNameModifiers(p),r?this.pushClassPrivateMethod(e,i,t,!0):(this.isNonstaticConstructor(s)&&this.raise(g.ConstructorIsAsync,s.key),this.pushClassMethod(e,s,t,!0,!1,!1))}}parseClassElementName(e){const{type:t,value:r}=this.state;if(132!==t&&134!==t||!e.static||"prototype"!==r||this.raise(g.StaticPrototype,this.state.startLoc),139===t){"constructor"===r&&this.raise(g.ConstructorClassPrivateField,this.state.startLoc);const t=this.parsePrivateName();return e.key=t,t}return this.parsePropertyName(e),e.key}parseClassStaticBlock(e,t){var r;this.scope.enter(208);const n=this.state.labels;this.state.labels=[],this.prodParam.enter(0);const s=t.body=[];this.parseBlockOrModuleBlockBody(s,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=n,e.body.push(this.finishNode(t,"StaticBlock")),null!=(r=t.decorators)&&r.length&&this.raise(g.DecoratorStaticBlock,t)}pushClassProperty(e,t){!t.computed&&this.nameIsConstructor(t.key)&&this.raise(g.ConstructorClassField,t.key),e.body.push(this.parseClassProperty(t))}pushClassPrivateProperty(e,t){const r=this.parseClassPrivateProperty(t);e.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(e,t,r){r||t.computed||!this.nameIsConstructor(t.key)||this.raise(g.ConstructorClassField,t.key);const n=this.parseClassAccessorProperty(t);e.body.push(n),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),0,n.key.loc.start)}pushClassMethod(e,t,r,n,s,i){e.body.push(this.parseMethod(t,r,n,s,i,"ClassMethod",!0))}pushClassPrivateMethod(e,t,r,n){const s=this.parseMethod(t,r,n,!1,!1,"ClassPrivateMethod",!0);e.body.push(s);const i="get"===s.kind?s.static?6:2:"set"===s.kind?s.static?5:1:0;this.declareClassPrivateMethodInScope(s,i)}declareClassPrivateMethodInScope(e,t){this.classScope.declarePrivateName(this.getPrivateNameSV(e.key),t,e.key.loc.start)}parsePostMemberNameModifiers(e){}parseClassPrivateProperty(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassPrivateProperty")}parseClassProperty(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassProperty")}parseClassAccessorProperty(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassAccessorProperty")}parseInitializer(e){this.scope.enter(80),this.expressionScope.enter(Je()),this.prodParam.enter(0),e.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(e,t,r,n=8331){if(q(this.state.type))e.id=this.parseIdentifier(),t&&this.declareNameFromIdentifier(e.id,n);else{if(!r&&t)throw this.raise(g.MissingClassName,this.state.startLoc);e.id=null}}parseClassSuper(e){e.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(e,t){const r=this.parseMaybeImportPhase(e,!0),n=this.maybeParseExportDefaultSpecifier(e,r),s=!n||this.eat(12),i=s&&this.eatExportStar(e),a=i&&this.maybeParseExportNamespaceSpecifier(e),o=s&&(!a||this.eat(12)),l=n||i;if(i&&!a){if(n&&this.unexpected(),t)throw this.raise(g.UnsupportedDecoratorExport,e);return this.parseExportFrom(e,!0),this.finishNode(e,"ExportAllDeclaration")}const c=this.maybeParseExportNamedSpecifiers(e);let p;if(n&&s&&!i&&!c&&this.unexpected(null,5),a&&o&&this.unexpected(null,98),l||c){if(p=!1,t)throw this.raise(g.UnsupportedDecoratorExport,e);this.parseExportFrom(e,l)}else p=this.maybeParseExportDeclaration(e);if(l||c||p){var u;const r=e;if(this.checkExport(r,!0,!1,!!r.source),"ClassDeclaration"===(null==(u=r.declaration)?void 0:u.type))this.maybeTakeDecorators(t,r.declaration,r);else if(t)throw this.raise(g.UnsupportedDecoratorExport,e);return this.finishNode(r,"ExportNamedDeclaration")}if(this.eat(65)){const r=e,n=this.parseExportDefaultExpression();if(r.declaration=n,"ClassDeclaration"===n.type)this.maybeTakeDecorators(t,n,r);else if(t)throw this.raise(g.UnsupportedDecoratorExport,e);return this.checkExport(r,!0,!0),this.finishNode(r,"ExportDefaultDeclaration")}this.unexpected(null,5)}eatExportStar(e){return this.eat(55)}maybeParseExportDefaultSpecifier(e,t){if(t||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",null==t?void 0:t.loc.start);const r=t||this.parseIdentifier(!0),n=this.startNodeAtNode(r);return n.exported=r,e.specifiers=[this.finishNode(n,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(e){if(this.isContextual(93)){var t;null!=(t=e).specifiers||(t.specifiers=[]);const r=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),r.exported=this.parseModuleExportName(),e.specifiers.push(this.finishNode(r,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(e){if(this.match(5)){const t=e;t.specifiers||(t.specifiers=[]);const r="type"===t.exportKind;return t.specifiers.push(...this.parseExportSpecifiers(r)),t.source=null,t.declaration=null,this.hasPlugin("importAssertions")&&(t.assertions=[]),!0}return!1}maybeParseExportDeclaration(e){return!!this.shouldParseExportDeclaration()&&(e.specifiers=[],e.source=null,this.hasPlugin("importAssertions")&&(e.assertions=[]),e.declaration=this.parseExportDeclaration(e),!0)}isAsyncFunction(){if(!this.isContextual(95))return!1;const e=this.nextTokenInLineStart();return this.isUnparsedContextual(e,"function")}parseExportDefaultExpression(){const e=this.startNode();if(this.match(68))return this.next(),this.parseFunction(e,5);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(e,13);if(this.match(80))return this.parseClass(e,!0,!0);if(this.match(26))return this.hasPlugin("decorators")&&!0===this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(g.DecoratorBeforeExport,this.state.startLoc),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet())throw this.raise(g.UnsupportedDefaultExport,this.state.startLoc);const t=this.parseMaybeAssignAllowIn();return this.semicolon(),t}parseExportDeclaration(e){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){const{type:e}=this.state;if(q(e)){if(95===e&&!this.state.containsEsc||100===e)return!1;if((130===e||129===e)&&!this.state.containsEsc){const{type:e}=this.lookahead();if(q(e)&&98!==e||5===e)return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;const t=this.nextTokenStart(),r=this.isUnparsedContextual(t,"from");if(44===this.input.charCodeAt(t)||q(this.state.type)&&r)return!0;if(this.match(65)&&r){const e=this.input.charCodeAt(this.nextTokenStartSince(t+4));return 34===e||39===e}return!1}parseExportFrom(e,t){this.eatContextual(98)?(e.source=this.parseImportSource(),this.checkExport(e),this.maybeParseImportAttributes(e),this.checkJSONModuleImport(e)):t&&this.unexpected(),this.semicolon()}shouldParseExportDeclaration(){const{type:e}=this.state;return 26===e&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))?(!0===this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(g.DecoratorBeforeExport,this.state.startLoc),!0):this.isContextual(107)||this.isContextual(96)&&this.startsAwaitUsing()?(this.raise(g.UsingDeclarationExport,this.state.startLoc),!0):74===e||75===e||68===e||80===e||this.isLet()||this.isAsyncFunction()}checkExport(e,t,r,n){var s;if(t)if(r){if(this.checkDuplicateExports(e,"default"),this.hasPlugin("exportDefaultFrom")){var i;const t=e.declaration;"Identifier"!==t.type||"from"!==t.name||t.end-t.start!=4||null!=(i=t.extra)&&i.parenthesized||this.raise(g.ExportDefaultFromAsIdentifier,t)}}else if(null!=(s=e.specifiers)&&s.length)for(const t of e.specifiers){const{exported:e}=t,r="Identifier"===e.type?e.name:e.value;if(this.checkDuplicateExports(t,r),!n&&t.local){const{local:e}=t;"Identifier"!==e.type?this.raise(g.ExportBindingIsString,t,{localName:e.value,exportName:r}):(this.checkReservedWord(e.name,e.loc.start,!0,!1),this.scope.checkLocalExport(e))}}else if(e.declaration){const t=e.declaration;if("FunctionDeclaration"===t.type||"ClassDeclaration"===t.type){const{id:r}=t;if(!r)throw new Error("Assertion failure");this.checkDuplicateExports(e,r.name)}else if("VariableDeclaration"===t.type)for(const e of t.declarations)this.checkDeclaration(e.id)}}checkDeclaration(e){if("Identifier"===e.type)this.checkDuplicateExports(e,e.name);else if("ObjectPattern"===e.type)for(const t of e.properties)this.checkDeclaration(t);else if("ArrayPattern"===e.type)for(const t of e.elements)t&&this.checkDeclaration(t);else"ObjectProperty"===e.type?this.checkDeclaration(e.value):"RestElement"===e.type?this.checkDeclaration(e.argument):"AssignmentPattern"===e.type&&this.checkDeclaration(e.left)}checkDuplicateExports(e,t){this.exportedIdentifiers.has(t)&&("default"===t?this.raise(g.DuplicateDefaultExport,e):this.raise(g.DuplicateExport,e,{exportName:t})),this.exportedIdentifiers.add(t)}parseExportSpecifiers(e){const t=[];let r=!0;for(this.expect(5);!this.eat(8);){if(r)r=!1;else if(this.expect(12),this.eat(8))break;const n=this.isContextual(130),s=this.match(134),i=this.startNode();i.local=this.parseModuleExportName(),t.push(this.parseExportSpecifier(i,s,e,n))}return t}parseExportSpecifier(e,t,r,n){return this.eatContextual(93)?e.exported=this.parseModuleExportName():t?e.exported=function(e){const{type:t,start:r,end:n,loc:s,range:i,extra:a}=e;if("Placeholder"===t)return function(e){return rt(e)}(e);const o=Object.create(tt);return o.type=t,o.start=r,o.end=n,o.loc=s,o.range=i,void 0!==e.raw?o.raw=e.raw:o.extra=a,o.value=e.value,o}(e.local):e.exported||(e.exported=rt(e.local)),this.finishNode(e,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){const e=this.parseStringLiteral(this.state.value),t=Dt.exec(e.value);return t&&this.raise(g.ModuleExportNameHasLoneSurrogate,e,{surrogateCharCode:t[0].charCodeAt(0)}),e}return this.parseIdentifier(!0)}isJSONModuleImport(e){return null!=e.assertions&&e.assertions.some((({key:e,value:t})=>"json"===t.value&&("Identifier"===e.type?"type"===e.name:"type"===e.value)))}checkImportReflection(e){const{specifiers:t}=e,r=1===t.length?t[0].type:null;if("source"===e.phase)"ImportDefaultSpecifier"!==r&&this.raise(g.SourcePhaseImportRequiresDefault,t[0].loc.start);else if("defer"===e.phase)"ImportNamespaceSpecifier"!==r&&this.raise(g.DeferImportRequiresNamespace,t[0].loc.start);else if(e.module){var n;"ImportDefaultSpecifier"!==r&&this.raise(g.ImportReflectionNotBinding,t[0].loc.start),(null==(n=e.assertions)?void 0:n.length)>0&&this.raise(g.ImportReflectionHasAssertion,t[0].loc.start)}}checkJSONModuleImport(e){if(this.isJSONModuleImport(e)&&"ExportAllDeclaration"!==e.type){const{specifiers:t}=e;if(null!=t){const e=t.find((e=>{let t;if("ExportSpecifier"===e.type?t=e.local:"ImportSpecifier"===e.type&&(t=e.imported),void 0!==t)return"Identifier"===t.type?"default"!==t.name:"default"!==t.value}));void 0!==e&&this.raise(g.ImportJSONBindingNotDefault,e.loc.start)}}}isPotentialImportPhase(e){return!e&&(this.isContextual(105)||this.isContextual(97)||this.isContextual(127))}applyImportPhase(e,t,r,n){t||("module"===r?(this.expectPlugin("importReflection",n),e.module=!0):this.hasPlugin("importReflection")&&(e.module=!1),"source"===r?(this.expectPlugin("sourcePhaseImports",n),e.phase="source"):"defer"===r?(this.expectPlugin("deferredImportEvaluation",n),e.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(e.phase=null))}parseMaybeImportPhase(e,t){if(!this.isPotentialImportPhase(t))return this.applyImportPhase(e,t,null),null;const r=this.parseIdentifier(!0),{type:n}=this.state;return(W(n)?98!==n||102===this.lookaheadCharCode():12!==n)?(this.resetPreviousIdentifierLeadingComments(r),this.applyImportPhase(e,t,r.name,r.loc.start),null):(this.applyImportPhase(e,t,null),r)}isPrecedingIdImportPhase(e){const{type:t}=this.state;return q(t)?98!==t||102===this.lookaheadCharCode():12!==t}parseImport(e){return this.match(134)?this.parseImportSourceAndAttributes(e):this.parseImportSpecifiersAndAfter(e,this.parseMaybeImportPhase(e,!1))}parseImportSpecifiersAndAfter(e,t){e.specifiers=[];const r=!this.maybeParseDefaultImportSpecifier(e,t)||this.eat(12),n=r&&this.maybeParseStarImportSpecifier(e);return r&&!n&&this.parseNamedImportSpecifiers(e),this.expectContextual(98),this.parseImportSourceAndAttributes(e)}parseImportSourceAndAttributes(e){return null!=e.specifiers||(e.specifiers=[]),e.source=this.parseImportSource(),this.maybeParseImportAttributes(e),this.checkImportReflection(e),this.checkJSONModuleImport(e),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.match(134)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(e,t,r){t.local=this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(t,r))}finishImportSpecifier(e,t,r=8201){return this.checkLVal(e.local,{type:t},r),this.finishNode(e,t)}parseImportAttributes(){this.expect(5);const e=[],t=new Set;do{if(this.match(8))break;const r=this.startNode(),n=this.state.value;if(t.has(n)&&this.raise(g.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:n}),t.add(n),this.match(134)?r.key=this.parseStringLiteral(n):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(g.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),e.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return this.expect(8),e}parseModuleAttributes(){const e=[],t=new Set;do{const r=this.startNode();if(r.key=this.parseIdentifier(!0),"type"!==r.key.name&&this.raise(g.ModuleAttributeDifferentFromType,r.key),t.has(r.key.name)&&this.raise(g.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),t.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(g.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),e.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return e}maybeParseImportAttributes(e){let t;var r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&40===this.lookaheadCharCode())return;this.next(),t=this.hasPlugin("moduleAttributes")?this.parseModuleAttributes():this.parseImportAttributes(),r=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(this.hasPlugin("deprecatedImportAssert")||this.hasPlugin("importAssertions")||this.raise(g.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(e,"deprecatedAssertSyntax",!0),this.next(),t=this.parseImportAttributes()):t=[];!r&&this.hasPlugin("importAssertions")?e.assertions=t:e.attributes=t}maybeParseDefaultImportSpecifier(e,t){if(t){const r=this.startNodeAtNode(t);return r.local=t,e.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}return!!W(this.state.type)&&(this.parseImportSpecifierLocal(e,this.startNode(),"ImportDefaultSpecifier"),!0)}maybeParseStarImportSpecifier(e){if(this.match(55)){const t=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(e,t,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(e){let t=!0;for(this.expect(5);!this.eat(8);){if(t)t=!1;else{if(this.eat(14))throw this.raise(g.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}const r=this.startNode(),n=this.match(134),s=this.isContextual(130);r.imported=this.parseModuleExportName();const i=this.parseImportSpecifier(r,n,"type"===e.importKind||"typeof"===e.importKind,s,void 0);e.specifiers.push(i)}}parseImportSpecifier(e,t,r,n,s){if(this.eatContextual(93))e.local=this.parseIdentifier();else{const{imported:r}=e;if(t)throw this.raise(g.ImportBindingIsString,e,{importName:r.value});this.checkReservedWord(r.name,e.loc.start,!0,!0),e.local||(e.local=rt(r))}return this.finishImportSpecifier(e,"ImportSpecifier",s)}isThisParam(e){return"Identifier"===e.type&&"this"===e.name}}class Mt extends Bt{constructor(e,t,r){super(e=function(e){const t={sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,plugins:[],strictMode:null,ranges:!1,tokens:!1,createImportExpressions:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0};if(null==e)return t;if(null!=e.annexB&&!1!==e.annexB)throw new Error("The `annexB` option can only be set to `false`.");for(const r of Object.keys(t))null!=e[r]&&(t[r]=e[r]);if(1===t.startLine)null==e.startIndex&&t.startColumn>0?t.startIndex=t.startColumn:null==e.startColumn&&t.startIndex>0&&(t.startColumn=t.startIndex);else if((null==e.startColumn||null==e.startIndex)&&null!=e.startIndex)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");return t}(e),t),this.options=e,this.initializeScopes(),this.plugins=r,this.filename=e.sourceFilename,this.startIndex=e.startIndex;let n=0;e.allowAwaitOutsideFunction&&(n|=1),e.allowReturnOutsideFunction&&(n|=2),e.allowImportExportEverywhere&&(n|=8),e.allowSuperOutsideMethod&&(n|=16),e.allowUndeclaredExports&&(n|=32),e.allowNewTargetOutsideFunction&&(n|=4),e.ranges&&(n|=64),e.tokens&&(n|=128),e.createImportExpressions&&(n|=256),e.createParenthesizedExpressions&&(n|=512),e.errorRecovery&&(n|=1024),e.attachComment&&(n|=2048),e.annexB&&(n|=4096),this.optionFlags=n}getScopeHandler(){return ye}parse(){this.enterInitialScopes();const e=this.startNode(),t=this.startNode();return this.nextToken(),e.errors=null,this.parseTopLevel(e,t),e.errors=this.state.errors,e.comments.length=this.state.commentsLen,e}}const Lt=function(e){const t={};for(const r of Object.keys(e))t[r]=X(e[r]);return t}(V);function Ft(e,t){let r=Mt;const n=new Map;if(null!=e&&e.plugins){for(const t of e.plugins){let e,r;"string"==typeof t?e=t:[e,r]=t,n.has(e)||n.set(e,r||{})}!function(e){if(e.has("decorators")){if(e.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");const t=e.get("decorators").decoratorsBeforeExport;if(null!=t&&"boolean"!=typeof t)throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");const r=e.get("decorators").allowCallParenthesized;if(null!=r&&"boolean"!=typeof r)throw new Error("'allowCallParenthesized' must be a boolean.")}if(e.has("flow")&&e.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(e.has("placeholders")&&e.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(e.has("pipelineOperator")){var t;const r=e.get("pipelineOperator").proposal;if(!wt.includes(r)){const e=wt.map((e=>`"${e}"`)).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${e}.`)}const n="hash"===(null==(t=e.get("recordAndTuple"))?void 0:t.syntaxType);if("hack"===r){if(e.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(e.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");const t=e.get("pipelineOperator").topicToken;if(!Ct.includes(t)){const e=Ct.map((e=>`"${e}"`)).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${e}.`)}if("#"===t&&n)throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",e.get("recordAndTuple")])}\`.`)}else if("smart"===r&&n)throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",e.get("recordAndTuple")])}\`.`)}if(e.has("moduleAttributes")){if(e.has("deprecatedImportAssert")||e.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if("may-2020"!==e.get("moduleAttributes").version)throw new Error("The 'moduleAttributes' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is 'may-2020'.")}if(e.has("importAssertions")&&e.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(!e.has("deprecatedImportAssert")&&e.has("importAttributes")&&e.get("importAttributes").deprecatedAssertSyntax&&e.set("deprecatedImportAssert",{}),e.has("recordAndTuple")){const t=e.get("recordAndTuple").syntaxType;if(null!=t){const e=["hash","bar"];if(!e.includes(t))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+e.map((e=>`'${e}'`)).join(", "))}}if(e.has("asyncDoExpressions")&&!e.has("doExpressions")){const e=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw e.missingPlugins="doExpressions",e}if(e.has("optionalChainingAssign")&&"2023-07"!==e.get("optionalChainingAssign").version)throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.")}(n),r=function(e){const t=[];for(const r of It)e.has(r)&&t.push(r);const r=t.join("|");let n=Rt.get(r);if(!n){n=Mt;for(const e of t)n=Ot[e](n);Rt.set(r,n)}return n}(n)}return new r(e,t,n)}const Rt=new Map;t.parse=function(e,t){var r;if("unambiguous"!==(null==(r=t)?void 0:r.sourceType))return Ft(t,e).parse();t=Object.assign({},t);try{t.sourceType="module";const r=Ft(t,e),n=r.parse();if(r.sawUnambiguousESM)return n;if(r.ambiguousScriptDifferentAst)try{return t.sourceType="script",Ft(t,e).parse()}catch(e){}else n.program.sourceType="script";return n}catch(r){try{return t.sourceType="script",Ft(t,e).parse()}catch(e){}throw r}},t.parseExpression=function(e,t){const r=Ft(t,e);return r.options.strictMode&&(r.state.strict=!0),r.getExpression()},t.tokTypes=Lt},2205:(e,t,r)=>{"use strict";var n=r(6743),s=r(1002),i=r(3144);e.exports=function(){return i(n,s,arguments)}},2226:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaggedTemplateExpression=function(e){this.print(e.tag),this.print(e.typeParameters),this.print(e.quasi)},t.TemplateElement=function(){throw new Error("TemplateElement printing is handled in TemplateLiteral")},t.TemplateLiteral=function(e){this._printTemplate(e,e.expressions)},t._printTemplate=function(e,t){const r=e.quasis;let n="`";for(let s=0;s<r.length-1;s++)if(n+=r[s].value.raw,this.token(n+"${",!0),this.print(t[s]),n="}",this.tokenMap){const t=this.tokenMap.findMatching(e,"}",s);t&&this._catchUpTo(t.loc.start)}n+=r[r.length-1].value.raw,this.token(n+"`",!0)}},2234:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return"eval"!==(e=(0,n.default)(e))&&"arguments"!==e||(e="_"+e),e};var n=r(6744)},2246:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertAccessor=function(e,t){i("Accessor",e,t)},t.assertAnyTypeAnnotation=function(e,t){i("AnyTypeAnnotation",e,t)},t.assertArgumentPlaceholder=function(e,t){i("ArgumentPlaceholder",e,t)},t.assertArrayExpression=function(e,t){i("ArrayExpression",e,t)},t.assertArrayPattern=function(e,t){i("ArrayPattern",e,t)},t.assertArrayTypeAnnotation=function(e,t){i("ArrayTypeAnnotation",e,t)},t.assertArrowFunctionExpression=function(e,t){i("ArrowFunctionExpression",e,t)},t.assertAssignmentExpression=function(e,t){i("AssignmentExpression",e,t)},t.assertAssignmentPattern=function(e,t){i("AssignmentPattern",e,t)},t.assertAwaitExpression=function(e,t){i("AwaitExpression",e,t)},t.assertBigIntLiteral=function(e,t){i("BigIntLiteral",e,t)},t.assertBinary=function(e,t){i("Binary",e,t)},t.assertBinaryExpression=function(e,t){i("BinaryExpression",e,t)},t.assertBindExpression=function(e,t){i("BindExpression",e,t)},t.assertBlock=function(e,t){i("Block",e,t)},t.assertBlockParent=function(e,t){i("BlockParent",e,t)},t.assertBlockStatement=function(e,t){i("BlockStatement",e,t)},t.assertBooleanLiteral=function(e,t){i("BooleanLiteral",e,t)},t.assertBooleanLiteralTypeAnnotation=function(e,t){i("BooleanLiteralTypeAnnotation",e,t)},t.assertBooleanTypeAnnotation=function(e,t){i("BooleanTypeAnnotation",e,t)},t.assertBreakStatement=function(e,t){i("BreakStatement",e,t)},t.assertCallExpression=function(e,t){i("CallExpression",e,t)},t.assertCatchClause=function(e,t){i("CatchClause",e,t)},t.assertClass=function(e,t){i("Class",e,t)},t.assertClassAccessorProperty=function(e,t){i("ClassAccessorProperty",e,t)},t.assertClassBody=function(e,t){i("ClassBody",e,t)},t.assertClassDeclaration=function(e,t){i("ClassDeclaration",e,t)},t.assertClassExpression=function(e,t){i("ClassExpression",e,t)},t.assertClassImplements=function(e,t){i("ClassImplements",e,t)},t.assertClassMethod=function(e,t){i("ClassMethod",e,t)},t.assertClassPrivateMethod=function(e,t){i("ClassPrivateMethod",e,t)},t.assertClassPrivateProperty=function(e,t){i("ClassPrivateProperty",e,t)},t.assertClassProperty=function(e,t){i("ClassProperty",e,t)},t.assertCompletionStatement=function(e,t){i("CompletionStatement",e,t)},t.assertConditional=function(e,t){i("Conditional",e,t)},t.assertConditionalExpression=function(e,t){i("ConditionalExpression",e,t)},t.assertContinueStatement=function(e,t){i("ContinueStatement",e,t)},t.assertDebuggerStatement=function(e,t){i("DebuggerStatement",e,t)},t.assertDecimalLiteral=function(e,t){i("DecimalLiteral",e,t)},t.assertDeclaration=function(e,t){i("Declaration",e,t)},t.assertDeclareClass=function(e,t){i("DeclareClass",e,t)},t.assertDeclareExportAllDeclaration=function(e,t){i("DeclareExportAllDeclaration",e,t)},t.assertDeclareExportDeclaration=function(e,t){i("DeclareExportDeclaration",e,t)},t.assertDeclareFunction=function(e,t){i("DeclareFunction",e,t)},t.assertDeclareInterface=function(e,t){i("DeclareInterface",e,t)},t.assertDeclareModule=function(e,t){i("DeclareModule",e,t)},t.assertDeclareModuleExports=function(e,t){i("DeclareModuleExports",e,t)},t.assertDeclareOpaqueType=function(e,t){i("DeclareOpaqueType",e,t)},t.assertDeclareTypeAlias=function(e,t){i("DeclareTypeAlias",e,t)},t.assertDeclareVariable=function(e,t){i("DeclareVariable",e,t)},t.assertDeclaredPredicate=function(e,t){i("DeclaredPredicate",e,t)},t.assertDecorator=function(e,t){i("Decorator",e,t)},t.assertDirective=function(e,t){i("Directive",e,t)},t.assertDirectiveLiteral=function(e,t){i("DirectiveLiteral",e,t)},t.assertDoExpression=function(e,t){i("DoExpression",e,t)},t.assertDoWhileStatement=function(e,t){i("DoWhileStatement",e,t)},t.assertEmptyStatement=function(e,t){i("EmptyStatement",e,t)},t.assertEmptyTypeAnnotation=function(e,t){i("EmptyTypeAnnotation",e,t)},t.assertEnumBody=function(e,t){i("EnumBody",e,t)},t.assertEnumBooleanBody=function(e,t){i("EnumBooleanBody",e,t)},t.assertEnumBooleanMember=function(e,t){i("EnumBooleanMember",e,t)},t.assertEnumDeclaration=function(e,t){i("EnumDeclaration",e,t)},t.assertEnumDefaultedMember=function(e,t){i("EnumDefaultedMember",e,t)},t.assertEnumMember=function(e,t){i("EnumMember",e,t)},t.assertEnumNumberBody=function(e,t){i("EnumNumberBody",e,t)},t.assertEnumNumberMember=function(e,t){i("EnumNumberMember",e,t)},t.assertEnumStringBody=function(e,t){i("EnumStringBody",e,t)},t.assertEnumStringMember=function(e,t){i("EnumStringMember",e,t)},t.assertEnumSymbolBody=function(e,t){i("EnumSymbolBody",e,t)},t.assertExistsTypeAnnotation=function(e,t){i("ExistsTypeAnnotation",e,t)},t.assertExportAllDeclaration=function(e,t){i("ExportAllDeclaration",e,t)},t.assertExportDeclaration=function(e,t){i("ExportDeclaration",e,t)},t.assertExportDefaultDeclaration=function(e,t){i("ExportDefaultDeclaration",e,t)},t.assertExportDefaultSpecifier=function(e,t){i("ExportDefaultSpecifier",e,t)},t.assertExportNamedDeclaration=function(e,t){i("ExportNamedDeclaration",e,t)},t.assertExportNamespaceSpecifier=function(e,t){i("ExportNamespaceSpecifier",e,t)},t.assertExportSpecifier=function(e,t){i("ExportSpecifier",e,t)},t.assertExpression=function(e,t){i("Expression",e,t)},t.assertExpressionStatement=function(e,t){i("ExpressionStatement",e,t)},t.assertExpressionWrapper=function(e,t){i("ExpressionWrapper",e,t)},t.assertFile=function(e,t){i("File",e,t)},t.assertFlow=function(e,t){i("Flow",e,t)},t.assertFlowBaseAnnotation=function(e,t){i("FlowBaseAnnotation",e,t)},t.assertFlowDeclaration=function(e,t){i("FlowDeclaration",e,t)},t.assertFlowPredicate=function(e,t){i("FlowPredicate",e,t)},t.assertFlowType=function(e,t){i("FlowType",e,t)},t.assertFor=function(e,t){i("For",e,t)},t.assertForInStatement=function(e,t){i("ForInStatement",e,t)},t.assertForOfStatement=function(e,t){i("ForOfStatement",e,t)},t.assertForStatement=function(e,t){i("ForStatement",e,t)},t.assertForXStatement=function(e,t){i("ForXStatement",e,t)},t.assertFunction=function(e,t){i("Function",e,t)},t.assertFunctionDeclaration=function(e,t){i("FunctionDeclaration",e,t)},t.assertFunctionExpression=function(e,t){i("FunctionExpression",e,t)},t.assertFunctionParent=function(e,t){i("FunctionParent",e,t)},t.assertFunctionTypeAnnotation=function(e,t){i("FunctionTypeAnnotation",e,t)},t.assertFunctionTypeParam=function(e,t){i("FunctionTypeParam",e,t)},t.assertGenericTypeAnnotation=function(e,t){i("GenericTypeAnnotation",e,t)},t.assertIdentifier=function(e,t){i("Identifier",e,t)},t.assertIfStatement=function(e,t){i("IfStatement",e,t)},t.assertImmutable=function(e,t){i("Immutable",e,t)},t.assertImport=function(e,t){i("Import",e,t)},t.assertImportAttribute=function(e,t){i("ImportAttribute",e,t)},t.assertImportDeclaration=function(e,t){i("ImportDeclaration",e,t)},t.assertImportDefaultSpecifier=function(e,t){i("ImportDefaultSpecifier",e,t)},t.assertImportExpression=function(e,t){i("ImportExpression",e,t)},t.assertImportNamespaceSpecifier=function(e,t){i("ImportNamespaceSpecifier",e,t)},t.assertImportOrExportDeclaration=function(e,t){i("ImportOrExportDeclaration",e,t)},t.assertImportSpecifier=function(e,t){i("ImportSpecifier",e,t)},t.assertIndexedAccessType=function(e,t){i("IndexedAccessType",e,t)},t.assertInferredPredicate=function(e,t){i("InferredPredicate",e,t)},t.assertInterfaceDeclaration=function(e,t){i("InterfaceDeclaration",e,t)},t.assertInterfaceExtends=function(e,t){i("InterfaceExtends",e,t)},t.assertInterfaceTypeAnnotation=function(e,t){i("InterfaceTypeAnnotation",e,t)},t.assertInterpreterDirective=function(e,t){i("InterpreterDirective",e,t)},t.assertIntersectionTypeAnnotation=function(e,t){i("IntersectionTypeAnnotation",e,t)},t.assertJSX=function(e,t){i("JSX",e,t)},t.assertJSXAttribute=function(e,t){i("JSXAttribute",e,t)},t.assertJSXClosingElement=function(e,t){i("JSXClosingElement",e,t)},t.assertJSXClosingFragment=function(e,t){i("JSXClosingFragment",e,t)},t.assertJSXElement=function(e,t){i("JSXElement",e,t)},t.assertJSXEmptyExpression=function(e,t){i("JSXEmptyExpression",e,t)},t.assertJSXExpressionContainer=function(e,t){i("JSXExpressionContainer",e,t)},t.assertJSXFragment=function(e,t){i("JSXFragment",e,t)},t.assertJSXIdentifier=function(e,t){i("JSXIdentifier",e,t)},t.assertJSXMemberExpression=function(e,t){i("JSXMemberExpression",e,t)},t.assertJSXNamespacedName=function(e,t){i("JSXNamespacedName",e,t)},t.assertJSXOpeningElement=function(e,t){i("JSXOpeningElement",e,t)},t.assertJSXOpeningFragment=function(e,t){i("JSXOpeningFragment",e,t)},t.assertJSXSpreadAttribute=function(e,t){i("JSXSpreadAttribute",e,t)},t.assertJSXSpreadChild=function(e,t){i("JSXSpreadChild",e,t)},t.assertJSXText=function(e,t){i("JSXText",e,t)},t.assertLVal=function(e,t){i("LVal",e,t)},t.assertLabeledStatement=function(e,t){i("LabeledStatement",e,t)},t.assertLiteral=function(e,t){i("Literal",e,t)},t.assertLogicalExpression=function(e,t){i("LogicalExpression",e,t)},t.assertLoop=function(e,t){i("Loop",e,t)},t.assertMemberExpression=function(e,t){i("MemberExpression",e,t)},t.assertMetaProperty=function(e,t){i("MetaProperty",e,t)},t.assertMethod=function(e,t){i("Method",e,t)},t.assertMiscellaneous=function(e,t){i("Miscellaneous",e,t)},t.assertMixedTypeAnnotation=function(e,t){i("MixedTypeAnnotation",e,t)},t.assertModuleDeclaration=function(e,t){(0,s.default)("assertModuleDeclaration","assertImportOrExportDeclaration"),i("ModuleDeclaration",e,t)},t.assertModuleExpression=function(e,t){i("ModuleExpression",e,t)},t.assertModuleSpecifier=function(e,t){i("ModuleSpecifier",e,t)},t.assertNewExpression=function(e,t){i("NewExpression",e,t)},t.assertNoop=function(e,t){i("Noop",e,t)},t.assertNullLiteral=function(e,t){i("NullLiteral",e,t)},t.assertNullLiteralTypeAnnotation=function(e,t){i("NullLiteralTypeAnnotation",e,t)},t.assertNullableTypeAnnotation=function(e,t){i("NullableTypeAnnotation",e,t)},t.assertNumberLiteral=function(e,t){(0,s.default)("assertNumberLiteral","assertNumericLiteral"),i("NumberLiteral",e,t)},t.assertNumberLiteralTypeAnnotation=function(e,t){i("NumberLiteralTypeAnnotation",e,t)},t.assertNumberTypeAnnotation=function(e,t){i("NumberTypeAnnotation",e,t)},t.assertNumericLiteral=function(e,t){i("NumericLiteral",e,t)},t.assertObjectExpression=function(e,t){i("ObjectExpression",e,t)},t.assertObjectMember=function(e,t){i("ObjectMember",e,t)},t.assertObjectMethod=function(e,t){i("ObjectMethod",e,t)},t.assertObjectPattern=function(e,t){i("ObjectPattern",e,t)},t.assertObjectProperty=function(e,t){i("ObjectProperty",e,t)},t.assertObjectTypeAnnotation=function(e,t){i("ObjectTypeAnnotation",e,t)},t.assertObjectTypeCallProperty=function(e,t){i("ObjectTypeCallProperty",e,t)},t.assertObjectTypeIndexer=function(e,t){i("ObjectTypeIndexer",e,t)},t.assertObjectTypeInternalSlot=function(e,t){i("ObjectTypeInternalSlot",e,t)},t.assertObjectTypeProperty=function(e,t){i("ObjectTypeProperty",e,t)},t.assertObjectTypeSpreadProperty=function(e,t){i("ObjectTypeSpreadProperty",e,t)},t.assertOpaqueType=function(e,t){i("OpaqueType",e,t)},t.assertOptionalCallExpression=function(e,t){i("OptionalCallExpression",e,t)},t.assertOptionalIndexedAccessType=function(e,t){i("OptionalIndexedAccessType",e,t)},t.assertOptionalMemberExpression=function(e,t){i("OptionalMemberExpression",e,t)},t.assertParenthesizedExpression=function(e,t){i("ParenthesizedExpression",e,t)},t.assertPattern=function(e,t){i("Pattern",e,t)},t.assertPatternLike=function(e,t){i("PatternLike",e,t)},t.assertPipelineBareFunction=function(e,t){i("PipelineBareFunction",e,t)},t.assertPipelinePrimaryTopicReference=function(e,t){i("PipelinePrimaryTopicReference",e,t)},t.assertPipelineTopicExpression=function(e,t){i("PipelineTopicExpression",e,t)},t.assertPlaceholder=function(e,t){i("Placeholder",e,t)},t.assertPrivate=function(e,t){i("Private",e,t)},t.assertPrivateName=function(e,t){i("PrivateName",e,t)},t.assertProgram=function(e,t){i("Program",e,t)},t.assertProperty=function(e,t){i("Property",e,t)},t.assertPureish=function(e,t){i("Pureish",e,t)},t.assertQualifiedTypeIdentifier=function(e,t){i("QualifiedTypeIdentifier",e,t)},t.assertRecordExpression=function(e,t){i("RecordExpression",e,t)},t.assertRegExpLiteral=function(e,t){i("RegExpLiteral",e,t)},t.assertRegexLiteral=function(e,t){(0,s.default)("assertRegexLiteral","assertRegExpLiteral"),i("RegexLiteral",e,t)},t.assertRestElement=function(e,t){i("RestElement",e,t)},t.assertRestProperty=function(e,t){(0,s.default)("assertRestProperty","assertRestElement"),i("RestProperty",e,t)},t.assertReturnStatement=function(e,t){i("ReturnStatement",e,t)},t.assertScopable=function(e,t){i("Scopable",e,t)},t.assertSequenceExpression=function(e,t){i("SequenceExpression",e,t)},t.assertSpreadElement=function(e,t){i("SpreadElement",e,t)},t.assertSpreadProperty=function(e,t){(0,s.default)("assertSpreadProperty","assertSpreadElement"),i("SpreadProperty",e,t)},t.assertStandardized=function(e,t){i("Standardized",e,t)},t.assertStatement=function(e,t){i("Statement",e,t)},t.assertStaticBlock=function(e,t){i("StaticBlock",e,t)},t.assertStringLiteral=function(e,t){i("StringLiteral",e,t)},t.assertStringLiteralTypeAnnotation=function(e,t){i("StringLiteralTypeAnnotation",e,t)},t.assertStringTypeAnnotation=function(e,t){i("StringTypeAnnotation",e,t)},t.assertSuper=function(e,t){i("Super",e,t)},t.assertSwitchCase=function(e,t){i("SwitchCase",e,t)},t.assertSwitchStatement=function(e,t){i("SwitchStatement",e,t)},t.assertSymbolTypeAnnotation=function(e,t){i("SymbolTypeAnnotation",e,t)},t.assertTSAnyKeyword=function(e,t){i("TSAnyKeyword",e,t)},t.assertTSArrayType=function(e,t){i("TSArrayType",e,t)},t.assertTSAsExpression=function(e,t){i("TSAsExpression",e,t)},t.assertTSBaseType=function(e,t){i("TSBaseType",e,t)},t.assertTSBigIntKeyword=function(e,t){i("TSBigIntKeyword",e,t)},t.assertTSBooleanKeyword=function(e,t){i("TSBooleanKeyword",e,t)},t.assertTSCallSignatureDeclaration=function(e,t){i("TSCallSignatureDeclaration",e,t)},t.assertTSConditionalType=function(e,t){i("TSConditionalType",e,t)},t.assertTSConstructSignatureDeclaration=function(e,t){i("TSConstructSignatureDeclaration",e,t)},t.assertTSConstructorType=function(e,t){i("TSConstructorType",e,t)},t.assertTSDeclareFunction=function(e,t){i("TSDeclareFunction",e,t)},t.assertTSDeclareMethod=function(e,t){i("TSDeclareMethod",e,t)},t.assertTSEntityName=function(e,t){i("TSEntityName",e,t)},t.assertTSEnumBody=function(e,t){i("TSEnumBody",e,t)},t.assertTSEnumDeclaration=function(e,t){i("TSEnumDeclaration",e,t)},t.assertTSEnumMember=function(e,t){i("TSEnumMember",e,t)},t.assertTSExportAssignment=function(e,t){i("TSExportAssignment",e,t)},t.assertTSExpressionWithTypeArguments=function(e,t){i("TSExpressionWithTypeArguments",e,t)},t.assertTSExternalModuleReference=function(e,t){i("TSExternalModuleReference",e,t)},t.assertTSFunctionType=function(e,t){i("TSFunctionType",e,t)},t.assertTSImportEqualsDeclaration=function(e,t){i("TSImportEqualsDeclaration",e,t)},t.assertTSImportType=function(e,t){i("TSImportType",e,t)},t.assertTSIndexSignature=function(e,t){i("TSIndexSignature",e,t)},t.assertTSIndexedAccessType=function(e,t){i("TSIndexedAccessType",e,t)},t.assertTSInferType=function(e,t){i("TSInferType",e,t)},t.assertTSInstantiationExpression=function(e,t){i("TSInstantiationExpression",e,t)},t.assertTSInterfaceBody=function(e,t){i("TSInterfaceBody",e,t)},t.assertTSInterfaceDeclaration=function(e,t){i("TSInterfaceDeclaration",e,t)},t.assertTSIntersectionType=function(e,t){i("TSIntersectionType",e,t)},t.assertTSIntrinsicKeyword=function(e,t){i("TSIntrinsicKeyword",e,t)},t.assertTSLiteralType=function(e,t){i("TSLiteralType",e,t)},t.assertTSMappedType=function(e,t){i("TSMappedType",e,t)},t.assertTSMethodSignature=function(e,t){i("TSMethodSignature",e,t)},t.assertTSModuleBlock=function(e,t){i("TSModuleBlock",e,t)},t.assertTSModuleDeclaration=function(e,t){i("TSModuleDeclaration",e,t)},t.assertTSNamedTupleMember=function(e,t){i("TSNamedTupleMember",e,t)},t.assertTSNamespaceExportDeclaration=function(e,t){i("TSNamespaceExportDeclaration",e,t)},t.assertTSNeverKeyword=function(e,t){i("TSNeverKeyword",e,t)},t.assertTSNonNullExpression=function(e,t){i("TSNonNullExpression",e,t)},t.assertTSNullKeyword=function(e,t){i("TSNullKeyword",e,t)},t.assertTSNumberKeyword=function(e,t){i("TSNumberKeyword",e,t)},t.assertTSObjectKeyword=function(e,t){i("TSObjectKeyword",e,t)},t.assertTSOptionalType=function(e,t){i("TSOptionalType",e,t)},t.assertTSParameterProperty=function(e,t){i("TSParameterProperty",e,t)},t.assertTSParenthesizedType=function(e,t){i("TSParenthesizedType",e,t)},t.assertTSPropertySignature=function(e,t){i("TSPropertySignature",e,t)},t.assertTSQualifiedName=function(e,t){i("TSQualifiedName",e,t)},t.assertTSRestType=function(e,t){i("TSRestType",e,t)},t.assertTSSatisfiesExpression=function(e,t){i("TSSatisfiesExpression",e,t)},t.assertTSStringKeyword=function(e,t){i("TSStringKeyword",e,t)},t.assertTSSymbolKeyword=function(e,t){i("TSSymbolKeyword",e,t)},t.assertTSTemplateLiteralType=function(e,t){i("TSTemplateLiteralType",e,t)},t.assertTSThisType=function(e,t){i("TSThisType",e,t)},t.assertTSTupleType=function(e,t){i("TSTupleType",e,t)},t.assertTSType=function(e,t){i("TSType",e,t)},t.assertTSTypeAliasDeclaration=function(e,t){i("TSTypeAliasDeclaration",e,t)},t.assertTSTypeAnnotation=function(e,t){i("TSTypeAnnotation",e,t)},t.assertTSTypeAssertion=function(e,t){i("TSTypeAssertion",e,t)},t.assertTSTypeElement=function(e,t){i("TSTypeElement",e,t)},t.assertTSTypeLiteral=function(e,t){i("TSTypeLiteral",e,t)},t.assertTSTypeOperator=function(e,t){i("TSTypeOperator",e,t)},t.assertTSTypeParameter=function(e,t){i("TSTypeParameter",e,t)},t.assertTSTypeParameterDeclaration=function(e,t){i("TSTypeParameterDeclaration",e,t)},t.assertTSTypeParameterInstantiation=function(e,t){i("TSTypeParameterInstantiation",e,t)},t.assertTSTypePredicate=function(e,t){i("TSTypePredicate",e,t)},t.assertTSTypeQuery=function(e,t){i("TSTypeQuery",e,t)},t.assertTSTypeReference=function(e,t){i("TSTypeReference",e,t)},t.assertTSUndefinedKeyword=function(e,t){i("TSUndefinedKeyword",e,t)},t.assertTSUnionType=function(e,t){i("TSUnionType",e,t)},t.assertTSUnknownKeyword=function(e,t){i("TSUnknownKeyword",e,t)},t.assertTSVoidKeyword=function(e,t){i("TSVoidKeyword",e,t)},t.assertTaggedTemplateExpression=function(e,t){i("TaggedTemplateExpression",e,t)},t.assertTemplateElement=function(e,t){i("TemplateElement",e,t)},t.assertTemplateLiteral=function(e,t){i("TemplateLiteral",e,t)},t.assertTerminatorless=function(e,t){i("Terminatorless",e,t)},t.assertThisExpression=function(e,t){i("ThisExpression",e,t)},t.assertThisTypeAnnotation=function(e,t){i("ThisTypeAnnotation",e,t)},t.assertThrowStatement=function(e,t){i("ThrowStatement",e,t)},t.assertTopicReference=function(e,t){i("TopicReference",e,t)},t.assertTryStatement=function(e,t){i("TryStatement",e,t)},t.assertTupleExpression=function(e,t){i("TupleExpression",e,t)},t.assertTupleTypeAnnotation=function(e,t){i("TupleTypeAnnotation",e,t)},t.assertTypeAlias=function(e,t){i("TypeAlias",e,t)},t.assertTypeAnnotation=function(e,t){i("TypeAnnotation",e,t)},t.assertTypeCastExpression=function(e,t){i("TypeCastExpression",e,t)},t.assertTypeParameter=function(e,t){i("TypeParameter",e,t)},t.assertTypeParameterDeclaration=function(e,t){i("TypeParameterDeclaration",e,t)},t.assertTypeParameterInstantiation=function(e,t){i("TypeParameterInstantiation",e,t)},t.assertTypeScript=function(e,t){i("TypeScript",e,t)},t.assertTypeofTypeAnnotation=function(e,t){i("TypeofTypeAnnotation",e,t)},t.assertUnaryExpression=function(e,t){i("UnaryExpression",e,t)},t.assertUnaryLike=function(e,t){i("UnaryLike",e,t)},t.assertUnionTypeAnnotation=function(e,t){i("UnionTypeAnnotation",e,t)},t.assertUpdateExpression=function(e,t){i("UpdateExpression",e,t)},t.assertUserWhitespacable=function(e,t){i("UserWhitespacable",e,t)},t.assertV8IntrinsicIdentifier=function(e,t){i("V8IntrinsicIdentifier",e,t)},t.assertVariableDeclaration=function(e,t){i("VariableDeclaration",e,t)},t.assertVariableDeclarator=function(e,t){i("VariableDeclarator",e,t)},t.assertVariance=function(e,t){i("Variance",e,t)},t.assertVoidTypeAnnotation=function(e,t){i("VoidTypeAnnotation",e,t)},t.assertWhile=function(e,t){i("While",e,t)},t.assertWhileStatement=function(e,t){i("WhileStatement",e,t)},t.assertWithStatement=function(e,t){i("WithStatement",e,t)},t.assertYieldExpression=function(e,t){i("YieldExpression",e,t)};var n=r(3828),s=r(3762);function i(e,t,r){if(!(0,n.default)(e,t,r))throw new Error(`Expected type "${e}" with option ${JSON.stringify(r)}, but instead got "${t.type}".`)}},2253:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getInclusionReasons=function(e,t,r){const a=r[e]||{};return Object.keys(t).reduce(((e,r)=>{const o=(0,i.getLowestImplementedVersion)(a,r),l=t[r];if(o){const t=(0,i.isUnreleasedVersion)(o,r);(0,i.isUnreleasedVersion)(l,r)||!t&&!n.lt(l.toString(),(0,i.semverify)(o))||(e[r]=(0,s.prettifyVersion)(l))}else e[r]=(0,s.prettifyVersion)(l);return e}),{})};var n=r(5345),s=r(228),i=r(6299)},2257:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.arrowFunctionToExpression=function({allowInsertArrow:e=!0,allowInsertArrowWithRest:t=e,noNewArrows:r=!(e=>null==(e=arguments[0])?void 0:e.specCompliant)()}={}){if(!this.isArrowFunctionExpression())throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");let n=this;var s;r||(n=null!=(s=n.ensureFunctionName(!1))?s:n);const{thisBinding:i,fnPath:a}=K(n,r,e,t);if(a.ensureBlock(),a.node.type="FunctionExpression",!r){const e=i?null:a.scope.generateUidIdentifier("arrowCheckId");return e&&a.parentPath.scope.push({id:e,init:S([])}),a.get("body").unshiftContainer("body",f(u(this.hub.addHelper("newArrowCheck"),[I(),h(e?e.name:i)]))),a.replaceWith(u(v(a.node,h("bind")),[e?h(e.name):I()])),a.get("callee.object")}return a},t.ensureBlock=function(){const e=this.get("body"),t=e.node;if(Array.isArray(e))throw new Error("Can't convert array path to a block statement");if(!t)throw new Error("Can't convert node without a body");if(e.isBlockStatement())return t;const r=[];let n,s,i="body";e.isStatement()?(s="body",n=0,r.push(e.node)):(i+=".body.0",this.isFunction()?(n="argument",r.push(P(e.node))):(n="expression",r.push(f(e.node)))),this.node.body=p(r);const o=this.get(i);return a.setup.call(e,o,s?o.node[s]:o.node,s,n),this.node},t.ensureFunctionName=function(e){if(this.node.id)return this;const t=M(this.node,this.parent);if(null==t)return this;let{name:r}=t;if(!e&&/[\uD800-\uDFFF]/.test(r))return null;if(r.startsWith("get ")||r.startsWith("set "))return null;r=_(r.replace(/[/ ]/g,"_"));const n=h(r);q(n,t.originalNode);const i={needsRename:!1,name:r},{scope:a}=this,o=a.getOwnBinding(r);if(o?"param"===o.kind&&(i.needsRename=!0):(a.parent.hasBinding(r)||a.hasGlobal(r))&&this.traverse(J,i),!i.needsRename)return this.node.id=n,a.getProgramParent().references[n.name]=!0,this;if(a.hasBinding(n.name)&&!a.hasGlobal(n.name))return a.rename(n.name),this.node.id=n,a.getProgramParent().references[n.name]=!0,this;if(!D(this.node))return null;const l=a.generateUidIdentifier(n.name),c=[];for(let e=0,t=function(e){const t=e.params.findIndex((e=>j(e)||B(e)));return-1===t?e.params.length:t}(this.node);e<t;e++)c.push(a.generateUidIdentifier("x"));const p=s.default.expression.ast` - (function (${l}) { - function ${n}(${c}) { - return ${L(l)}.apply(this, arguments); - } - - ${L(n)}.toString = function () { - return ${L(l)}.toString(); - } - - return ${L(n)}; - })(${N(this.node)}) - `;return this.replaceWith(p)[0].get("arguments.0")},t.splitExportDeclaration=function(){if(!this.isExportDeclaration()||this.isExportAllDeclaration())throw new Error("Only default and named export declarations can be split.");if(this.isExportNamedDeclaration()&&this.get("specifiers").length>0)throw new Error("It doesn't make sense to split exported specifiers.");const e=this.get("declaration");if(this.isExportDefaultDeclaration()){const t=e.isFunctionDeclaration()||e.isClassDeclaration(),r=e.isFunctionExpression()||e.isClassExpression(),n=e.isScope()?e.scope.parent:e.scope;let s=e.node.id,i=!1;s?r&&n.hasBinding(s.name)&&(i=!0,s=n.generateUidIdentifier(s.name)):(i=!0,s=n.generateUidIdentifier("default"),(t||r)&&(e.node.id=L(s)));const a=t?e.node:F("var",[R(L(s),e.node)]),o=U(null,[V(L(s),h("default"))]);return this.insertAfter(o),this.replaceWith(a),i&&n.registerDeclaration(this),this}if(this.get("specifiers").length>0)throw new Error("It doesn't make sense to split exported specifiers.");const t=e.getOuterBindingIdentifiers(),r=Object.keys(t).map((e=>V(h(e),h(e)))),n=U(null,r);return this.insertAfter(n),this.replaceWith(e.node),this},t.toComputedKey=function(){let e;if(this.isMemberExpression())e=this.node.property;else{if(!this.isProperty()&&!this.isMethod())throw new ReferenceError("todo");e=this.node.key}return this.node.computed||m(e)&&(e=C(e.name)),e},t.unwrapFunctionEnvironment=function(){if(!this.isArrowFunctionExpression()&&!this.isFunctionExpression()&&!this.isFunctionDeclaration())throw this.buildCodeFrameError("Can only unwrap the environment of a function.");K(this)};var n=r(2352),s=r(2485),i=r(4950),a=r(9578);const{arrowFunctionExpression:o,assignmentExpression:l,binaryExpression:c,blockStatement:p,callExpression:u,conditionalExpression:d,expressionStatement:f,identifier:h,isIdentifier:m,jsxIdentifier:y,logicalExpression:g,LOGICAL_OPERATORS:b,memberExpression:v,metaProperty:T,numericLiteral:x,objectExpression:S,restElement:E,returnStatement:P,sequenceExpression:A,spreadElement:w,stringLiteral:C,super:O,thisExpression:I,toExpression:N,unaryExpression:k,toBindingIdentifierName:_,isFunction:D,isAssignmentPattern:j,isRestElement:B,getFunctionName:M,cloneNode:L,variableDeclaration:F,variableDeclarator:R,exportNamedDeclaration:U,exportSpecifier:V,inherits:q}=n;t.arrowFunctionToShadowed=function(){this.isArrowFunctionExpression()&&this.arrowFunctionToExpression()};const W=(0,i.environmentVisitor)({CallExpression(e,{allSuperCalls:t}){e.get("callee").isSuper()&&t.push(e)}});function K(e,t=!0,r=!0,n=!0){let s,i=e.findParent((e=>e.isArrowFunctionExpression()?(null!=s||(s=e),!1):e.isFunction()||e.isProgram()||e.isClassProperty({static:!1})||e.isClassPrivateProperty({static:!1})));const a=i.isClassMethod({kind:"constructor"});if(i.isClassProperty()||i.isClassPrivateProperty())if(s)i=s;else{if(!r)throw e.buildCodeFrameError("Unable to transform arrow inside class property");e.replaceWith(u(o([],N(e.node)),[])),i=e.get("callee"),e=i.get("body")}const{thisPaths:p,argumentsPaths:f,newTargetPaths:m,superProps:S,superCalls:P}=function(e){const t=[],r=[],n=[],s=[],i=[];return e.traverse(Y,{thisPaths:t,argumentsPaths:r,newTargetPaths:n,superProps:s,superCalls:i}),{thisPaths:t,argumentsPaths:r,newTargetPaths:n,superProps:s,superCalls:i}}(e);if(a&&P.length>0){if(!r)throw P[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', it's not possible to compile `super()` in an arrow function without compiling classes.\nPlease add '@babel/plugin-transform-classes' to your Babel configuration.");if(!n)throw P[0].buildCodeFrameError("When using '@babel/plugin-transform-parameters', it's not possible to compile `super()` in an arrow function with default or rest parameters without compiling classes.\nPlease add '@babel/plugin-transform-classes' to your Babel configuration.");const e=[];i.traverse(W,{allSuperCalls:e});const t=function(e){return H(e,"supercall",(()=>{const t=e.scope.generateUidIdentifier("args");return o([E(t)],u(O(),[w(h(t.name))]))}))}(i);e.forEach((e=>{const r=h(t);r.loc=e.node.callee.loc,e.get("callee").replaceWith(r)}))}if(f.length>0){const e=H(i,"arguments",(()=>{const e=()=>h("arguments");return i.scope.path.isProgram()?d(c("===",k("typeof",e()),C("undefined")),i.scope.buildUndefinedNode(),e()):e()}));f.forEach((t=>{const r=h(e);r.loc=t.node.loc,t.replaceWith(r)}))}if(m.length>0){const e=H(i,"newtarget",(()=>T(h("new"),h("target"))));m.forEach((t=>{const r=h(e);r.loc=t.node.loc,t.replaceWith(r)}))}if(S.length>0){if(!r)throw S[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', it's not possible to compile `super.prop` in an arrow function without compiling classes.\nPlease add '@babel/plugin-transform-classes' to your Babel configuration.");S.reduce(((e,t)=>e.concat(function(e){if(e.parentPath.isAssignmentExpression()&&"="!==e.parentPath.node.operator){const r=e.parentPath,n=r.node.operator.slice(0,-1),s=r.node.right,i=function(e){return b.includes(e)}(n);if(e.node.computed){const a=e.scope.generateDeclaredUidIdentifier("tmp"),o=e.node.object,c=e.node.property;r.get("left").replaceWith(v(o,l("=",a,c),!0)),r.get("right").replaceWith(t(i?"=":n,v(o,h(a.name),!0),s))}else{const a=e.node.object,o=e.node.property;r.get("left").replaceWith(v(a,o)),r.get("right").replaceWith(t(i?"=":n,v(a,h(o.name)),s))}return i?r.replaceWith(g(n,r.node.left,r.node.right)):r.node.operator="=",[r.get("left"),r.get("right").get("left")]}if(e.parentPath.isUpdateExpression()){const t=e.parentPath,r=e.scope.generateDeclaredUidIdentifier("tmp"),n=e.node.computed?e.scope.generateDeclaredUidIdentifier("prop"):null,s=[l("=",r,v(e.node.object,n?l("=",n,e.node.property):e.node.property,e.node.computed)),l("=",v(e.node.object,n?h(n.name):e.node.property,e.node.computed),c(e.parentPath.node.operator[0],h(r.name),x(1)))];return e.parentPath.node.prefix||s.push(h(r.name)),t.replaceWith(A(s)),[t.get("expressions.0.right"),t.get("expressions.1.left")]}return[e];function t(e,t,r){return"="===e?l("=",t,r):c(e,t,r)}}(t))),[]).forEach((e=>{const t=e.node.computed?"":e.get("property").node.name,r=e.parentPath,n=r.isAssignmentExpression({left:e.node}),s=r.isCallExpression({callee:e.node}),a=r.isTaggedTemplateExpression({tag:e.node}),c=function(e,t,r){return H(e,`superprop_${t?"set":"get"}:${r||""}`,(()=>{const n=[];let s;if(r)s=v(O(),h(r));else{const t=e.scope.generateUidIdentifier("prop");n.unshift(t),s=v(O(),h(t.name),!0)}if(t){const t=e.scope.generateUidIdentifier("value");n.push(t),s=l("=",s,h(t.name))}return o(n,s)}))}(i,n,t),d=[];if(e.node.computed&&d.push(e.get("property").node),n){const e=r.node.right;d.push(e)}const f=u(h(c),d);s?(r.unshiftContainer("arguments",I()),e.replaceWith(v(f,h("call"))),p.push(r.get("arguments.0"))):n?r.replaceWith(f):a?(e.replaceWith(u(v(f,h("bind"),!1),[I()])),p.push(e.get("arguments.0"))):e.replaceWith(f)}))}let _;return(p.length>0||!t)&&(_=function(e,t){return H(e,"this",(r=>{if(!t||!$(e))return I();e.traverse(G,{supers:new WeakSet,thisBinding:r})}))}(i,a),(t||a&&$(i))&&(p.forEach((e=>{const t=e.isJSX()?y(_):h(_);t.loc=e.node.loc,e.replaceWith(t)})),t||(_=null))),{thisBinding:_,fnPath:e}}function $(e){return e.isClassMethod()&&!!e.parentPath.parentPath.node.superClass}const G=(0,i.environmentVisitor)({CallExpression(e,{supers:t,thisBinding:r}){e.get("callee").isSuper()&&(t.has(e.node)||(t.add(e.node),e.replaceWithMultiple([e.node,l("=",h(r),h("this"))])))}});function H(e,t,r){const n="binding:"+t;let s=e.getData(n);if(!s){const i=e.scope.generateUidIdentifier(t);s=i.name,e.setData(n,s),e.scope.push({id:i,init:r(s)})}return s}const Y=(0,i.environmentVisitor)({ThisExpression(e,{thisPaths:t}){t.push(e)},JSXIdentifier(e,{thisPaths:t}){"this"===e.node.name&&(e.parentPath.isJSXMemberExpression({object:e.node})||e.parentPath.isJSXOpeningElement({name:e.node}))&&t.push(e)},CallExpression(e,{superCalls:t}){e.get("callee").isSuper()&&t.push(e)},MemberExpression(e,{superProps:t}){e.get("object").isSuper()&&t.push(e)},Identifier(e,{argumentsPaths:t}){if(!e.isReferencedIdentifier({name:"arguments"}))return;let r=e.scope;do{if(r.hasOwnBinding("arguments"))return void r.rename("arguments");if(r.path.isFunction()&&!r.path.isArrowFunctionExpression())break}while(r=r.parent);t.push(e)},MetaProperty(e,{newTargetPaths:t}){e.get("meta").isIdentifier({name:"new"})&&e.get("property").isIdentifier({name:"target"})&&t.push(e)}}),J={"ReferencedIdentifier|BindingIdentifier"(e,t){e.node.name===t.name&&(t.needsRename=!0,e.stop())},Scope(e,t){e.scope.hasOwnBinding(t.name)&&e.skip()}}},2259:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AnyTypeAnnotation=function(){this.word("any")},t.ArrayTypeAnnotation=function(e){this.print(e.elementType,!0),this.tokenChar(91),this.tokenChar(93)},t.BooleanLiteralTypeAnnotation=function(e){this.word(e.value?"true":"false")},t.BooleanTypeAnnotation=function(){this.word("boolean")},t.DeclareClass=function(e,t){o(t)||(this.word("declare"),this.space()),this.word("class"),this.space(),this._interfaceish(e)},t.DeclareExportAllDeclaration=function(e){this.word("declare"),this.space(),s.ExportAllDeclaration.call(this,e)},t.DeclareExportDeclaration=function(e){this.word("declare"),this.space(),this.word("export"),this.space(),e.default&&(this.word("default"),this.space()),d.call(this,e)},t.DeclareFunction=function(e,t){o(t)||(this.word("declare"),this.space()),this.word("function"),this.space(),this.print(e.id),this.print(e.id.typeAnnotation.typeAnnotation),e.predicate&&(this.space(),this.print(e.predicate)),this.semicolon()},t.DeclareInterface=function(e){this.word("declare"),this.space(),this.InterfaceDeclaration(e)},t.DeclareModule=function(e){this.word("declare"),this.space(),this.word("module"),this.space(),this.print(e.id),this.space(),this.print(e.body)},t.DeclareModuleExports=function(e){this.word("declare"),this.space(),this.word("module"),this.tokenChar(46),this.word("exports"),this.print(e.typeAnnotation)},t.DeclareOpaqueType=function(e,t){o(t)||(this.word("declare"),this.space()),this.OpaqueType(e)},t.DeclareTypeAlias=function(e){this.word("declare"),this.space(),this.TypeAlias(e)},t.DeclareVariable=function(e,t){o(t)||(this.word("declare"),this.space()),this.word("var"),this.space(),this.print(e.id),this.print(e.id.typeAnnotation),this.semicolon()},t.DeclaredPredicate=function(e){this.tokenChar(37),this.word("checks"),this.tokenChar(40),this.print(e.value),this.tokenChar(41)},t.EmptyTypeAnnotation=function(){this.word("empty")},t.EnumBooleanBody=function(e){const{explicitType:t}=e;c(this,"boolean",t),p(this,e)},t.EnumBooleanMember=function(e){u(this,e)},t.EnumDeclaration=function(e){const{id:t,body:r}=e;this.word("enum"),this.space(),this.print(t),this.print(r)},t.EnumDefaultedMember=function(e){const{id:t}=e;this.print(t),this.tokenChar(44)},t.EnumNumberBody=function(e){const{explicitType:t}=e;c(this,"number",t),p(this,e)},t.EnumNumberMember=function(e){u(this,e)},t.EnumStringBody=function(e){const{explicitType:t}=e;c(this,"string",t),p(this,e)},t.EnumStringMember=function(e){u(this,e)},t.EnumSymbolBody=function(e){c(this,"symbol",!0),p(this,e)},t.ExistsTypeAnnotation=function(){this.tokenChar(42)},t.FunctionTypeAnnotation=function(e,t){this.print(e.typeParameters),this.tokenChar(40),e.this&&(this.word("this"),this.tokenChar(58),this.space(),this.print(e.this.typeAnnotation),(e.params.length||e.rest)&&(this.tokenChar(44),this.space())),this.printList(e.params),e.rest&&(e.params.length&&(this.tokenChar(44),this.space()),this.token("..."),this.print(e.rest)),this.tokenChar(41);const r=null==t?void 0:t.type;null!=r&&("ObjectTypeCallProperty"===r||"ObjectTypeInternalSlot"===r||"DeclareFunction"===r||"ObjectTypeProperty"===r&&t.method)?this.tokenChar(58):(this.space(),this.token("=>")),this.space(),this.print(e.returnType)},t.FunctionTypeParam=function(e){this.print(e.name),e.optional&&this.tokenChar(63),e.name&&(this.tokenChar(58),this.space()),this.print(e.typeAnnotation)},t.IndexedAccessType=function(e){this.print(e.objectType,!0),this.tokenChar(91),this.print(e.indexType),this.tokenChar(93)},t.InferredPredicate=function(){this.tokenChar(37),this.word("checks")},t.InterfaceDeclaration=function(e){this.word("interface"),this.space(),this._interfaceish(e)},t.GenericTypeAnnotation=t.ClassImplements=t.InterfaceExtends=function(e){this.print(e.id),this.print(e.typeParameters,!0)},t.InterfaceTypeAnnotation=function(e){var t;this.word("interface"),null!=(t=e.extends)&&t.length&&(this.space(),this.word("extends"),this.space(),this.printList(e.extends)),this.space(),this.print(e.body)},t.IntersectionTypeAnnotation=function(e){this.printJoin(e.types,void 0,void 0,f)},t.MixedTypeAnnotation=function(){this.word("mixed")},t.NullLiteralTypeAnnotation=function(){this.word("null")},t.NullableTypeAnnotation=function(e){this.tokenChar(63),this.print(e.typeAnnotation)},Object.defineProperty(t,"NumberLiteralTypeAnnotation",{enumerable:!0,get:function(){return a.NumericLiteral}}),t.NumberTypeAnnotation=function(){this.word("number")},t.ObjectTypeAnnotation=function(e){e.exact?this.token("{|"):this.tokenChar(123);const t=[...e.properties,...e.callProperties||[],...e.indexers||[],...e.internalSlots||[]];t.length&&(this.newline(),this.space(),this.printJoin(t,!0,!0,void 0,void 0,(function(e){if(e&&!t[0])return 1}),(()=>{(1!==t.length||e.inexact)&&(this.tokenChar(44),this.space())})),this.space()),e.inexact&&(this.indent(),this.token("..."),t.length&&this.newline(),this.dedent()),e.exact?this.token("|}"):this.tokenChar(125)},t.ObjectTypeCallProperty=function(e){e.static&&(this.word("static"),this.space()),this.print(e.value)},t.ObjectTypeIndexer=function(e){e.static&&(this.word("static"),this.space()),this._variance(e),this.tokenChar(91),e.id&&(this.print(e.id),this.tokenChar(58),this.space()),this.print(e.key),this.tokenChar(93),this.tokenChar(58),this.space(),this.print(e.value)},t.ObjectTypeInternalSlot=function(e){e.static&&(this.word("static"),this.space()),this.tokenChar(91),this.tokenChar(91),this.print(e.id),this.tokenChar(93),this.tokenChar(93),e.optional&&this.tokenChar(63),e.method||(this.tokenChar(58),this.space()),this.print(e.value)},t.ObjectTypeProperty=function(e){e.proto&&(this.word("proto"),this.space()),e.static&&(this.word("static"),this.space()),"get"!==e.kind&&"set"!==e.kind||(this.word(e.kind),this.space()),this._variance(e),this.print(e.key),e.optional&&this.tokenChar(63),e.method||(this.tokenChar(58),this.space()),this.print(e.value)},t.ObjectTypeSpreadProperty=function(e){this.token("..."),this.print(e.argument)},t.OpaqueType=function(e){this.word("opaque"),this.space(),this.word("type"),this.space(),this.print(e.id),this.print(e.typeParameters),e.supertype&&(this.tokenChar(58),this.space(),this.print(e.supertype)),e.impltype&&(this.space(),this.tokenChar(61),this.space(),this.print(e.impltype)),this.semicolon()},t.OptionalIndexedAccessType=function(e){this.print(e.objectType),e.optional&&this.token("?."),this.tokenChar(91),this.print(e.indexType),this.tokenChar(93)},t.QualifiedTypeIdentifier=function(e){this.print(e.qualification),this.tokenChar(46),this.print(e.id)},Object.defineProperty(t,"StringLiteralTypeAnnotation",{enumerable:!0,get:function(){return a.StringLiteral}}),t.StringTypeAnnotation=function(){this.word("string")},t.SymbolTypeAnnotation=function(){this.word("symbol")},t.ThisTypeAnnotation=function(){this.word("this")},t.TupleTypeAnnotation=function(e){this.tokenChar(91),this.printList(e.types),this.tokenChar(93)},t.TypeAlias=function(e){this.word("type"),this.space(),this.print(e.id),this.print(e.typeParameters),this.space(),this.tokenChar(61),this.space(),this.print(e.right),this.semicolon()},t.TypeAnnotation=function(e,t){this.tokenChar(58),this.space(),"ArrowFunctionExpression"===t.type?this.tokenContext|=i.TokenContext.arrowFlowReturnType:e.optional&&this.tokenChar(63),this.print(e.typeAnnotation)},t.TypeCastExpression=function(e){this.tokenChar(40),this.print(e.expression),this.print(e.typeAnnotation),this.tokenChar(41)},t.TypeParameter=function(e){this._variance(e),this.word(e.name),e.bound&&this.print(e.bound),e.default&&(this.space(),this.tokenChar(61),this.space(),this.print(e.default))},t.TypeParameterDeclaration=t.TypeParameterInstantiation=function(e){this.tokenChar(60),this.printList(e.params),this.tokenChar(62)},t.TypeofTypeAnnotation=function(e){this.word("typeof"),this.space(),this.print(e.argument)},t.UnionTypeAnnotation=function(e){this.printJoin(e.types,void 0,void 0,h)},t.Variance=function(e){"plus"===e.kind?this.tokenChar(43):this.tokenChar(45)},t.VoidTypeAnnotation=function(){this.word("void")},t._interfaceish=function(e){var t,r,n;(this.print(e.id),this.print(e.typeParameters),null!=(t=e.extends)&&t.length&&(this.space(),this.word("extends"),this.space(),this.printList(e.extends)),"DeclareClass"===e.type)&&(null!=(r=e.mixins)&&r.length&&(this.space(),this.word("mixins"),this.space(),this.printList(e.mixins)),null!=(n=e.implements)&&n.length&&(this.space(),this.word("implements"),this.space(),this.printList(e.implements)));this.space(),this.print(e.body)},t._variance=function(e){var t;const r=null==(t=e.variance)?void 0:t.kind;null!=r&&("plus"===r?this.tokenChar(43):"minus"===r&&this.tokenChar(45))};var n=r(2352),s=r(9638),i=r(1373),a=r(7942);const{isDeclareExportDeclaration:o,isStatement:l}=n;function c(e,t,r){r&&(e.space(),e.word("of"),e.space(),e.word(t)),e.space()}function p(e,t){const{members:r}=t;e.token("{"),e.indent(),e.newline();for(const t of r)e.print(t),e.newline();t.hasUnknownMembers&&(e.token("..."),e.newline()),e.dedent(),e.token("}")}function u(e,t){e.print(t.id),e.space(),e.token("="),e.space(),e.print(t.init),e.token(",")}function d(e){if(e.declaration){const t=e.declaration;this.print(t),l(t)||this.semicolon()}else this.tokenChar(123),e.specifiers.length&&(this.space(),this.printList(e.specifiers),this.space()),this.tokenChar(125),e.source&&(this.space(),this.word("from"),this.space(),this.print(e.source)),this.semicolon()}function f(e){this.space(),this.token("&",!1,e),this.space()}function h(e){this.space(),this.token("|",!1,e),this.space()}},2264:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.traverseNode=function(e,t,r,s,a,o,l){const c=i[e.type];if(!c)return!1;const p=new n.default(r,t,s,a);if(l)return(null==o||!o[a.parentKey])&&p.visitQueue([a]);for(const t of c)if((null==o||!o[t])&&p.visit(e,t))return!0;return!1};var n=r(1602),s=r(2352);const{VISITOR_KEYS:i}=s},2299:(e,t,r)=>{"use strict";function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,a,o=[],l=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(n=i.call(r)).done)&&(o.push(n.value),o.length!==t);l=!0);}catch(e){c=!0,s=e}finally{try{if(!l&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw s}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return s(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}var a=void 0!==/a/g.flags,o=function(e){var t=[];return e.forEach((function(e){return t.push(e)})),t},l=function(e){var t=[];return e.forEach((function(e,r){return t.push([r,e])})),t},c=Object.is?Object.is:r(7653),p=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols:function(){return[]},u=Number.isNaN?Number.isNaN:r(4133);function d(e){return e.call.bind(e)}var f=d(Object.prototype.hasOwnProperty),h=d(Object.prototype.propertyIsEnumerable),m=d(Object.prototype.toString),y=r(537).types,g=y.isAnyArrayBuffer,b=y.isArrayBufferView,v=y.isDate,T=y.isMap,x=y.isRegExp,S=y.isSet,E=y.isNativeError,P=y.isBoxedPrimitive,A=y.isNumberObject,w=y.isStringObject,C=y.isBooleanObject,O=y.isBigIntObject,I=y.isSymbolObject,N=y.isFloat32Array,k=y.isFloat64Array;function _(e){if(0===e.length||e.length>10)return!0;for(var t=0;t<e.length;t++){var r=e.charCodeAt(t);if(r<48||r>57)return!0}return 10===e.length&&e>=Math.pow(2,32)}function D(e){return Object.keys(e).filter(_).concat(p(e).filter(Object.prototype.propertyIsEnumerable.bind(e)))}function j(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,s=0,i=Math.min(r,n);s<i;++s)if(e[s]!==t[s]){r=e[s],n=t[s];break}return r<n?-1:n<r?1:0}function B(e,t,r,n){if(e===t)return 0!==e||!r||c(e,t);if(r){if("object"!==i(e))return"number"==typeof e&&u(e)&&u(t);if("object"!==i(t)||null===e||null===t)return!1;if(Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1}else{if(null===e||"object"!==i(e))return(null===t||"object"!==i(t))&&e==t;if(null===t||"object"!==i(t))return!1}var s,o,l,p,d=m(e);if(d!==m(t))return!1;if(Array.isArray(e)){if(e.length!==t.length)return!1;var f=D(e),h=D(t);return f.length===h.length&&L(e,t,r,n,1,f)}if("[object Object]"===d&&(!T(e)&&T(t)||!S(e)&&S(t)))return!1;if(v(e)){if(!v(t)||Date.prototype.getTime.call(e)!==Date.prototype.getTime.call(t))return!1}else if(x(e)){if(!x(t)||(l=e,p=t,!(a?l.source===p.source&&l.flags===p.flags:RegExp.prototype.toString.call(l)===RegExp.prototype.toString.call(p))))return!1}else if(E(e)||e instanceof Error){if(e.message!==t.message||e.name!==t.name)return!1}else{if(b(e)){if(r||!N(e)&&!k(e)){if(!function(e,t){return e.byteLength===t.byteLength&&0===j(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}(e,t))return!1}else if(!function(e,t){if(e.byteLength!==t.byteLength)return!1;for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e,t))return!1;var y=D(e),_=D(t);return y.length===_.length&&L(e,t,r,n,0,y)}if(S(e))return!(!S(t)||e.size!==t.size)&&L(e,t,r,n,2);if(T(e))return!(!T(t)||e.size!==t.size)&&L(e,t,r,n,3);if(g(e)){if(o=t,(s=e).byteLength!==o.byteLength||0!==j(new Uint8Array(s),new Uint8Array(o)))return!1}else if(P(e)&&!function(e,t){return A(e)?A(t)&&c(Number.prototype.valueOf.call(e),Number.prototype.valueOf.call(t)):w(e)?w(t)&&String.prototype.valueOf.call(e)===String.prototype.valueOf.call(t):C(e)?C(t)&&Boolean.prototype.valueOf.call(e)===Boolean.prototype.valueOf.call(t):O(e)?O(t)&&BigInt.prototype.valueOf.call(e)===BigInt.prototype.valueOf.call(t):I(t)&&Symbol.prototype.valueOf.call(e)===Symbol.prototype.valueOf.call(t)}(e,t))return!1}return L(e,t,r,n,0)}function M(e,t){return t.filter((function(t){return h(e,t)}))}function L(e,t,r,s,a,c){if(5===arguments.length){c=Object.keys(e);var u=Object.keys(t);if(c.length!==u.length)return!1}for(var d=0;d<c.length;d++)if(!f(t,c[d]))return!1;if(r&&5===arguments.length){var m=p(e);if(0!==m.length){var y=0;for(d=0;d<m.length;d++){var g=m[d];if(h(e,g)){if(!h(t,g))return!1;c.push(g),y++}else if(h(t,g))return!1}var b=p(t);if(m.length!==b.length&&M(t,b).length!==y)return!1}else{var v=p(t);if(0!==v.length&&0!==M(t,v).length)return!1}}if(0===c.length&&(0===a||1===a&&0===e.length||0===e.size))return!0;if(void 0===s)s={val1:new Map,val2:new Map,position:0};else{var T=s.val1.get(e);if(void 0!==T){var x=s.val2.get(t);if(void 0!==x)return T===x}s.position++}s.val1.set(e,s.position),s.val2.set(t,s.position);var S=function(e,t,r,s,a,c){var p=0;if(2===c){if(!function(e,t,r,n){for(var s=null,a=o(e),l=0;l<a.length;l++){var c=a[l];if("object"===i(c)&&null!==c)null===s&&(s=new Set),s.add(c);else if(!t.has(c)){if(r)return!1;if(!U(e,t,c))return!1;null===s&&(s=new Set),s.add(c)}}if(null!==s){for(var p=o(t),u=0;u<p.length;u++){var d=p[u];if("object"===i(d)&&null!==d){if(!F(s,d,r,n))return!1}else if(!r&&!e.has(d)&&!F(s,d,r,n))return!1}return 0===s.size}return!0}(e,t,r,a))return!1}else if(3===c){if(!function(e,t,r,s){for(var a=null,o=l(e),c=0;c<o.length;c++){var p=n(o[c],2),u=p[0],d=p[1];if("object"===i(u)&&null!==u)null===a&&(a=new Set),a.add(u);else{var f=t.get(u);if(void 0===f&&!t.has(u)||!B(d,f,r,s)){if(r)return!1;if(!V(e,t,u,d,s))return!1;null===a&&(a=new Set),a.add(u)}}}if(null!==a){for(var h=l(t),m=0;m<h.length;m++){var y=n(h[m],2),g=y[0],b=y[1];if("object"===i(g)&&null!==g){if(!q(a,e,g,b,r,s))return!1}else if(!(r||e.has(g)&&B(e.get(g),b,!1,s)||q(a,e,g,b,!1,s)))return!1}return 0===a.size}return!0}(e,t,r,a))return!1}else if(1===c)for(;p<e.length;p++){if(!f(e,p)){if(f(t,p))return!1;for(var u=Object.keys(e);p<u.length;p++){var d=u[p];if(!f(t,d)||!B(e[d],t[d],r,a))return!1}return u.length===Object.keys(t).length}if(!f(t,p)||!B(e[p],t[p],r,a))return!1}for(p=0;p<s.length;p++){var h=s[p];if(!B(e[h],t[h],r,a))return!1}return!0}(e,t,r,c,s,a);return s.val1.delete(e),s.val2.delete(t),S}function F(e,t,r,n){for(var s=o(e),i=0;i<s.length;i++){var a=s[i];if(B(t,a,r,n))return e.delete(a),!0}return!1}function R(e){switch(i(e)){case"undefined":return null;case"object":return;case"symbol":return!1;case"string":e=+e;case"number":if(u(e))return!1}return!0}function U(e,t,r){var n=R(r);return null!=n?n:t.has(n)&&!e.has(n)}function V(e,t,r,n,s){var i=R(r);if(null!=i)return i;var a=t.get(i);return!(void 0===a&&!t.has(i)||!B(n,a,!1,s))&&!e.has(i)&&B(n,a,!1,s)}function q(e,t,r,n,s,i){for(var a=o(e),l=0;l<a.length;l++){var c=a[l];if(B(r,c,s,i)&&B(n,t.get(c),s,i))return e.delete(c),!0}return!1}e.exports={isDeepEqual:function(e,t){return B(e,t,!1)},isDeepStrictEqual:function(e,t){return B(e,t,!0)}}},2315:(e,t)=>{"use strict";function r(e,t){if(null!==e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e)){n=new Array(e.length),t.set(e,n);for(let s=0;s<e.length;s++)n[s]="object"!=typeof e[s]?e[s]:r(e[s],t)}else{n={},t.set(e,n);const s=Object.keys(e);for(let i=0;i<s.length;i++){const a=s[i];n[a]="object"!=typeof e[a]?e[a]:r(e[a],t)}}return n}return e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return"object"!=typeof e?e:r(e,new Map)}},2352:(e,t,r)=>{"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0});var s={react:!0,assertNode:!0,createTypeAnnotationBasedOnTypeof:!0,createUnionTypeAnnotation:!0,createFlowUnionType:!0,createTSUnionType:!0,cloneNode:!0,clone:!0,cloneDeep:!0,cloneDeepWithoutLoc:!0,cloneWithoutLoc:!0,addComment:!0,addComments:!0,inheritInnerComments:!0,inheritLeadingComments:!0,inheritsComments:!0,inheritTrailingComments:!0,removeComments:!0,ensureBlock:!0,toBindingIdentifierName:!0,toBlock:!0,toComputedKey:!0,toExpression:!0,toIdentifier:!0,toKeyAlias:!0,toStatement:!0,valueToNode:!0,appendToMemberExpression:!0,inherits:!0,prependToMemberExpression:!0,removeProperties:!0,removePropertiesDeep:!0,removeTypeDuplicates:!0,getAssignmentIdentifiers:!0,getBindingIdentifiers:!0,getOuterBindingIdentifiers:!0,getFunctionName:!0,traverse:!0,traverseFast:!0,shallowEqual:!0,is:!0,isBinding:!0,isBlockScoped:!0,isImmutable:!0,isLet:!0,isNode:!0,isNodesEquivalent:!0,isPlaceholderType:!0,isReferenced:!0,isScope:!0,isSpecifierDefault:!0,isType:!0,isValidES3Identifier:!0,isValidIdentifier:!0,isVar:!0,matchesPattern:!0,validate:!0,buildMatchMemberExpression:!0,__internal__deprecationWarning:!0};Object.defineProperty(t,"__internal__deprecationWarning",{enumerable:!0,get:function(){return ge.default}}),Object.defineProperty(t,"addComment",{enumerable:!0,get:function(){return T.default}}),Object.defineProperty(t,"addComments",{enumerable:!0,get:function(){return x.default}}),Object.defineProperty(t,"appendToMemberExpression",{enumerable:!0,get:function(){return R.default}}),Object.defineProperty(t,"assertNode",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(t,"buildMatchMemberExpression",{enumerable:!0,get:function(){return me.default}}),Object.defineProperty(t,"clone",{enumerable:!0,get:function(){return y.default}}),Object.defineProperty(t,"cloneDeep",{enumerable:!0,get:function(){return g.default}}),Object.defineProperty(t,"cloneDeepWithoutLoc",{enumerable:!0,get:function(){return b.default}}),Object.defineProperty(t,"cloneNode",{enumerable:!0,get:function(){return m.default}}),Object.defineProperty(t,"cloneWithoutLoc",{enumerable:!0,get:function(){return v.default}}),Object.defineProperty(t,"createFlowUnionType",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"createTSUnionType",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(t,"createTypeAnnotationBasedOnTypeof",{enumerable:!0,get:function(){return p.default}}),Object.defineProperty(t,"createUnionTypeAnnotation",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(t,"ensureBlock",{enumerable:!0,get:function(){return I.default}}),Object.defineProperty(t,"getAssignmentIdentifiers",{enumerable:!0,get:function(){return $.default}}),Object.defineProperty(t,"getBindingIdentifiers",{enumerable:!0,get:function(){return G.default}}),Object.defineProperty(t,"getFunctionName",{enumerable:!0,get:function(){return Y.default}}),Object.defineProperty(t,"getOuterBindingIdentifiers",{enumerable:!0,get:function(){return H.default}}),Object.defineProperty(t,"inheritInnerComments",{enumerable:!0,get:function(){return S.default}}),Object.defineProperty(t,"inheritLeadingComments",{enumerable:!0,get:function(){return E.default}}),Object.defineProperty(t,"inheritTrailingComments",{enumerable:!0,get:function(){return A.default}}),Object.defineProperty(t,"inherits",{enumerable:!0,get:function(){return U.default}}),Object.defineProperty(t,"inheritsComments",{enumerable:!0,get:function(){return P.default}}),Object.defineProperty(t,"is",{enumerable:!0,get:function(){return Q.default}}),Object.defineProperty(t,"isBinding",{enumerable:!0,get:function(){return Z.default}}),Object.defineProperty(t,"isBlockScoped",{enumerable:!0,get:function(){return ee.default}}),Object.defineProperty(t,"isImmutable",{enumerable:!0,get:function(){return te.default}}),Object.defineProperty(t,"isLet",{enumerable:!0,get:function(){return re.default}}),Object.defineProperty(t,"isNode",{enumerable:!0,get:function(){return ne.default}}),Object.defineProperty(t,"isNodesEquivalent",{enumerable:!0,get:function(){return se.default}}),Object.defineProperty(t,"isPlaceholderType",{enumerable:!0,get:function(){return ie.default}}),Object.defineProperty(t,"isReferenced",{enumerable:!0,get:function(){return ae.default}}),Object.defineProperty(t,"isScope",{enumerable:!0,get:function(){return oe.default}}),Object.defineProperty(t,"isSpecifierDefault",{enumerable:!0,get:function(){return le.default}}),Object.defineProperty(t,"isType",{enumerable:!0,get:function(){return ce.default}}),Object.defineProperty(t,"isValidES3Identifier",{enumerable:!0,get:function(){return pe.default}}),Object.defineProperty(t,"isValidIdentifier",{enumerable:!0,get:function(){return ue.default}}),Object.defineProperty(t,"isVar",{enumerable:!0,get:function(){return de.default}}),Object.defineProperty(t,"matchesPattern",{enumerable:!0,get:function(){return fe.default}}),Object.defineProperty(t,"prependToMemberExpression",{enumerable:!0,get:function(){return V.default}}),t.react=void 0,Object.defineProperty(t,"removeComments",{enumerable:!0,get:function(){return w.default}}),Object.defineProperty(t,"removeProperties",{enumerable:!0,get:function(){return q.default}}),Object.defineProperty(t,"removePropertiesDeep",{enumerable:!0,get:function(){return W.default}}),Object.defineProperty(t,"removeTypeDuplicates",{enumerable:!0,get:function(){return K.default}}),Object.defineProperty(t,"shallowEqual",{enumerable:!0,get:function(){return X.default}}),Object.defineProperty(t,"toBindingIdentifierName",{enumerable:!0,get:function(){return N.default}}),Object.defineProperty(t,"toBlock",{enumerable:!0,get:function(){return k.default}}),Object.defineProperty(t,"toComputedKey",{enumerable:!0,get:function(){return _.default}}),Object.defineProperty(t,"toExpression",{enumerable:!0,get:function(){return D.default}}),Object.defineProperty(t,"toIdentifier",{enumerable:!0,get:function(){return j.default}}),Object.defineProperty(t,"toKeyAlias",{enumerable:!0,get:function(){return B.default}}),Object.defineProperty(t,"toStatement",{enumerable:!0,get:function(){return M.default}}),Object.defineProperty(t,"traverse",{enumerable:!0,get:function(){return J.default}}),Object.defineProperty(t,"traverseFast",{enumerable:!0,get:function(){return z.default}}),Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return he.default}}),Object.defineProperty(t,"valueToNode",{enumerable:!0,get:function(){return L.default}});var i=r(5682),a=r(5004),o=r(9018),l=r(4568),c=r(2246);Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===c[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}}))}));var p=r(5958),u=r(1009),d=r(6049),f=r(985);Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===f[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return f[e]}}))}));var h=r(8079);Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===h[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return h[e]}}))}));var m=r(5279),y=r(2107),g=r(245),b=r(5299),v=r(2425),T=r(6211),x=r(2598),S=r(7932),E=r(5766),P=r(8125),A=r(5586),w=r(3437),C=r(7980);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var O=r(3422);Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===O[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return O[e]}}))}));var I=r(7931),N=r(2234),k=r(5010),_=r(3017),D=r(6133),j=r(6744),B=r(2402),M=r(9198),L=r(4544),F=r(9793);Object.keys(F).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===F[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return F[e]}}))}));var R=r(4001),U=r(9564),V=r(6219),q=r(5333),W=r(7639),K=r(5237),$=r(1343),G=r(329),H=r(9420),Y=r(5109),J=r(3357);Object.keys(J).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===J[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return J[e]}}))}));var z=r(8943),X=r(6616),Q=r(3828),Z=r(2687),ee=r(9127),te=r(9722),re=r(3847),ne=r(3908),se=r(7003),ie=r(3571),ae=r(7591),oe=r(9246),le=r(2457),ce=r(4460),pe=r(1384),ue=r(983),de=r(499),fe=r(4965),he=r(7446),me=r(3937),ye=r(8960);Object.keys(ye).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(s,e)||e in t&&t[e]===ye[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return ye[e]}}))}));var ge=r(3762),be=r(640);t.react={isReactComponent:i.default,isCompatTag:a.default,buildChildren:o.default},t.toSequenceExpression=be.default,n.env.BABEL_TYPES_8_BREAKING&&console.warn("BABEL_TYPES_8_BREAKING is not supported anymore. Use the latest Babel 8.0.0 pre-release instead!")},2378:e=>{"use strict";e.exports=JSON.parse('{"es6.module":{"chrome":"61","and_chr":"61","edge":"16","firefox":"60","and_ff":"60","node":"13.2.0","opera":"48","op_mob":"45","safari":"10.1","ios":"10.3","samsung":"8.2","android":"61","electron":"2.0","ios_saf":"10.3"}}')},2402:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=a;var n=r(8960),s=r(5279),i=r(7639);function a(e,t=e.key){let r;return"method"===e.kind?a.increment()+"":(r=(0,n.isIdentifier)(t)?t.name:(0,n.isStringLiteral)(t)?JSON.stringify(t.value):JSON.stringify((0,i.default)((0,s.default)(t))),e.computed&&(r=`[${r}]`),e.static&&(r=`static:${r}`),r)}a.uid=0,a.increment=function(){return a.uid>=Number.MAX_SAFE_INTEGER?a.uid=0:a.uid++}},2425:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.default)(e,!1,!0)};var n=r(5279)},2457:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.isImportDefaultSpecifier)(e)||(0,n.isIdentifier)(e.imported||e.exported,{name:"default"})};var n=r(8960)},2464:(e,t,r)=>{"use strict";var n=r(8452),s=r(6642);e.exports=function(){var e=s();return n(Number,{isNaN:e},{isNaN:function(){return Number.isNaN!==e}}),e}},2485:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statements=t.statement=t.smart=t.program=t.expression=t.default=void 0;var n=r(826),s=r(4466);const i=t.smart=(0,s.default)(n.smart),a=t.statement=(0,s.default)(n.statement),o=t.statements=(0,s.default)(n.statements),l=t.expression=(0,s.default)(n.expression),c=t.program=(0,s.default)(n.program);t.default=Object.assign(i.bind(void 0),{smart:i,statement:a,statements:o,expression:l,program:c,ast:i.ast})},2598:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){if(!r||!e)return e;const n=`${t}Comments`;return e[n]?"leading"===t?e[n]=r.concat(e[n]):e[n].push(...r):e[n]=r,e}},2610:(e,t,r)=>{"use strict";function n(){const e=r(7975);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=f,t.loadPartialConfig=function*(e){let t=!1;if("object"==typeof e&&null!==e&&!Array.isArray(e)){var r=e;({showIgnoredFiles:t}=r),e=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}(r,d)}const n=yield*f(e);if(!n)return null;const{options:i,babelrc:a,ignore:o,config:l,fileHandling:c,files:p}=n;return"ignored"!==c||t?((i.plugins||[]).forEach((e=>{if(e.value instanceof s.default)throw new Error("Passing cached plugin instances is not supported in babel.loadPartialConfig()")})),new h(i,a?a.filepath:void 0,o?o.filepath:void 0,l?l.filepath:void 0,c,p)):null};var s=r(5856),i=r(9923),a=r(6140),o=r(3045),l=r(324),c=r(7165),p=r(682),u=r(3917);const d=["showIgnoredFiles"];function*f(e){if(null!=e&&("object"!=typeof e||Array.isArray(e)))throw new Error("Babel options must be an object, null, or undefined");const t=e?(0,c.validate)("arguments",e):{},{envName:r=(0,l.getEnv)(),cwd:s=".",root:d=".",rootMode:f="root",caller:h,cloneInputAst:m=!0}=t,y=n().resolve(s),g=function(e,t){switch(t){case"root":return e;case"upward-optional":{const t=(0,p.findConfigUpwards)(e);return null===t?e:t}case"upward":{const t=(0,p.findConfigUpwards)(e);if(null!==t)return t;throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not be found when searching upward from "${e}".\nOne of the following config files must be in the directory tree: "${p.ROOT_CONFIG_FILENAMES.join(", ")}".`),{code:"BABEL_ROOT_NOT_FOUND",dirname:e})}default:throw new Error("Assertion failure - unknown rootMode value.")}}(n().resolve(y,d),f),b="string"==typeof t.filename?n().resolve(s,t.filename):void 0,v={filename:b,cwd:y,root:g,envName:r,caller:h,showConfig:(yield*(0,p.resolveShowConfigPath)(y))===b},T=yield*(0,o.buildRootChain)(t,v);if(!T)return null;const x={assumptions:{}};return T.options.forEach((e=>{(0,i.mergeOptions)(x,e)})),{options:Object.assign({},x,{targets:(0,u.resolveTargets)(x,g),cloneInputAst:m,babelrc:!1,configFile:!1,browserslistConfigFile:!1,passPerPreset:!1,envName:v.envName,cwd:v.cwd,root:v.root,rootMode:"root",filename:"string"==typeof v.filename?v.filename:void 0,plugins:T.plugins.map((e=>(0,a.createItemFromDescriptor)(e))),presets:T.presets.map((e=>(0,a.createItemFromDescriptor)(e)))}),context:v,fileHandling:T.fileHandling,ignore:T.ignore,babelrc:T.babelrc,config:T.config,files:T.files}}class h{constructor(e,t,r,n,s,i){this.options=void 0,this.babelrc=void 0,this.babelignore=void 0,this.config=void 0,this.fileHandling=void 0,this.files=void 0,this.options=e,this.babelignore=r,this.babelrc=t,this.config=n,this.fileHandling=s,this.files=i,Object.freeze(this)}hasFilesystemConfig(){return void 0!==this.babelrc||void 0!==this.config}}Object.freeze(h.prototype)},2660:(e,t,r)=>{e.exports.browsers=r(562)},2682:(e,t,r)=>{"use strict";var n=r(9600),s=Object.prototype.toString,i=Object.prototype.hasOwnProperty;e.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a,o;arguments.length>=3&&(a=r),o=e,"[object Array]"===s.call(o)?function(e,t,r){for(var n=0,s=e.length;n<s;n++)i.call(e,n)&&(null==r?t(e[n],n,e):t.call(r,e[n],n,e))}(e,t,a):"string"==typeof e?function(e,t,r){for(var n=0,s=e.length;n<s;n++)null==r?t(e.charAt(n),n,e):t.call(r,e.charAt(n),n,e)}(e,t,a):function(e,t,r){for(var n in e)i.call(e,n)&&(null==r?t(e[n],n,e):t.call(r,e[n],n,e))}(e,t,a)}},2687:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){if(r&&"Identifier"===e.type&&"ObjectProperty"===t.type&&"ObjectExpression"===r.type)return!1;const s=n.default.keys[t.type];if(s)for(let r=0;r<s.length;r++){const n=t[s[r]];if(Array.isArray(n)){if(n.includes(e))return!0}else if(n===e)return!0}return!1};var n=r(329)},2716:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nodes=void 0;var n=r(2352);const{FLIPPED_ALIAS_KEYS:s,isArrayExpression:i,isAssignmentExpression:a,isBinary:o,isBlockStatement:l,isCallExpression:c,isFunction:p,isIdentifier:u,isLiteral:d,isMemberExpression:f,isObjectExpression:h,isOptionalCallExpression:m,isOptionalMemberExpression:y,isStringLiteral:g}=n;function b(e,t){return e?(f(e)||y(e)?(b(e.object,t),e.computed&&b(e.property,t)):o(e)||a(e)?(b(e.left,t),b(e.right,t)):c(e)||m(e)?(t.hasCall=!0,b(e.callee,t)):p(e)?t.hasFunction=!0:u(e)&&(t.hasHelper=t.hasHelper||e.callee&&T(e.callee)),t):t}function v(e){return b(e,{hasCall:!1,hasFunction:!1,hasHelper:!1})}function T(e){return!!e&&(f(e)?T(e.object)||T(e.property):u(e)?"require"===e.name||95===e.name.charCodeAt(0):c(e)?T(e.callee):!(!o(e)&&!a(e))&&(u(e.left)&&T(e.left)||T(e.right)))}function x(e){return d(e)||h(e)||i(e)||u(e)||f(e)}const S=t.nodes={AssignmentExpression(e){const t=v(e.right);if(t.hasCall&&t.hasHelper||t.hasFunction)return t.hasFunction?3:2},SwitchCase:(e,t)=>(e.consequent.length||t.cases[0]===e?1:0)|(e.consequent.length||t.cases[t.cases.length-1]!==e?0:2),LogicalExpression(e){if(p(e.left)||p(e.right))return 2},Literal(e){if(g(e)&&"use strict"===e.value)return 2},CallExpression(e){if(p(e.callee)||T(e))return 3},OptionalCallExpression(e){if(p(e.callee))return 3},VariableDeclaration(e){for(let t=0;t<e.declarations.length;t++){const r=e.declarations[t];let n=T(r.id)&&!x(r.init);if(!n&&r.init){const e=v(r.init);n=T(r.init)&&e.hasCall||e.hasFunction}if(n)return 3}},IfStatement(e){if(l(e.consequent))return 3}};S.ObjectProperty=S.ObjectTypeProperty=S.ObjectMethod=function(e,t){if(t.properties[0]===e)return 1},S.ObjectTypeCallProperty=function(e,t){var r;if(t.callProperties[0]===e&&(null==(r=t.properties)||!r.length))return 1},S.ObjectTypeIndexer=function(e,t){var r,n;if(!(t.indexers[0]!==e||null!=(r=t.properties)&&r.length||null!=(n=t.callProperties)&&n.length))return 1},S.ObjectTypeInternalSlot=function(e,t){var r,n,s;if(!(t.internalSlots[0]!==e||null!=(r=t.properties)&&r.length||null!=(n=t.callProperties)&&n.length||null!=(s=t.indexers)&&s.length))return 1},[["Function",!0],["Class",!0],["Loop",!0],["LabeledStatement",!0],["SwitchStatement",!0],["TryStatement",!0]].forEach((function([e,t]){[e].concat(s[e]||[]).forEach((function(e){const r=t?3:0;S[e]=()=>r}))}))},2802:function(e,t,r){!function(e,t,r){"use strict";function n(e,t){return t&&!t.endsWith("/")&&(t+="/"),r(e,t)}function s(e,t){for(let r=t;r<e.length;r++)if(!i(e[r]))return r;return e.length}function i(e){for(let t=1;t<e.length;t++)if(e[t][0]<e[t-1][0])return!1;return!0}function a(e,t){return t||(e=e.slice()),e.sort(o)}function o(e,t){return e[0]-t[0]}let l=!1;function c(e,t,r){for(let n=r+1;n<e.length&&e[n][0]===t;r=n++);return r}function p(e,t,r){for(let n=r-1;n>=0&&e[n][0]===t;r=n--);return r}function u(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function d(e,t,r,n){const{lastKey:s,lastNeedle:i,lastIndex:a}=r;let o=0,c=e.length-1;if(n===s){if(t===i)return l=-1!==a&&e[a][0]===t,a;t>=i?o=-1===a?0:a:c=a}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=function(e,t,r,n){for(;r<=n;){const s=r+(n-r>>1),i=e[s][0]-t;if(0===i)return l=!0,s;i<0?r=s+1:n=s-1}return l=!1,r-1}(e,t,o,c)}function f(e,t,r){for(let r=e.length;r>t;r--)e[r]=e[r-1];e[t]=r}function h(){return{__proto__:null}}function m(e){return"string"==typeof e?JSON.parse(e):e}function y(e,t,r,n,s,i,a,o,l,c,p){const{sections:u}=e;for(let e=0;e<u.length;e++){const{map:d,offset:f}=u[e];let h=c,m=p;if(e+1<u.length){const t=u[e+1].offset;h=Math.min(c,o+t.line),h===c?m=Math.min(p,l+t.column):h<c&&(m=l+t.column)}g(d,t,r,n,s,i,a,o+f.line,l+f.column,h,m)}}function g(e,t,r,n,s,i,a,o,l,c,p){const u=m(e);if("sections"in u)return y(...arguments);const d=new S(u,t),f=n.length,h=i.length,g=P(d),{resolvedSources:T,sourcesContent:x,ignoreList:E}=d;if(b(n,T),b(i,d.names),x)b(s,x);else for(let e=0;e<T.length;e++)s.push(null);if(E)for(let e=0;e<E.length;e++)a.push(E[e]+f);for(let e=0;e<g.length;e++){const t=o+e;if(t>c)return;const n=v(r,t),s=0===e?l:0,i=g[e];for(let e=0;e<i.length;e++){const r=i[e],a=s+r[0];if(t===c&&a>=p)return;if(1===r.length){n.push([a]);continue}const o=f+r[1],l=r[2],u=r[3];n.push(4===r.length?[a,o,l,u]:[a,o,l,u,h+r[4]])}}}function b(e,t){for(let r=0;r<t.length;r++)e.push(t[r])}function v(e,t){for(let r=e.length;r<=t;r++)e[r]=[];return e[t]}const T="`line` must be greater than 0 (lines start at line 1)",x="`column` must be greater than or equal to 0 (columns start at column 0)";class S{constructor(e,t){const r="string"==typeof e;if(!r&&e._decodedMemo)return e;const i=r?JSON.parse(e):e,{version:o,file:l,names:c,sourceRoot:p,sources:u,sourcesContent:d}=i;this.version=o,this.file=l,this.names=c||[],this.sourceRoot=p,this.sources=u,this.sourcesContent=d,this.ignoreList=i.ignoreList||i.x_google_ignoreList||void 0;const f=n(p||"",function(e){if(!e)return"";const t=e.lastIndexOf("/");return e.slice(0,t+1)}(t));this.resolvedSources=u.map((e=>n(e||"",f)));const{mappings:h}=i;"string"==typeof h?(this._encoded=h,this._decoded=void 0):(this._encoded=void 0,this._decoded=function(e,t){const r=s(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n<e.length;n=s(e,n+1))e[n]=a(e[n],t);return e}(h,r)),this._decodedMemo={lastKey:-1,lastNeedle:-1,lastIndex:-1},this._bySources=void 0,this._bySourceMemos=void 0}}function E(e){var r,n;return null!==(r=(n=e)._encoded)&&void 0!==r?r:n._encoded=t.encode(e._decoded)}function P(e){var r;return(r=e)._decoded||(r._decoded=t.decode(e._encoded))}function A(e,t){const{sources:r,resolvedSources:n}=e;let s=r.indexOf(t);return-1===s&&(s=n.indexOf(t)),s}function w(e,t){const r=new S(C(e,[]),t);return r._decoded=e.mappings,r}function C(e,t){return{version:e.version,file:e.file,names:e.names,sourceRoot:e.sourceRoot,sources:e.sources,sourcesContent:e.sourcesContent,mappings:t,ignoreList:e.ignoreList||e.x_google_ignoreList}}function O(e,t,r,n){return{source:e,line:t,column:r,name:n}}function I(e,t){return{line:e,column:t}}function N(e,t,r,n,s){let i=d(e,n,t,r);return l?i=(-1===s?c:p)(e,n,i):-1===s&&i++,-1===i||i===e.length?-1:i}function k(e,t,r,n,s,i){var a;if(--r<0)throw new Error(T);if(n<0)throw new Error(x);const{sources:o,resolvedSources:m}=e;let y=o.indexOf(t);if(-1===y&&(y=m.indexOf(t)),-1===y)return i?[]:I(null,null);const g=((a=e)._bySources||(a._bySources=function(e,t){const r=t.map(h);for(let n=0;n<e.length;n++){const s=e[n];for(let e=0;e<s.length;e++){const i=s[e];if(1===i.length)continue;const a=i[1],o=i[2],l=i[3],p=r[a],u=p[o]||(p[o]=[]),h=t[a];let m=c(u,l,d(u,l,h,o));h.lastIndex=++m,f(u,m,[l,n,i[0]])}}return r}(P(e),e._bySourceMemos=o.map(u))))[y][r];if(null==g)return i?[]:I(null,null);const b=e._bySourceMemos[y];if(i)return function(e,t,r,n,s){let i=N(e,t,r,n,1);if(l||-1!==s||i++,-1===i||i===e.length)return[];const a=l?n:e[i][0];l||(i=p(e,a,i));const o=c(e,a,i),u=[];for(;i<=o;i++){const t=e[i];u.push(I(t[1]+1,t[2]))}return u}(g,b,r,n,s);const v=N(g,b,r,n,s);if(-1===v)return I(null,null);const S=g[v];return I(S[1]+1,S[2])}e.AnyMap=function(e,t){const r=m(e);if(!("sections"in r))return new S(r,t);const n=[],s=[],i=[],a=[],o=[];return y(r,t,n,s,i,a,o,0,0,1/0,1/0),w({version:3,file:r.file,names:a,sources:s,sourcesContent:i,mappings:n,ignoreList:o})},e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=-1,e.TraceMap=S,e.allGeneratedPositionsFor=function(e,t){const{source:r,line:n,column:s,bias:i}=t;return k(e,r,n,s,i||-1,!0)},e.decodedMap=function(e){return C(e,P(e))},e.decodedMappings=P,e.eachMapping=function(e,t){const r=P(e),{names:n,resolvedSources:s}=e;for(let e=0;e<r.length;e++){const i=r[e];for(let r=0;r<i.length;r++){const a=i[r],o=e+1,l=a[0];let c=null,p=null,u=null,d=null;1!==a.length&&(c=s[a[1]],p=a[2]+1,u=a[3]),5===a.length&&(d=n[a[4]]),t({generatedLine:o,generatedColumn:l,source:c,originalLine:p,originalColumn:u,name:d})}}},e.encodedMap=function(e){return C(e,E(e))},e.encodedMappings=E,e.generatedPositionFor=function(e,t){const{source:r,line:n,column:s,bias:i}=t;return k(e,r,n,s,i||1,!1)},e.isIgnored=function(e,t){const{ignoreList:r}=e;if(null==r)return!1;const n=A(e,t);return-1!==n&&r.includes(n)},e.originalPositionFor=function(e,t){let{line:r,column:n,bias:s}=t;if(r--,r<0)throw new Error(T);if(n<0)throw new Error(x);const i=P(e);if(r>=i.length)return O(null,null,null,null);const a=i[r],o=N(a,e._decodedMemo,r,n,s||1);if(-1===o)return O(null,null,null,null);const l=a[o];if(1===l.length)return O(null,null,null,null);const{names:c,resolvedSources:p}=e;return O(p[l[1]],l[2]+1,l[3],5===l.length?c[l[4]]:null)},e.presortedDecodedMap=w,e.sourceContentFor=function(e,t){const{sourcesContent:r}=e;if(null==r)return null;const n=A(e,t);return-1===n?null:r[n]},e.traceSegment=function(e,t,r){const n=P(e);if(t>=n.length)return null;const s=n[t],i=N(s,e._decodedMemo,t,r,1);return-1===i?null:s[i]}}(t,r(4318),r(4424))},2861:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ArrowFunctionExpression=function(e,t){e.async&&(this.word("async",!0),this.space()),this._shouldPrintArrowParamsParens(e)?this._params(e,void 0,t):this.print(e.params[0],!0),this._predicate(e,!0),this.space(),this.printInnerComments(),this.token("=>"),this.space(),this.tokenContext|=s.TokenContext.arrowBody,this.print(e.body)},t.FunctionDeclaration=t.FunctionExpression=function(e,t){this._functionHead(e,t),this.space(),this.print(e.body)},t._functionHead=function(e,t){e.async&&(this.word("async"),this.format.preserveFormat||(this._endsWithInnerRaw=!1),this.space()),this.word("function"),e.generator&&(this.format.preserveFormat||(this._endsWithInnerRaw=!1),this.tokenChar(42)),this.space(),e.id&&this.print(e.id),this._params(e,e.id,t),"TSDeclareFunction"!==e.type&&this._predicate(e)},t._methodHead=function(e){const t=e.kind,r=e.key;"get"!==t&&"set"!==t||(this.word(t),this.space()),e.async&&(this.word("async",!0),this.space()),"method"!==t&&"init"!==t||e.generator&&this.tokenChar(42),e.computed?(this.tokenChar(91),this.print(r),this.tokenChar(93)):this.print(r),e.optional&&this.tokenChar(63),this._params(e,e.computed&&"StringLiteral"!==e.key.type?void 0:e.key,void 0)},t._param=function(e){this.printJoin(e.decorators),this.print(e),e.optional&&this.tokenChar(63),this.print(e.typeAnnotation)},t._parameters=function(e,t){const r=this.enterDelimited(),n=this.shouldPrintTrailingComma(t),s=e.length;for(let t=0;t<s;t++)this._param(e[t]),(n||t<s-1)&&(this.token(",",null,t),this.space());this.token(t),r()},t._params=function(e,t,r){this.print(e.typeParameters);const n=a.call(this,t,r);n&&this.sourceIdentifierName(n.name,n.pos),this.tokenChar(40),this._parameters(e.params,")");const s="ArrowFunctionExpression"===e.type;this.print(e.returnType,s),this._noLineTerminator=s},t._predicate=function(e,t){e.predicate&&(e.returnType||this.tokenChar(58),this.space(),this.print(e.predicate,t))},t._shouldPrintArrowParamsParens=function(e){var t,r;if(1!==e.params.length)return!0;if(e.typeParameters||e.returnType||e.predicate)return!0;const n=e.params[0];if(!i(n)||n.typeAnnotation||n.optional||null!=(t=n.leadingComments)&&t.length||null!=(r=n.trailingComments)&&r.length)return!0;if(this.tokenMap){if(null==e.loc)return!0;if(null!==this.tokenMap.findMatching(e,"("))return!0;const t=this.tokenMap.findMatching(e,"=>");return null==(null==t?void 0:t.loc)||t.loc.start.line!==e.loc.start.line}return!!this.format.retainLines};var n=r(2352),s=r(1373);const{isIdentifier:i}=n;function a(e,t){let r,n=e;if(!n&&t){const e=t.type;"VariableDeclarator"===e?n=t.id:"AssignmentExpression"===e||"AssignmentPattern"===e?n=t.left:"ObjectProperty"===e||"ClassProperty"===e?t.computed&&"StringLiteral"!==t.key.type||(n=t.key):"ClassPrivateProperty"!==e&&"ClassAccessorProperty"!==e||(n=t.key)}if(n){var s,i;if("Identifier"===n.type)r={pos:null==(s=n.loc)?void 0:s.start,name:(null==(i=n.loc)?void 0:i.identifierName)||n.name};else if("PrivateName"===n.type){var a;r={pos:null==(a=n.loc)?void 0:a.start,name:"#"+n.id.name}}else if("StringLiteral"===n.type){var o;r={pos:null==(o=n.loc)?void 0:o.start,name:n.value}}return r}}},2882:(e,t,r)=>{"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0});var s=r(8633),i=r(5879),a=r(1e3);const o=(e,t)=>r=>e(t(r));function l(e){return{keyword:e.cyan,capitalized:e.yellow,jsxIdentifier:e.yellow,punctuator:e.yellow,number:e.magenta,string:e.green,regex:e.magenta,comment:e.gray,invalid:o(o(e.white,e.bgRed),e.bold),gutter:e.gray,marker:o(e.red,e.bold),message:o(e.red,e.bold),reset:e.reset}}const c=l(s.createColors(!0)),p=l(s.createColors(!1));function u(e){return e?c:p}const d=new Set(["as","async","from","get","of","set"]),f=/\r\n|[\n\r\u2028\u2029]/,h=/^[()[\]{}]$/;let m;{const e=/^[a-z][\w-]*$/i,t=function(t,r,n){if("name"===t.type){if(a.isKeyword(t.value)||a.isStrictReservedWord(t.value,!0)||d.has(t.value))return"keyword";if(e.test(t.value)&&("<"===n[r-1]||"</"===n.slice(r-2,r)))return"jsxIdentifier";if(t.value[0]!==t.value[0].toLowerCase())return"capitalized"}return"punctuator"===t.type&&h.test(t.value)?"bracket":"invalid"!==t.type||"@"!==t.value&&"#"!==t.value?t.type:"punctuator"};m=function*(e){let r;for(;r=i.default.exec(e);){const n=i.matchToToken(r);yield{type:t(n,r.index,e),value:n.value}}}}function y(e){if(""===e)return"";const t=u(!0);let r="";for(const{type:n,value:s}of m(e))r+=n in t?s.split(f).map((e=>t[n](e))).join("\n"):s;return r}let g=!1;const b=/\r\n|[\n\r\u2028\u2029]/;function v(e,t,r={}){const i=r.forceColor||("object"!=typeof n||"0"!==n.env.FORCE_COLOR&&"false"!==n.env.FORCE_COLOR)&&s.isColorSupported&&r.highlightCode,a=u(i),o=e.split(b),{start:l,end:c,markerLines:p}=function(e,t,r){const n=Object.assign({column:0,line:-1},e.start),s=Object.assign({},n,e.end),{linesAbove:i=2,linesBelow:a=3}=r||{},o=n.line,l=n.column,c=s.line,p=s.column;let u=Math.max(o-(i+1),0),d=Math.min(t.length,c+a);-1===o&&(u=0),-1===c&&(d=t.length);const f=c-o,h={};if(f)for(let e=0;e<=f;e++){const r=e+o;if(l)if(0===e){const e=t[r-1].length;h[r]=[l,e-l+1]}else if(e===f)h[r]=[0,p];else{const n=t[r-e].length;h[r]=[0,n]}else h[r]=!0}else h[o]=l===p?!l||[l,0]:[l,p-l];return{start:u,end:d,markerLines:h}}(t,o,r),d=t.start&&"number"==typeof t.start.column,f=String(c).length;let h=(i?y(e):e).split(b,c).slice(l,c).map(((e,t)=>{const n=l+1+t,s=` ${` ${n}`.slice(-f)} |`,i=p[n],o=!p[n+1];if(i){let t="";if(Array.isArray(i)){const n=e.slice(0,Math.max(i[0]-1,0)).replace(/[^\t]/g," "),l=i[1]||1;t=["\n ",a.gutter(s.replace(/\d/g," "))," ",n,a.marker("^").repeat(l)].join(""),o&&r.message&&(t+=" "+a.message(r.message))}return[a.marker(">"),a.gutter(s),e.length>0?` ${e}`:"",t].join("")}return` ${a.gutter(s)}${e.length>0?` ${e}`:""}`})).join("\n");return r.message&&!d&&(h=`${" ".repeat(f+1)}${r.message}\n${h}`),i?a.reset(h):h}t.codeFrameColumns=v,t.default=function(e,t,r,s={}){if(!g){g=!0;const e="Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";n.emitWarning?n.emitWarning(e,"DeprecationWarning"):(new Error(e).name="DeprecationWarning",console.warn(new Error(e)))}return v(e,{start:{column:r=Math.max(r,0),line:t}},s)},t.highlight=y},2911:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default={auxiliaryComment:{message:"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"},blacklist:{message:"Put the specific transforms you want in the `plugins` option"},breakConfig:{message:"This is not a necessary option in Babel 6"},experimental:{message:"Put the specific transforms you want in the `plugins` option"},externalHelpers:{message:"Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"},extra:{message:""},jsxPragma:{message:"use the `pragma` option in the `react-jsx` plugin. Check out http://babeljs.io/docs/plugins/transform-react-jsx/"},loose:{message:"Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."},metadataUsedHelpers:{message:"Not required anymore as this is enabled by default"},modules:{message:"Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules"},nonStandard:{message:"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"},optional:{message:"Put the specific transforms you want in the `plugins` option"},sourceMapName:{message:"The `sourceMapName` option has been removed because it makes more sense for the tooling that calls Babel to assign `map.file` themselves."},stage:{message:"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"},whitelist:{message:"Put the specific transforms you want in the `plugins` option"},resolveModuleSource:{version:6,message:"Use `babel-plugin-module-resolver@3`'s 'resolvePath' options"},metadata:{version:6,message:"Generated plugin metadata is always included in the output result"},sourceMapTarget:{version:6,message:"The `sourceMapTarget` option has been removed because it makes more sense for the tooling that calls Babel to assign `map.file` themselves."}}},3003:e=>{"use strict";e.exports=function(e){return e!=e}},3017:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t=e.key||e.property){return!e.computed&&(0,n.isIdentifier)(t)&&(t=(0,s.stringLiteral)(t.name)),t};var n=r(8960),s=r(8079)},3043:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const r=e.value.split(/\r\n|\n|\r/);let i=0;for(let e=0;e<r.length;e++)/[^ \t]/.exec(r[e])&&(i=e);let a="";for(let e=0;e<r.length;e++){const t=r[e],n=0===e,s=e===r.length-1,o=e===i;let l=t.replace(/\t/g," ");n||(l=l.replace(/^ +/,"")),s||(l=l.replace(/ +$/,"")),l&&(o||(l+=" "),a+=l)}a&&t.push((0,s.inherits)((0,n.stringLiteral)(a),e))};var n=r(8079),s=r(2352)},3045:(e,t,r)=>{"use strict";function n(){const e=r(7975);return n=function(){return e},e}function s(){const e=r(7833);return s=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.buildPresetChain=function*(e,t){const r=yield*h(e,t);return r?{plugins:R(r.plugins),presets:R(r.presets),options:r.options.map((e=>F(e))),files:new Set}:null},t.buildPresetChainWalker=void 0,t.buildRootChain=function*(e,t){let r,s;const i=new o.ConfigPrinter,l=yield*S({options:e,dirname:t.cwd},t,void 0,i);if(!l)return null;const c=yield*i.output();let u;"string"==typeof e.configFile?u=yield*(0,p.loadConfig)(e.configFile,t.cwd,t.envName,t.caller):!1!==e.configFile&&(u=yield*(0,p.findRootConfig)(t.root,t.envName,t.caller));let{babelrc:d,babelrcRoots:f}=e,h=t.cwd;const m=L(),y=new o.ConfigPrinter;if(u){const e=v(u),n=yield*P(e,t,void 0,y);if(!n)return null;r=yield*y.output(),void 0===d&&(d=e.options.babelrc),void 0===f&&(h=e.dirname,f=e.options.babelrcRoots),B(m,n)}let g,b,x=!1;const E=L();if((!0===d||void 0===d)&&"string"==typeof t.filename){const e=yield*(0,p.findPackageData)(t.filename);if(e&&function(e,t,r,s){if("boolean"==typeof r)return r;const i=e.root;if(void 0===r)return t.directories.includes(i);let o=r;return Array.isArray(o)||(o=[o]),o=o.map((e=>"string"==typeof e?n().resolve(s,e):e)),1===o.length&&o[0]===i?t.directories.includes(i):o.some((r=>("string"==typeof r&&(r=(0,a.default)(r,s)),t.directories.some((t=>$(r,s,t,e))))))}(t,e,f,h)){if(({ignore:g,config:b}=yield*(0,p.findRelativeConfig)(e,t.envName,t.caller)),g&&E.files.add(g.filepath),g&&W(t,g.ignore,null,g.dirname)&&(x=!0),b&&!x){const e=T(b),r=new o.ConfigPrinter,n=yield*P(e,t,void 0,r);n?(s=yield*r.output(),B(E,n)):x=!0}b&&x&&E.files.add(b.filepath)}}t.showConfig&&console.log(`Babel configs on "${t.filename}" (ascending priority):\n`+[r,s,c].filter((e=>!!e)).join("\n\n")+"\n-----End Babel configs-----");const A=B(B(B(L(),m),E),l);return{plugins:x?[]:R(A.plugins),presets:x?[]:R(A.presets),options:x?[]:A.options.map((e=>F(e))),fileHandling:x?"ignored":"transpile",ignore:g||void 0,babelrc:b||void 0,config:u||void 0,files:A.files}};var i=r(7165),a=r(3853),o=r(3611),l=r(1339),c=r(7445),p=r(682),u=r(1310),d=r(9990);const f=s()("babel:config:config-chain"),h=t.buildPresetChainWalker=D({root:e=>m(e),env:(e,t)=>y(e)(t),overrides:(e,t)=>g(e)(t),overridesEnv:(e,t,r)=>b(e)(t)(r),createLogger:()=>()=>{}}),m=(0,u.makeWeakCacheSync)((e=>I(e,e.alias,d.createUncachedDescriptors))),y=(0,u.makeWeakCacheSync)((e=>(0,u.makeStrongCacheSync)((t=>N(e,e.alias,d.createUncachedDescriptors,t))))),g=(0,u.makeWeakCacheSync)((e=>(0,u.makeStrongCacheSync)((t=>k(e,e.alias,d.createUncachedDescriptors,t))))),b=(0,u.makeWeakCacheSync)((e=>(0,u.makeStrongCacheSync)((t=>(0,u.makeStrongCacheSync)((r=>_(e,e.alias,d.createUncachedDescriptors,t,r))))))),v=(0,u.makeWeakCacheSync)((e=>({filepath:e.filepath,dirname:e.dirname,options:(0,i.validate)("configfile",e.options,e.filepath)}))),T=(0,u.makeWeakCacheSync)((e=>({filepath:e.filepath,dirname:e.dirname,options:(0,i.validate)("babelrcfile",e.options,e.filepath)}))),x=(0,u.makeWeakCacheSync)((e=>({filepath:e.filepath,dirname:e.dirname,options:(0,i.validate)("extendsfile",e.options,e.filepath)}))),S=D({root:e=>I(e,"base",d.createCachedDescriptors),env:(e,t)=>N(e,"base",d.createCachedDescriptors,t),overrides:(e,t)=>k(e,"base",d.createCachedDescriptors,t),overridesEnv:(e,t,r)=>_(e,"base",d.createCachedDescriptors,t,r),createLogger:(e,t,r)=>function(e,t,r){var n;return r?r.configure(t.showConfig,o.ChainFormatter.Programmatic,{callerName:null==(n=t.caller)?void 0:n.name}):()=>{}}(0,t,r)}),E=D({root:e=>A(e),env:(e,t)=>w(e)(t),overrides:(e,t)=>C(e)(t),overridesEnv:(e,t,r)=>O(e)(t)(r),createLogger:(e,t,r)=>function(e,t,r){return r?r.configure(t.showConfig,o.ChainFormatter.Config,{filepath:e}):()=>{}}(e.filepath,t,r)});function*P(e,t,r,n){const s=yield*E(e,t,r,n);return null==s||s.files.add(e.filepath),s}const A=(0,u.makeWeakCacheSync)((e=>I(e,e.filepath,d.createUncachedDescriptors))),w=(0,u.makeWeakCacheSync)((e=>(0,u.makeStrongCacheSync)((t=>N(e,e.filepath,d.createUncachedDescriptors,t))))),C=(0,u.makeWeakCacheSync)((e=>(0,u.makeStrongCacheSync)((t=>k(e,e.filepath,d.createUncachedDescriptors,t))))),O=(0,u.makeWeakCacheSync)((e=>(0,u.makeStrongCacheSync)((t=>(0,u.makeStrongCacheSync)((r=>_(e,e.filepath,d.createUncachedDescriptors,t,r)))))));function I({dirname:e,options:t},r,n){return n(e,t,r)}function N({dirname:e,options:t},r,n,s){var i;const a=null==(i=t.env)?void 0:i[s];return a?n(e,a,`${r}.env["${s}"]`):null}function k({dirname:e,options:t},r,n,s){var i;const a=null==(i=t.overrides)?void 0:i[s];if(!a)throw new Error("Assertion failure - missing override");return n(e,a,`${r}.overrides[${s}]`)}function _({dirname:e,options:t},r,n,s,i){var a,o;const l=null==(a=t.overrides)?void 0:a[s];if(!l)throw new Error("Assertion failure - missing override");const c=null==(o=l.env)?void 0:o[i];return c?n(e,c,`${r}.overrides[${s}].env["${i}"]`):null}function D({root:e,env:t,overrides:r,overridesEnv:n,createLogger:s}){return function*(i,a,o=new Set,l){const{dirname:c}=i,p=[],u=e(i);if(U(u,c,a,i.filepath)){p.push({config:u,envName:void 0,index:void 0});const e=t(i,a.envName);e&&U(e,c,a,i.filepath)&&p.push({config:e,envName:a.envName,index:void 0}),(u.options.overrides||[]).forEach(((e,t)=>{const s=r(i,t);if(U(s,c,a,i.filepath)){p.push({config:s,index:t,envName:void 0});const e=n(i,t,a.envName);e&&U(e,c,a,i.filepath)&&p.push({config:e,index:t,envName:a.envName})}}))}if(p.some((({config:{options:{ignore:e,only:t}}})=>W(a,e,t,c))))return null;const d=L(),f=s(i,a,l);for(const{config:e,index:t,envName:r}of p){if(!(yield*j(d,e.options,c,a,o,l)))return null;f(e,t,r),yield*M(d,e)}return d}}function*j(e,t,r,n,s,i){if(void 0===t.extends)return!0;const a=yield*(0,p.loadConfig)(t.extends,r,n.envName,n.caller);if(s.has(a))throw new Error(`Configuration cycle detected loading ${a.filepath}.\nFile already loaded following the config chain:\n`+Array.from(s,(e=>` - ${e.filepath}`)).join("\n"));s.add(a);const o=yield*P(x(a),n,s,i);return s.delete(a),!!o&&(B(e,o),!0)}function B(e,t){e.options.push(...t.options),e.plugins.push(...t.plugins),e.presets.push(...t.presets);for(const r of t.files)e.files.add(r);return e}function*M(e,{options:t,plugins:r,presets:n}){return e.options.push(t),e.plugins.push(...yield*r()),e.presets.push(...yield*n()),e}function L(){return{options:[],presets:[],plugins:[],files:new Set}}function F(e){const t=Object.assign({},e);return delete t.extends,delete t.env,delete t.overrides,delete t.plugins,delete t.presets,delete t.passPerPreset,delete t.ignore,delete t.only,delete t.test,delete t.include,delete t.exclude,hasOwnProperty.call(t,"sourceMap")&&(t.sourceMaps=t.sourceMap,delete t.sourceMap),t}function R(e){const t=new Map,r=[];for(const n of e)if("function"==typeof n.value){const e=n.value;let s=t.get(e);s||(s=new Map,t.set(e,s));let i=s.get(n.name);i?i.value=n:(i={value:n},r.push(i),n.ownPass||s.set(n.name,i))}else r.push({value:n});return r.reduce(((e,t)=>(e.push(t.value),e)),[])}function U({options:e},t,r,n){return(void 0===e.test||V(r,e.test,t,n))&&(void 0===e.include||V(r,e.include,t,n))&&(void 0===e.exclude||!V(r,e.exclude,t,n))}function V(e,t,r,n){return K(e,Array.isArray(t)?t:[t],r,n)}function q(e,t){return t instanceof RegExp?String(t):t}function W(e,t,r,n){if(t&&K(e,t,n)){var s;const r=`No config is applied to "${null!=(s=e.filename)?s:"(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(t,q)}\` from "${n}"`;return f(r),e.showConfig&&console.log(r),!0}if(r&&!K(e,r,n)){var i;const t=`No config is applied to "${null!=(i=e.filename)?i:"(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(r,q)}\` from "${n}"`;return f(t),e.showConfig&&console.log(t),!0}return!1}function K(e,t,r,n){return t.some((t=>$(t,r,e.filename,e,n)))}function $(e,t,r,n,s){if("function"==typeof e)return!!(0,l.endHiddenCallStack)(e)(r,{dirname:t,envName:n.envName,caller:n.caller});if("string"!=typeof r)throw new c.default("Configuration contains string/RegExp pattern, but no filename was passed to Babel",s);return"string"==typeof e&&(e=(0,a.default)(e,t)),e.test(r)}},3093:(e,t,r)=>{"use strict";var n=r(4459);e.exports=function(e){return n(e)||0===e?e:e<0?-1:1}},3097:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._assertUnremoved=m,t._callRemovalHooks=d,t._markRemoved=h,t._remove=f,t._removeFromScope=u,t.remove=function(){var e;m.call(this),c.resync.call(this),d.call(this)||(null!=(e=this.opts)&&e.noScope||u.call(this),this.shareCommentsWithSiblings(),f.call(this)),h.call(this)};var n=r(7860),s=r(7411),i=r(2037),a=r(9709),o=r(2352),l=r(8345),c=r(9578);const{getBindingIdentifiers:p}=o;function u(){const e=p(this.node,!1,!1,!0);Object.keys(e).forEach((e=>this.scope.removeBinding(e)))}function d(){if(this.parentPath)for(const e of n.hooks)if(e(this,this.parentPath))return!0}function f(){Array.isArray(this.container)?(this.container.splice(this.key,1),l.updateSiblingKeys.call(this,this.key,-1)):i._replaceWith.call(this,null)}function h(){this._traverseFlags|=a.SHOULD_SKIP|a.REMOVED,this.parent&&(0,s.getCachedPaths)(this.hub,this.parent).delete(this.node),this.node=null}function m(){if(this.removed)throw this.buildCodeFrameError("NodePath has been removed so is read-only.")}},3115:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isKeyword=function(e){return r.has(e)},t.isReservedWord=i,t.isStrictBindOnlyReservedWord=o,t.isStrictBindReservedWord=function(e,t){return a(e,t)||o(e)},t.isStrictReservedWord=a;const r=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"]),n=new Set(["implements","interface","let","package","private","protected","public","static","yield"]),s=new Set(["eval","arguments"]);function i(e,t){return t&&"await"===e||"enum"===e}function a(e,t){return i(e,t)||n.has(e)}function o(e){return s.has(e)}},3126:(e,t,r)=>{"use strict";var n=r(6743),s=r(9675),i=r(76),a=r(3144);e.exports=function(e){if(e.length<1||"function"!=typeof e[0])throw new s("a function is required");return a(n,i,e)}},3141:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createUnionType=function(e){return e.every((e=>o(e)))?s?s(e):a(e):e.every((e=>l(e)))&&i?i(e):void 0};var n=r(2352);const{createFlowUnionType:s,createTSUnionType:i,createUnionTypeAnnotation:a,isFlowType:o,isTSType:l}=n},3144:(e,t,r)=>{"use strict";var n=r(6743),s=r(1002),i=r(76),a=r(7119);e.exports=a||n.call(i,s)},3147:e=>{"use strict";e.exports=JSON.parse('{"v0.8":{"start":"2012-06-25","end":"2014-07-31"},"v0.10":{"start":"2013-03-11","end":"2016-10-31"},"v0.12":{"start":"2015-02-06","end":"2016-12-31"},"v4":{"start":"2015-09-08","lts":"2015-10-12","maintenance":"2017-04-01","end":"2018-04-30","codename":"Argon"},"v5":{"start":"2015-10-29","maintenance":"2016-04-30","end":"2016-06-30"},"v6":{"start":"2016-04-26","lts":"2016-10-18","maintenance":"2018-04-30","end":"2019-04-30","codename":"Boron"},"v7":{"start":"2016-10-25","maintenance":"2017-04-30","end":"2017-06-30"},"v8":{"start":"2017-05-30","lts":"2017-10-31","maintenance":"2019-01-01","end":"2019-12-31","codename":"Carbon"},"v9":{"start":"2017-10-01","maintenance":"2018-04-01","end":"2018-06-30"},"v10":{"start":"2018-04-24","lts":"2018-10-30","maintenance":"2020-05-19","end":"2021-04-30","codename":"Dubnium"},"v11":{"start":"2018-10-23","maintenance":"2019-04-22","end":"2019-06-01"},"v12":{"start":"2019-04-23","lts":"2019-10-21","maintenance":"2020-11-30","end":"2022-04-30","codename":"Erbium"},"v13":{"start":"2019-10-22","maintenance":"2020-04-01","end":"2020-06-01"},"v14":{"start":"2020-04-21","lts":"2020-10-27","maintenance":"2021-10-19","end":"2023-04-30","codename":"Fermium"},"v15":{"start":"2020-10-20","maintenance":"2021-04-01","end":"2021-06-01"},"v16":{"start":"2021-04-20","lts":"2021-10-26","maintenance":"2022-10-18","end":"2023-09-11","codename":"Gallium"},"v17":{"start":"2021-10-19","maintenance":"2022-04-01","end":"2022-06-01"},"v18":{"start":"2022-04-19","lts":"2022-10-25","maintenance":"2023-10-18","end":"2025-04-30","codename":"Hydrogen"},"v19":{"start":"2022-10-18","maintenance":"2023-04-01","end":"2023-06-01"},"v20":{"start":"2023-04-18","lts":"2023-10-24","maintenance":"2024-10-22","end":"2026-04-30","codename":"Iron"},"v21":{"start":"2023-10-17","maintenance":"2024-04-01","end":"2024-06-01"},"v22":{"start":"2024-04-24","lts":"2024-10-29","maintenance":"2025-10-21","end":"2027-04-30","codename":"Jod"},"v23":{"start":"2024-10-16","maintenance":"2025-04-01","end":"2025-06-01"},"v24":{"start":"2025-04-22","lts":"2025-10-28","maintenance":"2026-10-20","end":"2028-04-30","codename":""}}')},3205:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){t&&r&&(t[e]=Array.from(new Set([].concat(t[e],r[e]).filter(Boolean))))}},3286:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.anyTypeAnnotation=function(){return{type:"AnyTypeAnnotation"}},t.argumentPlaceholder=function(){return{type:"ArgumentPlaceholder"}},t.arrayExpression=function(e=[]){const t={type:"ArrayExpression",elements:e},r=o.ArrayExpression;return a(r.elements,t,"elements",e,1),t},t.arrayPattern=function(e){const t={type:"ArrayPattern",elements:e},r=o.ArrayPattern;return a(r.elements,t,"elements",e,1),t},t.arrayTypeAnnotation=function(e){const t={type:"ArrayTypeAnnotation",elementType:e},r=o.ArrayTypeAnnotation;return a(r.elementType,t,"elementType",e,1),t},t.arrowFunctionExpression=function(e,t,r=!1){const n={type:"ArrowFunctionExpression",params:e,body:t,async:r,expression:null},s=o.ArrowFunctionExpression;return a(s.params,n,"params",e,1),a(s.body,n,"body",t,1),a(s.async,n,"async",r),n},t.assignmentExpression=function(e,t,r){const n={type:"AssignmentExpression",operator:e,left:t,right:r},s=o.AssignmentExpression;return a(s.operator,n,"operator",e),a(s.left,n,"left",t,1),a(s.right,n,"right",r,1),n},t.assignmentPattern=function(e,t){const r={type:"AssignmentPattern",left:e,right:t},n=o.AssignmentPattern;return a(n.left,r,"left",e,1),a(n.right,r,"right",t,1),r},t.awaitExpression=function(e){const t={type:"AwaitExpression",argument:e},r=o.AwaitExpression;return a(r.argument,t,"argument",e,1),t},t.bigIntLiteral=function(e){const t={type:"BigIntLiteral",value:e},r=o.BigIntLiteral;return a(r.value,t,"value",e),t},t.binaryExpression=function(e,t,r){const n={type:"BinaryExpression",operator:e,left:t,right:r},s=o.BinaryExpression;return a(s.operator,n,"operator",e),a(s.left,n,"left",t,1),a(s.right,n,"right",r,1),n},t.bindExpression=function(e,t){const r={type:"BindExpression",object:e,callee:t},n=o.BindExpression;return a(n.object,r,"object",e,1),a(n.callee,r,"callee",t,1),r},t.blockStatement=function(e,t=[]){const r={type:"BlockStatement",body:e,directives:t},n=o.BlockStatement;return a(n.body,r,"body",e,1),a(n.directives,r,"directives",t,1),r},t.booleanLiteral=function(e){const t={type:"BooleanLiteral",value:e},r=o.BooleanLiteral;return a(r.value,t,"value",e),t},t.booleanLiteralTypeAnnotation=function(e){const t={type:"BooleanLiteralTypeAnnotation",value:e},r=o.BooleanLiteralTypeAnnotation;return a(r.value,t,"value",e),t},t.booleanTypeAnnotation=function(){return{type:"BooleanTypeAnnotation"}},t.breakStatement=function(e=null){const t={type:"BreakStatement",label:e},r=o.BreakStatement;return a(r.label,t,"label",e,1),t},t.callExpression=function(e,t){const r={type:"CallExpression",callee:e,arguments:t},n=o.CallExpression;return a(n.callee,r,"callee",e,1),a(n.arguments,r,"arguments",t,1),r},t.catchClause=function(e=null,t){const r={type:"CatchClause",param:e,body:t},n=o.CatchClause;return a(n.param,r,"param",e,1),a(n.body,r,"body",t,1),r},t.classAccessorProperty=function(e,t=null,r=null,n=null,s=!1,i=!1){const l={type:"ClassAccessorProperty",key:e,value:t,typeAnnotation:r,decorators:n,computed:s,static:i},c=o.ClassAccessorProperty;return a(c.key,l,"key",e,1),a(c.value,l,"value",t,1),a(c.typeAnnotation,l,"typeAnnotation",r,1),a(c.decorators,l,"decorators",n,1),a(c.computed,l,"computed",s),a(c.static,l,"static",i),l},t.classBody=function(e){const t={type:"ClassBody",body:e},r=o.ClassBody;return a(r.body,t,"body",e,1),t},t.classDeclaration=function(e=null,t=null,r,n=null){const s={type:"ClassDeclaration",id:e,superClass:t,body:r,decorators:n},i=o.ClassDeclaration;return a(i.id,s,"id",e,1),a(i.superClass,s,"superClass",t,1),a(i.body,s,"body",r,1),a(i.decorators,s,"decorators",n,1),s},t.classExpression=function(e=null,t=null,r,n=null){const s={type:"ClassExpression",id:e,superClass:t,body:r,decorators:n},i=o.ClassExpression;return a(i.id,s,"id",e,1),a(i.superClass,s,"superClass",t,1),a(i.body,s,"body",r,1),a(i.decorators,s,"decorators",n,1),s},t.classImplements=function(e,t=null){const r={type:"ClassImplements",id:e,typeParameters:t},n=o.ClassImplements;return a(n.id,r,"id",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.classMethod=function(e="method",t,r,n,s=!1,i=!1,l=!1,c=!1){const p={type:"ClassMethod",kind:e,key:t,params:r,body:n,computed:s,static:i,generator:l,async:c},u=o.ClassMethod;return a(u.kind,p,"kind",e),a(u.key,p,"key",t,1),a(u.params,p,"params",r,1),a(u.body,p,"body",n,1),a(u.computed,p,"computed",s),a(u.static,p,"static",i),a(u.generator,p,"generator",l),a(u.async,p,"async",c),p},t.classPrivateMethod=function(e="method",t,r,n,s=!1){const i={type:"ClassPrivateMethod",kind:e,key:t,params:r,body:n,static:s},l=o.ClassPrivateMethod;return a(l.kind,i,"kind",e),a(l.key,i,"key",t,1),a(l.params,i,"params",r,1),a(l.body,i,"body",n,1),a(l.static,i,"static",s),i},t.classPrivateProperty=function(e,t=null,r=null,n=!1){const s={type:"ClassPrivateProperty",key:e,value:t,decorators:r,static:n},i=o.ClassPrivateProperty;return a(i.key,s,"key",e,1),a(i.value,s,"value",t,1),a(i.decorators,s,"decorators",r,1),a(i.static,s,"static",n),s},t.classProperty=function(e,t=null,r=null,n=null,s=!1,i=!1){const l={type:"ClassProperty",key:e,value:t,typeAnnotation:r,decorators:n,computed:s,static:i},c=o.ClassProperty;return a(c.key,l,"key",e,1),a(c.value,l,"value",t,1),a(c.typeAnnotation,l,"typeAnnotation",r,1),a(c.decorators,l,"decorators",n,1),a(c.computed,l,"computed",s),a(c.static,l,"static",i),l},t.conditionalExpression=function(e,t,r){const n={type:"ConditionalExpression",test:e,consequent:t,alternate:r},s=o.ConditionalExpression;return a(s.test,n,"test",e,1),a(s.consequent,n,"consequent",t,1),a(s.alternate,n,"alternate",r,1),n},t.continueStatement=function(e=null){const t={type:"ContinueStatement",label:e},r=o.ContinueStatement;return a(r.label,t,"label",e,1),t},t.debuggerStatement=function(){return{type:"DebuggerStatement"}},t.decimalLiteral=function(e){const t={type:"DecimalLiteral",value:e},r=o.DecimalLiteral;return a(r.value,t,"value",e),t},t.declareClass=function(e,t=null,r=null,n){const s={type:"DeclareClass",id:e,typeParameters:t,extends:r,body:n},i=o.DeclareClass;return a(i.id,s,"id",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.extends,s,"extends",r,1),a(i.body,s,"body",n,1),s},t.declareExportAllDeclaration=function(e,t=null){const r={type:"DeclareExportAllDeclaration",source:e,attributes:t},n=o.DeclareExportAllDeclaration;return a(n.source,r,"source",e,1),a(n.attributes,r,"attributes",t,1),r},t.declareExportDeclaration=function(e=null,t=null,r=null,n=null){const s={type:"DeclareExportDeclaration",declaration:e,specifiers:t,source:r,attributes:n},i=o.DeclareExportDeclaration;return a(i.declaration,s,"declaration",e,1),a(i.specifiers,s,"specifiers",t,1),a(i.source,s,"source",r,1),a(i.attributes,s,"attributes",n,1),s},t.declareFunction=function(e){const t={type:"DeclareFunction",id:e},r=o.DeclareFunction;return a(r.id,t,"id",e,1),t},t.declareInterface=function(e,t=null,r=null,n){const s={type:"DeclareInterface",id:e,typeParameters:t,extends:r,body:n},i=o.DeclareInterface;return a(i.id,s,"id",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.extends,s,"extends",r,1),a(i.body,s,"body",n,1),s},t.declareModule=function(e,t,r=null){const n={type:"DeclareModule",id:e,body:t,kind:r},s=o.DeclareModule;return a(s.id,n,"id",e,1),a(s.body,n,"body",t,1),a(s.kind,n,"kind",r),n},t.declareModuleExports=function(e){const t={type:"DeclareModuleExports",typeAnnotation:e},r=o.DeclareModuleExports;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.declareOpaqueType=function(e,t=null,r=null){const n={type:"DeclareOpaqueType",id:e,typeParameters:t,supertype:r},s=o.DeclareOpaqueType;return a(s.id,n,"id",e,1),a(s.typeParameters,n,"typeParameters",t,1),a(s.supertype,n,"supertype",r,1),n},t.declareTypeAlias=function(e,t=null,r){const n={type:"DeclareTypeAlias",id:e,typeParameters:t,right:r},s=o.DeclareTypeAlias;return a(s.id,n,"id",e,1),a(s.typeParameters,n,"typeParameters",t,1),a(s.right,n,"right",r,1),n},t.declareVariable=function(e){const t={type:"DeclareVariable",id:e},r=o.DeclareVariable;return a(r.id,t,"id",e,1),t},t.declaredPredicate=function(e){const t={type:"DeclaredPredicate",value:e},r=o.DeclaredPredicate;return a(r.value,t,"value",e,1),t},t.decorator=function(e){const t={type:"Decorator",expression:e},r=o.Decorator;return a(r.expression,t,"expression",e,1),t},t.directive=function(e){const t={type:"Directive",value:e},r=o.Directive;return a(r.value,t,"value",e,1),t},t.directiveLiteral=function(e){const t={type:"DirectiveLiteral",value:e},r=o.DirectiveLiteral;return a(r.value,t,"value",e),t},t.doExpression=function(e,t=!1){const r={type:"DoExpression",body:e,async:t},n=o.DoExpression;return a(n.body,r,"body",e,1),a(n.async,r,"async",t),r},t.doWhileStatement=function(e,t){const r={type:"DoWhileStatement",test:e,body:t},n=o.DoWhileStatement;return a(n.test,r,"test",e,1),a(n.body,r,"body",t,1),r},t.emptyStatement=function(){return{type:"EmptyStatement"}},t.emptyTypeAnnotation=function(){return{type:"EmptyTypeAnnotation"}},t.enumBooleanBody=function(e){const t={type:"EnumBooleanBody",members:e,explicitType:null,hasUnknownMembers:null},r=o.EnumBooleanBody;return a(r.members,t,"members",e,1),t},t.enumBooleanMember=function(e){const t={type:"EnumBooleanMember",id:e,init:null},r=o.EnumBooleanMember;return a(r.id,t,"id",e,1),t},t.enumDeclaration=function(e,t){const r={type:"EnumDeclaration",id:e,body:t},n=o.EnumDeclaration;return a(n.id,r,"id",e,1),a(n.body,r,"body",t,1),r},t.enumDefaultedMember=function(e){const t={type:"EnumDefaultedMember",id:e},r=o.EnumDefaultedMember;return a(r.id,t,"id",e,1),t},t.enumNumberBody=function(e){const t={type:"EnumNumberBody",members:e,explicitType:null,hasUnknownMembers:null},r=o.EnumNumberBody;return a(r.members,t,"members",e,1),t},t.enumNumberMember=function(e,t){const r={type:"EnumNumberMember",id:e,init:t},n=o.EnumNumberMember;return a(n.id,r,"id",e,1),a(n.init,r,"init",t,1),r},t.enumStringBody=function(e){const t={type:"EnumStringBody",members:e,explicitType:null,hasUnknownMembers:null},r=o.EnumStringBody;return a(r.members,t,"members",e,1),t},t.enumStringMember=function(e,t){const r={type:"EnumStringMember",id:e,init:t},n=o.EnumStringMember;return a(n.id,r,"id",e,1),a(n.init,r,"init",t,1),r},t.enumSymbolBody=function(e){const t={type:"EnumSymbolBody",members:e,hasUnknownMembers:null},r=o.EnumSymbolBody;return a(r.members,t,"members",e,1),t},t.existsTypeAnnotation=function(){return{type:"ExistsTypeAnnotation"}},t.exportAllDeclaration=function(e){const t={type:"ExportAllDeclaration",source:e},r=o.ExportAllDeclaration;return a(r.source,t,"source",e,1),t},t.exportDefaultDeclaration=function(e){const t={type:"ExportDefaultDeclaration",declaration:e},r=o.ExportDefaultDeclaration;return a(r.declaration,t,"declaration",e,1),t},t.exportDefaultSpecifier=function(e){const t={type:"ExportDefaultSpecifier",exported:e},r=o.ExportDefaultSpecifier;return a(r.exported,t,"exported",e,1),t},t.exportNamedDeclaration=function(e=null,t=[],r=null){const n={type:"ExportNamedDeclaration",declaration:e,specifiers:t,source:r},s=o.ExportNamedDeclaration;return a(s.declaration,n,"declaration",e,1),a(s.specifiers,n,"specifiers",t,1),a(s.source,n,"source",r,1),n},t.exportNamespaceSpecifier=function(e){const t={type:"ExportNamespaceSpecifier",exported:e},r=o.ExportNamespaceSpecifier;return a(r.exported,t,"exported",e,1),t},t.exportSpecifier=function(e,t){const r={type:"ExportSpecifier",local:e,exported:t},n=o.ExportSpecifier;return a(n.local,r,"local",e,1),a(n.exported,r,"exported",t,1),r},t.expressionStatement=function(e){const t={type:"ExpressionStatement",expression:e},r=o.ExpressionStatement;return a(r.expression,t,"expression",e,1),t},t.file=function(e,t=null,r=null){const n={type:"File",program:e,comments:t,tokens:r},s=o.File;return a(s.program,n,"program",e,1),a(s.comments,n,"comments",t,1),a(s.tokens,n,"tokens",r),n},t.forInStatement=function(e,t,r){const n={type:"ForInStatement",left:e,right:t,body:r},s=o.ForInStatement;return a(s.left,n,"left",e,1),a(s.right,n,"right",t,1),a(s.body,n,"body",r,1),n},t.forOfStatement=function(e,t,r,n=!1){const s={type:"ForOfStatement",left:e,right:t,body:r,await:n},i=o.ForOfStatement;return a(i.left,s,"left",e,1),a(i.right,s,"right",t,1),a(i.body,s,"body",r,1),a(i.await,s,"await",n),s},t.forStatement=function(e=null,t=null,r=null,n){const s={type:"ForStatement",init:e,test:t,update:r,body:n},i=o.ForStatement;return a(i.init,s,"init",e,1),a(i.test,s,"test",t,1),a(i.update,s,"update",r,1),a(i.body,s,"body",n,1),s},t.functionDeclaration=function(e=null,t,r,n=!1,s=!1){const i={type:"FunctionDeclaration",id:e,params:t,body:r,generator:n,async:s},l=o.FunctionDeclaration;return a(l.id,i,"id",e,1),a(l.params,i,"params",t,1),a(l.body,i,"body",r,1),a(l.generator,i,"generator",n),a(l.async,i,"async",s),i},t.functionExpression=function(e=null,t,r,n=!1,s=!1){const i={type:"FunctionExpression",id:e,params:t,body:r,generator:n,async:s},l=o.FunctionExpression;return a(l.id,i,"id",e,1),a(l.params,i,"params",t,1),a(l.body,i,"body",r,1),a(l.generator,i,"generator",n),a(l.async,i,"async",s),i},t.functionTypeAnnotation=function(e=null,t,r=null,n){const s={type:"FunctionTypeAnnotation",typeParameters:e,params:t,rest:r,returnType:n},i=o.FunctionTypeAnnotation;return a(i.typeParameters,s,"typeParameters",e,1),a(i.params,s,"params",t,1),a(i.rest,s,"rest",r,1),a(i.returnType,s,"returnType",n,1),s},t.functionTypeParam=function(e=null,t){const r={type:"FunctionTypeParam",name:e,typeAnnotation:t},n=o.FunctionTypeParam;return a(n.name,r,"name",e,1),a(n.typeAnnotation,r,"typeAnnotation",t,1),r},t.genericTypeAnnotation=function(e,t=null){const r={type:"GenericTypeAnnotation",id:e,typeParameters:t},n=o.GenericTypeAnnotation;return a(n.id,r,"id",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.identifier=function(e){const t={type:"Identifier",name:e},r=o.Identifier;return a(r.name,t,"name",e),t},t.ifStatement=function(e,t,r=null){const n={type:"IfStatement",test:e,consequent:t,alternate:r},s=o.IfStatement;return a(s.test,n,"test",e,1),a(s.consequent,n,"consequent",t,1),a(s.alternate,n,"alternate",r,1),n},t.import=function(){return{type:"Import"}},t.importAttribute=function(e,t){const r={type:"ImportAttribute",key:e,value:t},n=o.ImportAttribute;return a(n.key,r,"key",e,1),a(n.value,r,"value",t,1),r},t.importDeclaration=function(e,t){const r={type:"ImportDeclaration",specifiers:e,source:t},n=o.ImportDeclaration;return a(n.specifiers,r,"specifiers",e,1),a(n.source,r,"source",t,1),r},t.importDefaultSpecifier=function(e){const t={type:"ImportDefaultSpecifier",local:e},r=o.ImportDefaultSpecifier;return a(r.local,t,"local",e,1),t},t.importExpression=function(e,t=null){const r={type:"ImportExpression",source:e,options:t},n=o.ImportExpression;return a(n.source,r,"source",e,1),a(n.options,r,"options",t,1),r},t.importNamespaceSpecifier=function(e){const t={type:"ImportNamespaceSpecifier",local:e},r=o.ImportNamespaceSpecifier;return a(r.local,t,"local",e,1),t},t.importSpecifier=function(e,t){const r={type:"ImportSpecifier",local:e,imported:t},n=o.ImportSpecifier;return a(n.local,r,"local",e,1),a(n.imported,r,"imported",t,1),r},t.indexedAccessType=function(e,t){const r={type:"IndexedAccessType",objectType:e,indexType:t},n=o.IndexedAccessType;return a(n.objectType,r,"objectType",e,1),a(n.indexType,r,"indexType",t,1),r},t.inferredPredicate=function(){return{type:"InferredPredicate"}},t.interfaceDeclaration=function(e,t=null,r=null,n){const s={type:"InterfaceDeclaration",id:e,typeParameters:t,extends:r,body:n},i=o.InterfaceDeclaration;return a(i.id,s,"id",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.extends,s,"extends",r,1),a(i.body,s,"body",n,1),s},t.interfaceExtends=function(e,t=null){const r={type:"InterfaceExtends",id:e,typeParameters:t},n=o.InterfaceExtends;return a(n.id,r,"id",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.interfaceTypeAnnotation=function(e=null,t){const r={type:"InterfaceTypeAnnotation",extends:e,body:t},n=o.InterfaceTypeAnnotation;return a(n.extends,r,"extends",e,1),a(n.body,r,"body",t,1),r},t.interpreterDirective=function(e){const t={type:"InterpreterDirective",value:e},r=o.InterpreterDirective;return a(r.value,t,"value",e),t},t.intersectionTypeAnnotation=function(e){const t={type:"IntersectionTypeAnnotation",types:e},r=o.IntersectionTypeAnnotation;return a(r.types,t,"types",e,1),t},t.jSXAttribute=t.jsxAttribute=function(e,t=null){const r={type:"JSXAttribute",name:e,value:t},n=o.JSXAttribute;return a(n.name,r,"name",e,1),a(n.value,r,"value",t,1),r},t.jSXClosingElement=t.jsxClosingElement=function(e){const t={type:"JSXClosingElement",name:e},r=o.JSXClosingElement;return a(r.name,t,"name",e,1),t},t.jSXClosingFragment=t.jsxClosingFragment=function(){return{type:"JSXClosingFragment"}},t.jSXElement=t.jsxElement=function(e,t=null,r,n=null){const s={type:"JSXElement",openingElement:e,closingElement:t,children:r,selfClosing:n},i=o.JSXElement;return a(i.openingElement,s,"openingElement",e,1),a(i.closingElement,s,"closingElement",t,1),a(i.children,s,"children",r,1),a(i.selfClosing,s,"selfClosing",n),s},t.jSXEmptyExpression=t.jsxEmptyExpression=function(){return{type:"JSXEmptyExpression"}},t.jSXExpressionContainer=t.jsxExpressionContainer=function(e){const t={type:"JSXExpressionContainer",expression:e},r=o.JSXExpressionContainer;return a(r.expression,t,"expression",e,1),t},t.jSXFragment=t.jsxFragment=function(e,t,r){const n={type:"JSXFragment",openingFragment:e,closingFragment:t,children:r},s=o.JSXFragment;return a(s.openingFragment,n,"openingFragment",e,1),a(s.closingFragment,n,"closingFragment",t,1),a(s.children,n,"children",r,1),n},t.jSXIdentifier=t.jsxIdentifier=function(e){const t={type:"JSXIdentifier",name:e},r=o.JSXIdentifier;return a(r.name,t,"name",e),t},t.jSXMemberExpression=t.jsxMemberExpression=function(e,t){const r={type:"JSXMemberExpression",object:e,property:t},n=o.JSXMemberExpression;return a(n.object,r,"object",e,1),a(n.property,r,"property",t,1),r},t.jSXNamespacedName=t.jsxNamespacedName=function(e,t){const r={type:"JSXNamespacedName",namespace:e,name:t},n=o.JSXNamespacedName;return a(n.namespace,r,"namespace",e,1),a(n.name,r,"name",t,1),r},t.jSXOpeningElement=t.jsxOpeningElement=function(e,t,r=!1){const n={type:"JSXOpeningElement",name:e,attributes:t,selfClosing:r},s=o.JSXOpeningElement;return a(s.name,n,"name",e,1),a(s.attributes,n,"attributes",t,1),a(s.selfClosing,n,"selfClosing",r),n},t.jSXOpeningFragment=t.jsxOpeningFragment=function(){return{type:"JSXOpeningFragment"}},t.jSXSpreadAttribute=t.jsxSpreadAttribute=function(e){const t={type:"JSXSpreadAttribute",argument:e},r=o.JSXSpreadAttribute;return a(r.argument,t,"argument",e,1),t},t.jSXSpreadChild=t.jsxSpreadChild=function(e){const t={type:"JSXSpreadChild",expression:e},r=o.JSXSpreadChild;return a(r.expression,t,"expression",e,1),t},t.jSXText=t.jsxText=function(e){const t={type:"JSXText",value:e},r=o.JSXText;return a(r.value,t,"value",e),t},t.labeledStatement=function(e,t){const r={type:"LabeledStatement",label:e,body:t},n=o.LabeledStatement;return a(n.label,r,"label",e,1),a(n.body,r,"body",t,1),r},t.logicalExpression=function(e,t,r){const n={type:"LogicalExpression",operator:e,left:t,right:r},s=o.LogicalExpression;return a(s.operator,n,"operator",e),a(s.left,n,"left",t,1),a(s.right,n,"right",r,1),n},t.memberExpression=function(e,t,r=!1,n=null){const s={type:"MemberExpression",object:e,property:t,computed:r,optional:n},i=o.MemberExpression;return a(i.object,s,"object",e,1),a(i.property,s,"property",t,1),a(i.computed,s,"computed",r),a(i.optional,s,"optional",n),s},t.metaProperty=function(e,t){const r={type:"MetaProperty",meta:e,property:t},n=o.MetaProperty;return a(n.meta,r,"meta",e,1),a(n.property,r,"property",t,1),r},t.mixedTypeAnnotation=function(){return{type:"MixedTypeAnnotation"}},t.moduleExpression=function(e){const t={type:"ModuleExpression",body:e},r=o.ModuleExpression;return a(r.body,t,"body",e,1),t},t.newExpression=function(e,t){const r={type:"NewExpression",callee:e,arguments:t},n=o.NewExpression;return a(n.callee,r,"callee",e,1),a(n.arguments,r,"arguments",t,1),r},t.noop=function(){return{type:"Noop"}},t.nullLiteral=function(){return{type:"NullLiteral"}},t.nullLiteralTypeAnnotation=function(){return{type:"NullLiteralTypeAnnotation"}},t.nullableTypeAnnotation=function(e){const t={type:"NullableTypeAnnotation",typeAnnotation:e},r=o.NullableTypeAnnotation;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.numberLiteral=function(e){return(0,s.default)("NumberLiteral","NumericLiteral","The node type "),l(e)},t.numberLiteralTypeAnnotation=function(e){const t={type:"NumberLiteralTypeAnnotation",value:e},r=o.NumberLiteralTypeAnnotation;return a(r.value,t,"value",e),t},t.numberTypeAnnotation=function(){return{type:"NumberTypeAnnotation"}},t.numericLiteral=l,t.objectExpression=function(e){const t={type:"ObjectExpression",properties:e},r=o.ObjectExpression;return a(r.properties,t,"properties",e,1),t},t.objectMethod=function(e="method",t,r,n,s=!1,i=!1,l=!1){const c={type:"ObjectMethod",kind:e,key:t,params:r,body:n,computed:s,generator:i,async:l},p=o.ObjectMethod;return a(p.kind,c,"kind",e),a(p.key,c,"key",t,1),a(p.params,c,"params",r,1),a(p.body,c,"body",n,1),a(p.computed,c,"computed",s),a(p.generator,c,"generator",i),a(p.async,c,"async",l),c},t.objectPattern=function(e){const t={type:"ObjectPattern",properties:e},r=o.ObjectPattern;return a(r.properties,t,"properties",e,1),t},t.objectProperty=function(e,t,r=!1,n=!1,s=null){const i={type:"ObjectProperty",key:e,value:t,computed:r,shorthand:n,decorators:s},l=o.ObjectProperty;return a(l.key,i,"key",e,1),a(l.value,i,"value",t,1),a(l.computed,i,"computed",r),a(l.shorthand,i,"shorthand",n),a(l.decorators,i,"decorators",s,1),i},t.objectTypeAnnotation=function(e,t=[],r=[],n=[],s=!1){const i={type:"ObjectTypeAnnotation",properties:e,indexers:t,callProperties:r,internalSlots:n,exact:s},l=o.ObjectTypeAnnotation;return a(l.properties,i,"properties",e,1),a(l.indexers,i,"indexers",t,1),a(l.callProperties,i,"callProperties",r,1),a(l.internalSlots,i,"internalSlots",n,1),a(l.exact,i,"exact",s),i},t.objectTypeCallProperty=function(e){const t={type:"ObjectTypeCallProperty",value:e,static:null},r=o.ObjectTypeCallProperty;return a(r.value,t,"value",e,1),t},t.objectTypeIndexer=function(e=null,t,r,n=null){const s={type:"ObjectTypeIndexer",id:e,key:t,value:r,variance:n,static:null},i=o.ObjectTypeIndexer;return a(i.id,s,"id",e,1),a(i.key,s,"key",t,1),a(i.value,s,"value",r,1),a(i.variance,s,"variance",n,1),s},t.objectTypeInternalSlot=function(e,t,r,n,s){const i={type:"ObjectTypeInternalSlot",id:e,value:t,optional:r,static:n,method:s},l=o.ObjectTypeInternalSlot;return a(l.id,i,"id",e,1),a(l.value,i,"value",t,1),a(l.optional,i,"optional",r),a(l.static,i,"static",n),a(l.method,i,"method",s),i},t.objectTypeProperty=function(e,t,r=null){const n={type:"ObjectTypeProperty",key:e,value:t,variance:r,kind:null,method:null,optional:null,proto:null,static:null},s=o.ObjectTypeProperty;return a(s.key,n,"key",e,1),a(s.value,n,"value",t,1),a(s.variance,n,"variance",r,1),n},t.objectTypeSpreadProperty=function(e){const t={type:"ObjectTypeSpreadProperty",argument:e},r=o.ObjectTypeSpreadProperty;return a(r.argument,t,"argument",e,1),t},t.opaqueType=function(e,t=null,r=null,n){const s={type:"OpaqueType",id:e,typeParameters:t,supertype:r,impltype:n},i=o.OpaqueType;return a(i.id,s,"id",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.supertype,s,"supertype",r,1),a(i.impltype,s,"impltype",n,1),s},t.optionalCallExpression=function(e,t,r){const n={type:"OptionalCallExpression",callee:e,arguments:t,optional:r},s=o.OptionalCallExpression;return a(s.callee,n,"callee",e,1),a(s.arguments,n,"arguments",t,1),a(s.optional,n,"optional",r),n},t.optionalIndexedAccessType=function(e,t){const r={type:"OptionalIndexedAccessType",objectType:e,indexType:t,optional:null},n=o.OptionalIndexedAccessType;return a(n.objectType,r,"objectType",e,1),a(n.indexType,r,"indexType",t,1),r},t.optionalMemberExpression=function(e,t,r=!1,n){const s={type:"OptionalMemberExpression",object:e,property:t,computed:r,optional:n},i=o.OptionalMemberExpression;return a(i.object,s,"object",e,1),a(i.property,s,"property",t,1),a(i.computed,s,"computed",r),a(i.optional,s,"optional",n),s},t.parenthesizedExpression=function(e){const t={type:"ParenthesizedExpression",expression:e},r=o.ParenthesizedExpression;return a(r.expression,t,"expression",e,1),t},t.pipelineBareFunction=function(e){const t={type:"PipelineBareFunction",callee:e},r=o.PipelineBareFunction;return a(r.callee,t,"callee",e,1),t},t.pipelinePrimaryTopicReference=function(){return{type:"PipelinePrimaryTopicReference"}},t.pipelineTopicExpression=function(e){const t={type:"PipelineTopicExpression",expression:e},r=o.PipelineTopicExpression;return a(r.expression,t,"expression",e,1),t},t.placeholder=function(e,t){const r={type:"Placeholder",expectedNode:e,name:t},n=o.Placeholder;return a(n.expectedNode,r,"expectedNode",e),a(n.name,r,"name",t,1),r},t.privateName=function(e){const t={type:"PrivateName",id:e},r=o.PrivateName;return a(r.id,t,"id",e,1),t},t.program=function(e,t=[],r="script",n=null){const s={type:"Program",body:e,directives:t,sourceType:r,interpreter:n},i=o.Program;return a(i.body,s,"body",e,1),a(i.directives,s,"directives",t,1),a(i.sourceType,s,"sourceType",r),a(i.interpreter,s,"interpreter",n,1),s},t.qualifiedTypeIdentifier=function(e,t){const r={type:"QualifiedTypeIdentifier",id:e,qualification:t},n=o.QualifiedTypeIdentifier;return a(n.id,r,"id",e,1),a(n.qualification,r,"qualification",t,1),r},t.recordExpression=function(e){const t={type:"RecordExpression",properties:e},r=o.RecordExpression;return a(r.properties,t,"properties",e,1),t},t.regExpLiteral=c,t.regexLiteral=function(e,t=""){return(0,s.default)("RegexLiteral","RegExpLiteral","The node type "),c(e,t)},t.restElement=p,t.restProperty=function(e){return(0,s.default)("RestProperty","RestElement","The node type "),p(e)},t.returnStatement=function(e=null){const t={type:"ReturnStatement",argument:e},r=o.ReturnStatement;return a(r.argument,t,"argument",e,1),t},t.sequenceExpression=function(e){const t={type:"SequenceExpression",expressions:e},r=o.SequenceExpression;return a(r.expressions,t,"expressions",e,1),t},t.spreadElement=u,t.spreadProperty=function(e){return(0,s.default)("SpreadProperty","SpreadElement","The node type "),u(e)},t.staticBlock=function(e){const t={type:"StaticBlock",body:e},r=o.StaticBlock;return a(r.body,t,"body",e,1),t},t.stringLiteral=function(e){const t={type:"StringLiteral",value:e},r=o.StringLiteral;return a(r.value,t,"value",e),t},t.stringLiteralTypeAnnotation=function(e){const t={type:"StringLiteralTypeAnnotation",value:e},r=o.StringLiteralTypeAnnotation;return a(r.value,t,"value",e),t},t.stringTypeAnnotation=function(){return{type:"StringTypeAnnotation"}},t.super=function(){return{type:"Super"}},t.switchCase=function(e=null,t){const r={type:"SwitchCase",test:e,consequent:t},n=o.SwitchCase;return a(n.test,r,"test",e,1),a(n.consequent,r,"consequent",t,1),r},t.switchStatement=function(e,t){const r={type:"SwitchStatement",discriminant:e,cases:t},n=o.SwitchStatement;return a(n.discriminant,r,"discriminant",e,1),a(n.cases,r,"cases",t,1),r},t.symbolTypeAnnotation=function(){return{type:"SymbolTypeAnnotation"}},t.taggedTemplateExpression=function(e,t){const r={type:"TaggedTemplateExpression",tag:e,quasi:t},n=o.TaggedTemplateExpression;return a(n.tag,r,"tag",e,1),a(n.quasi,r,"quasi",t,1),r},t.templateElement=function(e,t=!1){const r={type:"TemplateElement",value:e,tail:t},n=o.TemplateElement;return a(n.value,r,"value",e),a(n.tail,r,"tail",t),r},t.templateLiteral=function(e,t){const r={type:"TemplateLiteral",quasis:e,expressions:t},n=o.TemplateLiteral;return a(n.quasis,r,"quasis",e,1),a(n.expressions,r,"expressions",t,1),r},t.thisExpression=function(){return{type:"ThisExpression"}},t.thisTypeAnnotation=function(){return{type:"ThisTypeAnnotation"}},t.throwStatement=function(e){const t={type:"ThrowStatement",argument:e},r=o.ThrowStatement;return a(r.argument,t,"argument",e,1),t},t.topicReference=function(){return{type:"TopicReference"}},t.tryStatement=function(e,t=null,r=null){const n={type:"TryStatement",block:e,handler:t,finalizer:r},s=o.TryStatement;return a(s.block,n,"block",e,1),a(s.handler,n,"handler",t,1),a(s.finalizer,n,"finalizer",r,1),n},t.tSAnyKeyword=t.tsAnyKeyword=function(){return{type:"TSAnyKeyword"}},t.tSArrayType=t.tsArrayType=function(e){const t={type:"TSArrayType",elementType:e},r=o.TSArrayType;return a(r.elementType,t,"elementType",e,1),t},t.tSAsExpression=t.tsAsExpression=function(e,t){const r={type:"TSAsExpression",expression:e,typeAnnotation:t},n=o.TSAsExpression;return a(n.expression,r,"expression",e,1),a(n.typeAnnotation,r,"typeAnnotation",t,1),r},t.tSBigIntKeyword=t.tsBigIntKeyword=function(){return{type:"TSBigIntKeyword"}},t.tSBooleanKeyword=t.tsBooleanKeyword=function(){return{type:"TSBooleanKeyword"}},t.tSCallSignatureDeclaration=t.tsCallSignatureDeclaration=function(e=null,t,r=null){const n={type:"TSCallSignatureDeclaration",typeParameters:e,parameters:t,typeAnnotation:r},s=o.TSCallSignatureDeclaration;return a(s.typeParameters,n,"typeParameters",e,1),a(s.parameters,n,"parameters",t,1),a(s.typeAnnotation,n,"typeAnnotation",r,1),n},t.tSConditionalType=t.tsConditionalType=function(e,t,r,n){const s={type:"TSConditionalType",checkType:e,extendsType:t,trueType:r,falseType:n},i=o.TSConditionalType;return a(i.checkType,s,"checkType",e,1),a(i.extendsType,s,"extendsType",t,1),a(i.trueType,s,"trueType",r,1),a(i.falseType,s,"falseType",n,1),s},t.tSConstructSignatureDeclaration=t.tsConstructSignatureDeclaration=function(e=null,t,r=null){const n={type:"TSConstructSignatureDeclaration",typeParameters:e,parameters:t,typeAnnotation:r},s=o.TSConstructSignatureDeclaration;return a(s.typeParameters,n,"typeParameters",e,1),a(s.parameters,n,"parameters",t,1),a(s.typeAnnotation,n,"typeAnnotation",r,1),n},t.tSConstructorType=t.tsConstructorType=function(e=null,t,r=null){const n={type:"TSConstructorType",typeParameters:e,parameters:t,typeAnnotation:r},s=o.TSConstructorType;return a(s.typeParameters,n,"typeParameters",e,1),a(s.parameters,n,"parameters",t,1),a(s.typeAnnotation,n,"typeAnnotation",r,1),n},t.tSDeclareFunction=t.tsDeclareFunction=function(e=null,t=null,r,n=null){const s={type:"TSDeclareFunction",id:e,typeParameters:t,params:r,returnType:n},i=o.TSDeclareFunction;return a(i.id,s,"id",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.params,s,"params",r,1),a(i.returnType,s,"returnType",n,1),s},t.tSDeclareMethod=t.tsDeclareMethod=function(e=null,t,r=null,n,s=null){const i={type:"TSDeclareMethod",decorators:e,key:t,typeParameters:r,params:n,returnType:s},l=o.TSDeclareMethod;return a(l.decorators,i,"decorators",e,1),a(l.key,i,"key",t,1),a(l.typeParameters,i,"typeParameters",r,1),a(l.params,i,"params",n,1),a(l.returnType,i,"returnType",s,1),i},t.tSEnumBody=t.tsEnumBody=function(e){const t={type:"TSEnumBody",members:e},r=o.TSEnumBody;return a(r.members,t,"members",e,1),t},t.tSEnumDeclaration=t.tsEnumDeclaration=function(e,t){const r={type:"TSEnumDeclaration",id:e,members:t},n=o.TSEnumDeclaration;return a(n.id,r,"id",e,1),a(n.members,r,"members",t,1),r},t.tSEnumMember=t.tsEnumMember=function(e,t=null){const r={type:"TSEnumMember",id:e,initializer:t},n=o.TSEnumMember;return a(n.id,r,"id",e,1),a(n.initializer,r,"initializer",t,1),r},t.tSExportAssignment=t.tsExportAssignment=function(e){const t={type:"TSExportAssignment",expression:e},r=o.TSExportAssignment;return a(r.expression,t,"expression",e,1),t},t.tSExpressionWithTypeArguments=t.tsExpressionWithTypeArguments=function(e,t=null){const r={type:"TSExpressionWithTypeArguments",expression:e,typeParameters:t},n=o.TSExpressionWithTypeArguments;return a(n.expression,r,"expression",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.tSExternalModuleReference=t.tsExternalModuleReference=function(e){const t={type:"TSExternalModuleReference",expression:e},r=o.TSExternalModuleReference;return a(r.expression,t,"expression",e,1),t},t.tSFunctionType=t.tsFunctionType=function(e=null,t,r=null){const n={type:"TSFunctionType",typeParameters:e,parameters:t,typeAnnotation:r},s=o.TSFunctionType;return a(s.typeParameters,n,"typeParameters",e,1),a(s.parameters,n,"parameters",t,1),a(s.typeAnnotation,n,"typeAnnotation",r,1),n},t.tSImportEqualsDeclaration=t.tsImportEqualsDeclaration=function(e,t){const r={type:"TSImportEqualsDeclaration",id:e,moduleReference:t,isExport:null},n=o.TSImportEqualsDeclaration;return a(n.id,r,"id",e,1),a(n.moduleReference,r,"moduleReference",t,1),r},t.tSImportType=t.tsImportType=function(e,t=null,r=null){const n={type:"TSImportType",argument:e,qualifier:t,typeParameters:r},s=o.TSImportType;return a(s.argument,n,"argument",e,1),a(s.qualifier,n,"qualifier",t,1),a(s.typeParameters,n,"typeParameters",r,1),n},t.tSIndexSignature=t.tsIndexSignature=function(e,t=null){const r={type:"TSIndexSignature",parameters:e,typeAnnotation:t},n=o.TSIndexSignature;return a(n.parameters,r,"parameters",e,1),a(n.typeAnnotation,r,"typeAnnotation",t,1),r},t.tSIndexedAccessType=t.tsIndexedAccessType=function(e,t){const r={type:"TSIndexedAccessType",objectType:e,indexType:t},n=o.TSIndexedAccessType;return a(n.objectType,r,"objectType",e,1),a(n.indexType,r,"indexType",t,1),r},t.tSInferType=t.tsInferType=function(e){const t={type:"TSInferType",typeParameter:e},r=o.TSInferType;return a(r.typeParameter,t,"typeParameter",e,1),t},t.tSInstantiationExpression=t.tsInstantiationExpression=function(e,t=null){const r={type:"TSInstantiationExpression",expression:e,typeParameters:t},n=o.TSInstantiationExpression;return a(n.expression,r,"expression",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.tSInterfaceBody=t.tsInterfaceBody=function(e){const t={type:"TSInterfaceBody",body:e},r=o.TSInterfaceBody;return a(r.body,t,"body",e,1),t},t.tSInterfaceDeclaration=t.tsInterfaceDeclaration=function(e,t=null,r=null,n){const s={type:"TSInterfaceDeclaration",id:e,typeParameters:t,extends:r,body:n},i=o.TSInterfaceDeclaration;return a(i.id,s,"id",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.extends,s,"extends",r,1),a(i.body,s,"body",n,1),s},t.tSIntersectionType=t.tsIntersectionType=function(e){const t={type:"TSIntersectionType",types:e},r=o.TSIntersectionType;return a(r.types,t,"types",e,1),t},t.tSIntrinsicKeyword=t.tsIntrinsicKeyword=function(){return{type:"TSIntrinsicKeyword"}},t.tSLiteralType=t.tsLiteralType=function(e){const t={type:"TSLiteralType",literal:e},r=o.TSLiteralType;return a(r.literal,t,"literal",e,1),t},t.tSMappedType=t.tsMappedType=function(e,t=null,r=null){const n={type:"TSMappedType",typeParameter:e,typeAnnotation:t,nameType:r},s=o.TSMappedType;return a(s.typeParameter,n,"typeParameter",e,1),a(s.typeAnnotation,n,"typeAnnotation",t,1),a(s.nameType,n,"nameType",r,1),n},t.tSMethodSignature=t.tsMethodSignature=function(e,t=null,r,n=null){const s={type:"TSMethodSignature",key:e,typeParameters:t,parameters:r,typeAnnotation:n,kind:null},i=o.TSMethodSignature;return a(i.key,s,"key",e,1),a(i.typeParameters,s,"typeParameters",t,1),a(i.parameters,s,"parameters",r,1),a(i.typeAnnotation,s,"typeAnnotation",n,1),s},t.tSModuleBlock=t.tsModuleBlock=function(e){const t={type:"TSModuleBlock",body:e},r=o.TSModuleBlock;return a(r.body,t,"body",e,1),t},t.tSModuleDeclaration=t.tsModuleDeclaration=function(e,t){const r={type:"TSModuleDeclaration",id:e,body:t,kind:null},n=o.TSModuleDeclaration;return a(n.id,r,"id",e,1),a(n.body,r,"body",t,1),r},t.tSNamedTupleMember=t.tsNamedTupleMember=function(e,t,r=!1){const n={type:"TSNamedTupleMember",label:e,elementType:t,optional:r},s=o.TSNamedTupleMember;return a(s.label,n,"label",e,1),a(s.elementType,n,"elementType",t,1),a(s.optional,n,"optional",r),n},t.tSNamespaceExportDeclaration=t.tsNamespaceExportDeclaration=function(e){const t={type:"TSNamespaceExportDeclaration",id:e},r=o.TSNamespaceExportDeclaration;return a(r.id,t,"id",e,1),t},t.tSNeverKeyword=t.tsNeverKeyword=function(){return{type:"TSNeverKeyword"}},t.tSNonNullExpression=t.tsNonNullExpression=function(e){const t={type:"TSNonNullExpression",expression:e},r=o.TSNonNullExpression;return a(r.expression,t,"expression",e,1),t},t.tSNullKeyword=t.tsNullKeyword=function(){return{type:"TSNullKeyword"}},t.tSNumberKeyword=t.tsNumberKeyword=function(){return{type:"TSNumberKeyword"}},t.tSObjectKeyword=t.tsObjectKeyword=function(){return{type:"TSObjectKeyword"}},t.tSOptionalType=t.tsOptionalType=function(e){const t={type:"TSOptionalType",typeAnnotation:e},r=o.TSOptionalType;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.tSParameterProperty=t.tsParameterProperty=function(e){const t={type:"TSParameterProperty",parameter:e},r=o.TSParameterProperty;return a(r.parameter,t,"parameter",e,1),t},t.tSParenthesizedType=t.tsParenthesizedType=function(e){const t={type:"TSParenthesizedType",typeAnnotation:e},r=o.TSParenthesizedType;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.tSPropertySignature=t.tsPropertySignature=function(e,t=null){const r={type:"TSPropertySignature",key:e,typeAnnotation:t},n=o.TSPropertySignature;return a(n.key,r,"key",e,1),a(n.typeAnnotation,r,"typeAnnotation",t,1),r},t.tSQualifiedName=t.tsQualifiedName=function(e,t){const r={type:"TSQualifiedName",left:e,right:t},n=o.TSQualifiedName;return a(n.left,r,"left",e,1),a(n.right,r,"right",t,1),r},t.tSRestType=t.tsRestType=function(e){const t={type:"TSRestType",typeAnnotation:e},r=o.TSRestType;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.tSSatisfiesExpression=t.tsSatisfiesExpression=function(e,t){const r={type:"TSSatisfiesExpression",expression:e,typeAnnotation:t},n=o.TSSatisfiesExpression;return a(n.expression,r,"expression",e,1),a(n.typeAnnotation,r,"typeAnnotation",t,1),r},t.tSStringKeyword=t.tsStringKeyword=function(){return{type:"TSStringKeyword"}},t.tSSymbolKeyword=t.tsSymbolKeyword=function(){return{type:"TSSymbolKeyword"}},t.tSTemplateLiteralType=t.tsTemplateLiteralType=function(e,t){const r={type:"TSTemplateLiteralType",quasis:e,types:t},n=o.TSTemplateLiteralType;return a(n.quasis,r,"quasis",e,1),a(n.types,r,"types",t,1),r},t.tSThisType=t.tsThisType=function(){return{type:"TSThisType"}},t.tSTupleType=t.tsTupleType=function(e){const t={type:"TSTupleType",elementTypes:e},r=o.TSTupleType;return a(r.elementTypes,t,"elementTypes",e,1),t},t.tSTypeAliasDeclaration=t.tsTypeAliasDeclaration=function(e,t=null,r){const n={type:"TSTypeAliasDeclaration",id:e,typeParameters:t,typeAnnotation:r},s=o.TSTypeAliasDeclaration;return a(s.id,n,"id",e,1),a(s.typeParameters,n,"typeParameters",t,1),a(s.typeAnnotation,n,"typeAnnotation",r,1),n},t.tSTypeAnnotation=t.tsTypeAnnotation=function(e){const t={type:"TSTypeAnnotation",typeAnnotation:e},r=o.TSTypeAnnotation;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.tSTypeAssertion=t.tsTypeAssertion=function(e,t){const r={type:"TSTypeAssertion",typeAnnotation:e,expression:t},n=o.TSTypeAssertion;return a(n.typeAnnotation,r,"typeAnnotation",e,1),a(n.expression,r,"expression",t,1),r},t.tSTypeLiteral=t.tsTypeLiteral=function(e){const t={type:"TSTypeLiteral",members:e},r=o.TSTypeLiteral;return a(r.members,t,"members",e,1),t},t.tSTypeOperator=t.tsTypeOperator=function(e){const t={type:"TSTypeOperator",typeAnnotation:e,operator:null},r=o.TSTypeOperator;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.tSTypeParameter=t.tsTypeParameter=function(e=null,t=null,r){const n={type:"TSTypeParameter",constraint:e,default:t,name:r},s=o.TSTypeParameter;return a(s.constraint,n,"constraint",e,1),a(s.default,n,"default",t,1),a(s.name,n,"name",r),n},t.tSTypeParameterDeclaration=t.tsTypeParameterDeclaration=function(e){const t={type:"TSTypeParameterDeclaration",params:e},r=o.TSTypeParameterDeclaration;return a(r.params,t,"params",e,1),t},t.tSTypeParameterInstantiation=t.tsTypeParameterInstantiation=function(e){const t={type:"TSTypeParameterInstantiation",params:e},r=o.TSTypeParameterInstantiation;return a(r.params,t,"params",e,1),t},t.tSTypePredicate=t.tsTypePredicate=function(e,t=null,r=null){const n={type:"TSTypePredicate",parameterName:e,typeAnnotation:t,asserts:r},s=o.TSTypePredicate;return a(s.parameterName,n,"parameterName",e,1),a(s.typeAnnotation,n,"typeAnnotation",t,1),a(s.asserts,n,"asserts",r),n},t.tSTypeQuery=t.tsTypeQuery=function(e,t=null){const r={type:"TSTypeQuery",exprName:e,typeParameters:t},n=o.TSTypeQuery;return a(n.exprName,r,"exprName",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.tSTypeReference=t.tsTypeReference=function(e,t=null){const r={type:"TSTypeReference",typeName:e,typeParameters:t},n=o.TSTypeReference;return a(n.typeName,r,"typeName",e,1),a(n.typeParameters,r,"typeParameters",t,1),r},t.tSUndefinedKeyword=t.tsUndefinedKeyword=function(){return{type:"TSUndefinedKeyword"}},t.tSUnionType=t.tsUnionType=function(e){const t={type:"TSUnionType",types:e},r=o.TSUnionType;return a(r.types,t,"types",e,1),t},t.tSUnknownKeyword=t.tsUnknownKeyword=function(){return{type:"TSUnknownKeyword"}},t.tSVoidKeyword=t.tsVoidKeyword=function(){return{type:"TSVoidKeyword"}},t.tupleExpression=function(e=[]){const t={type:"TupleExpression",elements:e},r=o.TupleExpression;return a(r.elements,t,"elements",e,1),t},t.tupleTypeAnnotation=function(e){const t={type:"TupleTypeAnnotation",types:e},r=o.TupleTypeAnnotation;return a(r.types,t,"types",e,1),t},t.typeAlias=function(e,t=null,r){const n={type:"TypeAlias",id:e,typeParameters:t,right:r},s=o.TypeAlias;return a(s.id,n,"id",e,1),a(s.typeParameters,n,"typeParameters",t,1),a(s.right,n,"right",r,1),n},t.typeAnnotation=function(e){const t={type:"TypeAnnotation",typeAnnotation:e},r=o.TypeAnnotation;return a(r.typeAnnotation,t,"typeAnnotation",e,1),t},t.typeCastExpression=function(e,t){const r={type:"TypeCastExpression",expression:e,typeAnnotation:t},n=o.TypeCastExpression;return a(n.expression,r,"expression",e,1),a(n.typeAnnotation,r,"typeAnnotation",t,1),r},t.typeParameter=function(e=null,t=null,r=null){const n={type:"TypeParameter",bound:e,default:t,variance:r,name:null},s=o.TypeParameter;return a(s.bound,n,"bound",e,1),a(s.default,n,"default",t,1),a(s.variance,n,"variance",r,1),n},t.typeParameterDeclaration=function(e){const t={type:"TypeParameterDeclaration",params:e},r=o.TypeParameterDeclaration;return a(r.params,t,"params",e,1),t},t.typeParameterInstantiation=function(e){const t={type:"TypeParameterInstantiation",params:e},r=o.TypeParameterInstantiation;return a(r.params,t,"params",e,1),t},t.typeofTypeAnnotation=function(e){const t={type:"TypeofTypeAnnotation",argument:e},r=o.TypeofTypeAnnotation;return a(r.argument,t,"argument",e,1),t},t.unaryExpression=function(e,t,r=!0){const n={type:"UnaryExpression",operator:e,argument:t,prefix:r},s=o.UnaryExpression;return a(s.operator,n,"operator",e),a(s.argument,n,"argument",t,1),a(s.prefix,n,"prefix",r),n},t.unionTypeAnnotation=function(e){const t={type:"UnionTypeAnnotation",types:e},r=o.UnionTypeAnnotation;return a(r.types,t,"types",e,1),t},t.updateExpression=function(e,t,r=!1){const n={type:"UpdateExpression",operator:e,argument:t,prefix:r},s=o.UpdateExpression;return a(s.operator,n,"operator",e),a(s.argument,n,"argument",t,1),a(s.prefix,n,"prefix",r),n},t.v8IntrinsicIdentifier=function(e){const t={type:"V8IntrinsicIdentifier",name:e},r=o.V8IntrinsicIdentifier;return a(r.name,t,"name",e),t},t.variableDeclaration=function(e,t){const r={type:"VariableDeclaration",kind:e,declarations:t},n=o.VariableDeclaration;return a(n.kind,r,"kind",e),a(n.declarations,r,"declarations",t,1),r},t.variableDeclarator=function(e,t=null){const r={type:"VariableDeclarator",id:e,init:t},n=o.VariableDeclarator;return a(n.id,r,"id",e,1),a(n.init,r,"init",t,1),r},t.variance=function(e){const t={type:"Variance",kind:e},r=o.Variance;return a(r.kind,t,"kind",e),t},t.voidTypeAnnotation=function(){return{type:"VoidTypeAnnotation"}},t.whileStatement=function(e,t){const r={type:"WhileStatement",test:e,body:t},n=o.WhileStatement;return a(n.test,r,"test",e,1),a(n.body,r,"body",t,1),r},t.withStatement=function(e,t){const r={type:"WithStatement",object:e,body:t},n=o.WithStatement;return a(n.object,r,"object",e,1),a(n.body,r,"body",t,1),r},t.yieldExpression=function(e=null,t=!1){const r={type:"YieldExpression",argument:e,delegate:t},n=o.YieldExpression;return a(n.argument,r,"argument",e,1),a(n.delegate,r,"delegate",t),r};var n=r(7446),s=r(3762),i=r(7596);const{validateInternal:a}=n,{NODE_FIELDS:o}=i;function l(e){const t={type:"NumericLiteral",value:e},r=o.NumericLiteral;return a(r.value,t,"value",e),t}function c(e,t=""){const r={type:"RegExpLiteral",pattern:e,flags:t},n=o.RegExpLiteral;return a(n.pattern,r,"pattern",e),a(n.flags,r,"flags",t),r}function p(e){const t={type:"RestElement",argument:e},r=o.RestElement;return a(r.argument,t,"argument",e,1),t}function u(e){const t={type:"SpreadElement",argument:e},r=o.SpreadElement;return a(r.argument,t,"argument",e,1),t}},3310:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}function s(e,t,r,n,s,i,a){try{var o=e[i](a),l=o.value}catch(e){return void r(e)}o.done?t(l):Promise.resolve(l).then(n,s)}function i(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var a=e.apply(t,r);function o(e){s(a,n,i,o,l,"next",e)}function l(e){s(a,n,i,o,l,"throw",e)}o(void 0)}))}}Object.defineProperty(t,"__esModule",{value:!0}),t.forwardAsync=function(e,t){const r=n()(e);return o((e=>{const n=r[e];return t(n)}))},t.isAsync=void 0,t.isThenable=p,t.maybeAsync=function(e,t){return n()({sync(...r){const n=e.apply(this,r);if(p(n))throw new Error(t);return n},async(...t){return Promise.resolve(e.apply(this,t))}})},t.waitFor=t.onFirstPause=void 0;const a=n()((function*(e){return yield*e}));t.isAsync=n()({sync:()=>!1,errback:e=>e(null,!0)});const o=n()({sync:e=>e("sync"),async:(l=i((function*(e){return e("async")})),function(e){return l.apply(this,arguments)})});var l,c;function p(e){return!(!e||"object"!=typeof e&&"function"!=typeof e||!e.then||"function"!=typeof e.then)}t.onFirstPause=n()({name:"onFirstPause",arity:2,sync:function(e){return a.sync(e)},errback:function(e,t,r){let n=!1;a.errback(e,((e,t)=>{n=!0,r(e,t)})),n||t()}}),t.waitFor=n()({sync:e=>e,async:(c=i((function*(e){return e})),function(e){return c.apply(this,arguments)})})},3342:(e,t,r)=>{"use strict";function n(){const e=r(9971);return n=function(){return e},e}function s(){const e=r(7975);return s=function(){return e},e}function i(){const e=r(7833);return i=function(){return e},e}function a(){const e=r(2352);return a=function(){return e},e}function o(){const e=r(5913);return o=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function*(e,t,r,i){if(r=`${r||""}`,i){if("Program"===i.type)i=u(i,[],[]);else if("File"!==i.type)throw new Error("AST root must be a Program or File node");t.cloneInputAst&&(i=(0,p.default)(i))}else i=yield*(0,c.default)(e,t,r);let a=null;if(!1!==t.inputSourceMap){if("object"==typeof t.inputSourceMap&&(a=o().fromObject(t.inputSourceMap)),!a){const e=g(h,i);if(e)try{a=o().fromComment("//"+e)}catch(e){f("discarding unknown inline input sourcemap")}}if(!a){const e=g(m,i);if("string"==typeof t.filename&&e)try{const r=m.exec(e),i=n().readFileSync(s().resolve(s().dirname(t.filename),r[1]),"utf8");a=o().fromJSON(i)}catch(e){f("discarding unknown file input sourcemap",e)}else e&&f("discarding un-loadable file input sourcemap")}}return new l.default(t,{code:r,ast:i,inputMap:a})};var l=r(4797),c=r(7262),p=r(2315);const{file:u,traverseFast:d}=a(),f=i()("babel:transform:file"),h=/^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,.*$/,m=/^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/;function y(e,t,r){return t&&(t=t.filter((({value:t})=>!e.test(t)||(r=t,!1)))),[t,r]}function g(e,t){let r=null;return d(t,(t=>{[t.leadingComments,r]=y(e,t.leadingComments,r),[t.innerComments,r]=y(e,t.innerComments,r),[t.trailingComments,r]=y(e,t.trailingComments,r)})),r}},3347:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,n,s,i,a){const l=new Set,c={compatData:e,includes:t,excludes:r};for(const t in e)if(o(t,n,c))l.add(t);else if(a){const e=a.get(t);e&&l.add(e)}return null==s||s.forEach((e=>!r.has(e)&&l.add(e))),null==i||i.forEach((e=>!t.has(e)&&l.delete(e))),l},t.isRequired=o,t.targetsSupported=a;var n=r(5345),s=r(5196),i=r(6299);function a(e,t){const r=Object.keys(e);return 0!==r.length&&0===r.filter((r=>{const s=(0,i.getLowestImplementedVersion)(t,r);if(!s)return!0;const a=e[r];if((0,i.isUnreleasedVersion)(a,r))return!1;if((0,i.isUnreleasedVersion)(s,r))return!0;if(!n.valid(a.toString()))throw new Error(`Invalid version passed for target "${r}": "${a}". Versions must be in semver format (major.minor.patch)`);return n.gt((0,i.semverify)(s),a.toString())})).length}function o(e,t,{compatData:r=s,includes:n,excludes:i}={}){return!(null!=i&&i.has(e)||(null==n||!n.has(e))&&a(t,r[e]))}},3357:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){"function"==typeof t&&(t={enter:t});const{enter:n,exit:i}=t;s(e,n,i,r,[])};var n=r(9793);function s(e,t,r,i,a){const o=n.VISITOR_KEYS[e.type];if(o){t&&t(e,a,i);for(const n of o){const o=e[n];if(Array.isArray(o))for(let l=0;l<o.length;l++){const c=o[l];c&&(a.push({node:e,key:n,index:l}),s(c,t,r,i,a),a.pop())}else o&&(a.push({node:e,key:n}),s(o,t,r,i,a),a.pop())}r&&r(e,a,i)}}},3380:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionValidator=void 0;var n=r(8500);t.OptionValidator=class{constructor(e){this.descriptor=e}validateTopLevelOptions(e,t){const r=Object.keys(t);for(const t of Object.keys(e))if(!r.includes(t))throw new Error(this.formatMessage(`'${t}' is not a valid top-level option.\n- Did you mean '${(0,n.findSuggestion)(t,r)}'?`))}validateBooleanOption(e,t,r){return void 0===t?r:(this.invariant("boolean"==typeof t,`'${e}' option must be a boolean.`),t)}validateStringOption(e,t,r){return void 0===t?r:(this.invariant("string"==typeof t,`'${e}' option must be a string.`),t)}invariant(e,t){if(!e)throw new Error(this.formatMessage(t))}formatMessage(e){return`${this.descriptor}: ${e}`}}},3383:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addComment=function(e,t,r){s(this.node,e,t,r)},t.addComments=function(e,t){i(this.node,e,t)},t.shareCommentsWithSiblings=function(){if("string"==typeof this.key)return;const e=this.node;if(!e)return;const t=e.trailingComments,r=e.leadingComments;if(!t&&!r)return;const n=this.getSibling(this.key-1),s=this.getSibling(this.key+1),i=Boolean(n.node),o=Boolean(s.node);i&&(r&&n.addComments("trailing",a(r,n.node.trailingComments)),t&&!o&&n.addComments("trailing",t)),o&&(t&&s.addComments("leading",a(t,s.node.leadingComments)),r&&!i&&s.addComments("leading",r))};var n=r(2352);const{addComment:s,addComments:i}=n;function a(e,t){if(null==t||!t.length)return e;const r=new Set(t);return e.filter((e=>!r.has(e)))}},3422:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UPDATE_OPERATORS=t.UNARY_OPERATORS=t.STRING_UNARY_OPERATORS=t.STATEMENT_OR_BLOCK_KEYS=t.NUMBER_UNARY_OPERATORS=t.NUMBER_BINARY_OPERATORS=t.NOT_LOCAL_BINDING=t.LOGICAL_OPERATORS=t.INHERIT_KEYS=t.FOR_INIT_KEYS=t.FLATTENABLE_KEYS=t.EQUALITY_BINARY_OPERATORS=t.COMPARISON_BINARY_OPERATORS=t.COMMENT_KEYS=t.BOOLEAN_UNARY_OPERATORS=t.BOOLEAN_NUMBER_BINARY_OPERATORS=t.BOOLEAN_BINARY_OPERATORS=t.BLOCK_SCOPED_SYMBOL=t.BINARY_OPERATORS=t.ASSIGNMENT_OPERATORS=void 0,t.STATEMENT_OR_BLOCK_KEYS=["consequent","body","alternate"],t.FLATTENABLE_KEYS=["body","expressions"],t.FOR_INIT_KEYS=["left","init"],t.COMMENT_KEYS=["leadingComments","trailingComments","innerComments"];const r=t.LOGICAL_OPERATORS=["||","&&","??"],n=(t.UPDATE_OPERATORS=["++","--"],t.BOOLEAN_NUMBER_BINARY_OPERATORS=[">","<",">=","<="]),s=t.EQUALITY_BINARY_OPERATORS=["==","===","!=","!=="],i=t.COMPARISON_BINARY_OPERATORS=[...s,"in","instanceof"],a=t.BOOLEAN_BINARY_OPERATORS=[...i,...n],o=t.NUMBER_BINARY_OPERATORS=["-","/","%","*","**","&","|",">>",">>>","<<","^"],l=(t.BINARY_OPERATORS=["+",...o,...a,"|>"],t.ASSIGNMENT_OPERATORS=["=","+=",...o.map((e=>e+"=")),...r.map((e=>e+"="))],t.BOOLEAN_UNARY_OPERATORS=["delete","!"]),c=t.NUMBER_UNARY_OPERATORS=["+","-","~"],p=t.STRING_UNARY_OPERATORS=["typeof"];t.UNARY_OPERATORS=["void","throw",...l,...c,...p],t.INHERIT_KEYS={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]},t.BLOCK_SCOPED_SYMBOL=Symbol.for("var used to be block scoped"),t.NOT_LOCAL_BINDING=Symbol.for("should not be considered a local binding")},3437:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return n.COMMENT_KEYS.forEach((t=>{e[t]=null})),e};var n=r(3422)},3438:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){const{metadata:a,names:o}=function(e,t,r){let n="BABEL_TPL$";const i=t.join("");do{n="$$"+n}while(i.includes(n));const{names:a,code:o}=function(e,t){const r=[];let n=e[0];for(let s=1;s<e.length;s++){const i=`${t}${s-1}`;r.push(i),n+=i+e[s]}return{names:r,code:n}}(t,n);return{metadata:(0,s.default)(e,e.code(o),{parser:r.parser,placeholderWhitelist:new Set(a.concat(r.placeholderWhitelist?Array.from(r.placeholderWhitelist):[])),placeholderPattern:r.placeholderPattern,preserveComments:r.preserveComments,syntacticPlaceholders:r.syntacticPlaceholders}),names:a}}(e,t,r);return t=>{const r={};return t.forEach(((e,t)=>{r[o[t]]=e})),t=>{const s=(0,n.normalizeReplacements)(t);return s&&Object.keys(s).forEach((e=>{if(hasOwnProperty.call(r,e))throw new Error("Unexpected replacement overlap.")})),e.unwrap((0,i.default)(a,s?Object.assign(s,r):r))}}};var n=r(9815),s=r(4858),i=r(7427)},3534:function(e,t){!function(e){"use strict";function t(e,t){return e._indexes[t]}e.SetArray=class{constructor(){this._indexes={__proto__:null},this.array=[]}},e.get=t,e.pop=function(e){const{array:t,_indexes:r}=e;0!==t.length&&(r[t.pop()]=void 0)},e.put=function(e,r){const n=t(e,r);if(void 0!==n)return n;const{array:s,_indexes:i}=e,a=s.push(r);return i[r]=a-1},e.remove=function(e,r){const n=t(e,r);if(void 0===n)return;const{array:s,_indexes:i}=e;for(let e=n+1;e<s.length;e++){const t=s[e];s[e-1]=t,i[t]--}i[r]=void 0,s.pop()},Object.defineProperty(e,"__esModule",{value:!0})}(t)},3571:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(e===t)return!0;const r=n.PLACEHOLDERS_ALIAS[e];if(r)for(const e of r)if(t===e)return!0;return!1};var n=r(9793)},3599:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=class{constructor({identifier:e,scope:t,path:r,kind:n}){this.identifier=void 0,this.scope=void 0,this.path=void 0,this.kind=void 0,this.constantViolations=[],this.constant=!0,this.referencePaths=[],this.referenced=!1,this.references=0,this.identifier=e,this.scope=t,this.path=r,this.kind=n,"var"!==n&&"hoisted"!==n||!function(e){for(let{parentPath:t,key:r}=e;t;({parentPath:t,key:r}=t)){if(t.isFunctionParent())return!1;if(t.isWhile()||t.isForXStatement()||t.isForStatement()&&"body"===r)return!0}return!1}(r)||this.reassign(r),this.clearValue()}deoptValue(){this.clearValue(),this.hasDeoptedValue=!0}setValue(e){this.hasDeoptedValue||(this.hasValue=!0,this.value=e)}clearValue(){this.hasDeoptedValue=!1,this.hasValue=!1,this.value=null}reassign(e){this.constant=!1,this.constantViolations.includes(e)||this.constantViolations.push(e)}reference(e){this.referencePaths.includes(e)||(this.referenced=!0,this.references++,this.referencePaths.push(e))}dereference(){this.references--,this.referenced=!!this.references}}},3611:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.ConfigPrinter=t.ChainFormatter=void 0;const s=t.ChainFormatter={Programmatic:0,Config:1},i={title(e,t,r){let n="";return e===s.Programmatic?(n="programmatic options",t&&(n+=" from "+t)):n="config "+r,n},loc(e,t){let r="";return null!=e&&(r+=`.overrides[${e}]`),null!=t&&(r+=`.env["${t}"]`),r},*optionsAndDescriptors(e){const t=Object.assign({},e.options);delete t.overrides,delete t.env;const r=[...yield*e.plugins()];r.length&&(t.plugins=r.map((e=>a(e))));const n=[...yield*e.presets()];return n.length&&(t.presets=[...n].map((e=>a(e)))),JSON.stringify(t,void 0,2)}};function a(e){var t;let r=null==(t=e.file)?void 0:t.request;return null==r&&("object"==typeof e.value?r=e.value:"function"==typeof e.value&&(r=`[Function: ${e.value.toString().slice(0,50)} ... ]`)),null==r&&(r="[Unknown]"),void 0===e.options?r:null==e.name?[r,e.options]:[r,e.options,e.name]}class o{constructor(){this._stack=[]}configure(e,t,{callerName:r,filepath:n}){return e?(e,s,i)=>{this._stack.push({type:t,callerName:r,filepath:n,content:e,index:s,envName:i})}:()=>{}}static*format(e){let t=i.title(e.type,e.callerName,e.filepath);const r=i.loc(e.index,e.envName);return r&&(t+=` ${r}`),`${t}\n${yield*i.optionsAndDescriptors(e.content)}`}*output(){return 0===this._stack.length?"":(yield*n().all(this._stack.map((e=>o.format(e))))).join("\n\n")}}t.ConfigPrinter=o},3628:(e,t,r)=>{"use strict";var n=r(8648),s=r(1064),i=r(7176);e.exports=n?function(e){return n(e)}:s?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return s(e)}:i?function(e){return i(e)}:null},3762:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n=""){if(r.has(e))return;r.add(e);const{internal:s,trace:i}=function(){const{stackTraceLimit:e,prepareStackTrace:t}=Error;let r;if(Error.stackTraceLimit=4,Error.prepareStackTrace=function(e,t){r=t},(new Error).stack,Error.stackTraceLimit=e,Error.prepareStackTrace=t,!r)return{internal:!1,trace:""};const n=r.slice(2,4);return{internal:/[\\/]@babel[\\/]/.test(n[1].getFileName()),trace:n.map((e=>` at ${e}`)).join("\n")}}();s||console.warn(`${n}\`${e}\` has been deprecated, please migrate to \`${t}\`\n${i}`)};const r=new Set},3817:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){i||(i=s.visitors.environmentVisitor({ThisExpression(e){e.replaceWith(n.types.unaryExpression("void",n.types.numericLiteral(0),!0))}}),i.noScope=!0),(0,s.default)(e.node,i)};var n=r(6416),s=r(5781);let i},3823:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;class r{constructor(e,t,r,n){this._map=new Map,this.key=void 0,this.file=void 0,this.opts=void 0,this.cwd=void 0,this.filename=void 0,this.isAsync=void 0,this.key=t,this.file=e,this.opts=r||{},this.cwd=e.opts.cwd,this.filename=e.opts.filename,this.isAsync=n}set(e,t){this._map.set(e,t)}get(e){return this._map.get(e)}availableHelper(e,t){return this.file.availableHelper(e,t)}addHelper(e){return this.file.addHelper(e)}buildCodeFrameError(e,t,r){return this.file.buildCodeFrameError(e,t,r)}}t.default=r,r.prototype.getModuleName=function(){return this.file.getModuleName()},r.prototype.addImport=function(){this.file.addImport()}},3828:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){return!!t&&((0,s.default)(t.type,e)?void 0===r||(0,n.default)(t,r):!r&&"Placeholder"===t.type&&e in a.FLIPPED_ALIAS_KEYS&&(0,i.default)(t.expectedNode,e))};var n=r(6616),s=r(4460),i=r(3571),a=r(9793)},3847:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.isVariableDeclaration)(e)&&("var"!==e.kind||e[s.BLOCK_SCOPED_SYMBOL])};var n=r(8960),s=r(3422)},3853:(e,t,r)=>{"use strict";function n(){const e=r(7975);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const r=n().resolve(t,e).split(n().sep);return new RegExp(["^",...r.map(((e,t)=>{const n=t===r.length-1;return"**"===e?n?p:c:"*"===e?n?l:o:0===e.indexOf("*.")?a+u(e.slice(1))+(n?i:s):u(e)+(n?i:s)}))].join(""))};const s=`\\${n().sep}`,i=`(?:${s}|$)`,a=`[^${s}]+`,o=`(?:${a}${s})`,l=`(?:${a}${i})`,c=`${o}*?`,p=`${o}*?${l}?`;function u(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&")}},3863:(e,t,r)=>{"use strict";function n(){const e=r(5781);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return i||(i=new s.default(Object.assign({},a,{visitor:n().default.explode(a.visitor)}),{})),i};var s=r(5856);let i;const a={name:"internal.blockHoist",visitor:{Block:{exit({node:e}){e.body=o(e.body)}},SwitchCase:{exit({node:e}){e.consequent=o(e.consequent)}}}};function o(e){let t=Math.pow(2,30)-1,r=!1;for(let n=0;n<e.length;n++){const s=l(e[n]);if(s>t){r=!0;break}t=s}return r?function(e){const t=Object.create(null);for(let r=0;r<e.length;r++){const n=e[r],s=l(n);(t[s]||(t[s]=[])).push(n)}const r=Object.keys(t).map((e=>+e)).sort(((e,t)=>t-e));let n=0;for(const s of r){const r=t[s];for(const t of r)e[n++]=t}return e}(e.slice()):e}function l(e){const t=null==e?void 0:e._blockHoist;return null==t?1:!0===t?2:t}},3874:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(2352),s=n,i=r(2264),a=r(4950),o=r(9578);const{getAssignmentIdentifiers:l}=s,c={ReferencedIdentifier({node:e},t){e.name===t.oldName&&(e.name=t.newName)},Scope(e,t){e.scope.bindingIdentifierEquals(t.oldName,t.binding.identifier)||(e.skip(),e.isMethod()&&(e.requeueComputedKeyAndDecorators?e.requeueComputedKeyAndDecorators():o.requeueComputedKeyAndDecorators.call(e)))},ObjectProperty({node:e,scope:t},r){const{name:n}=e.key;var s;!e.shorthand||n!==r.oldName&&n!==r.newName||t.getBindingIdentifier(n)!==r.binding.identifier||(e.shorthand=!1,null!=(s=e.extra)&&s.shorthand&&(e.extra.shorthand=!1))},"AssignmentExpression|Declaration|VariableDeclarator"(e,t){if(e.isVariableDeclaration())return;const r=e.isAssignmentExpression()?l(e.node):e.getOuterBindingIdentifiers();for(const e in r)e===t.oldName&&(r[e].name=t.newName)}};t.default=class{constructor(e,t,r){this.newName=r,this.oldName=t,this.binding=e}maybeConvertFromExportDeclaration(e){const t=e.parentPath;if(t.isExportDeclaration()){if(t.isExportDefaultDeclaration()){const{declaration:e}=t.node;if(n.isDeclaration(e)&&!e.id)return}t.isExportAllDeclaration()||t.splitExportDeclaration()}}maybeConvertFromClassFunctionDeclaration(e){return e}maybeConvertFromClassFunctionExpression(e){return e}rename(){const{binding:e,oldName:t,newName:r}=this,{scope:s,path:o}=e,l=o.find((e=>e.isDeclaration()||e.isFunctionExpression()||e.isClassExpression()));l&&l.getOuterBindingIdentifiers()[t]===e.identifier&&this.maybeConvertFromExportDeclaration(l);const p=arguments[0]||s.block,u={discriminant:!0};n.isMethod(p)&&(p.computed&&(u.key=!0),n.isObjectMethod(p)||(u.decorators=!0)),(0,i.traverseNode)(p,(0,a.explode)(c),s,this,s.path,u),arguments[0]||(s.removeOwnBinding(t),s.bindings[r]=e,this.binding.identifier.name=r),l&&(this.maybeConvertFromClassFunctionDeclaration(o),this.maybeConvertFromClassFunctionExpression(o))}}},3878:e=>{"use strict";const t=Symbol.for("gensync:v1:start"),r=Symbol.for("gensync:v1:suspend"),n="GENSYNC_OPTIONS_ERROR",s="GENSYNC_RACE_NONEMPTY";function i(e,t,r,s){if(typeof r===e||s&&void 0===r)return;let i;throw i=s?`Expected opts.${t} to be either a ${e}, or undefined.`:`Expected opts.${t} to be a ${e}.`,a(i,n)}function a(e,t){return Object.assign(new Error(e),{code:t})}function o({name:e,arity:n,sync:s,async:i}){return f(e,n,(function*(...e){const n=yield t;if(!n)return s.call(this,e);let a;try{i.call(this,e,(e=>{a||(a={value:e},n())}),(e=>{a||(a={err:e},n())}))}catch(e){a={err:e},n()}if(yield r,a.hasOwnProperty("err"))throw a.err;return a.value}))}function l(e){let t;for(;!({value:t}=e.next()).done;)p(t,e);return t}function c(e,t,r){!function n(){try{let r;for(;!({value:r}=e.next()).done;){p(r,e);let t=!0,s=!1;const i=e.next((()=>{t?s=!0:n()}));if(t=!1,u(i,e),!s)return}return t(r)}catch(e){return r(e)}}()}function p(e,r){e!==t&&d(r,a(`Got unexpected yielded value in gensync generator: ${JSON.stringify(e)}. Did you perhaps mean to use 'yield*' instead of 'yield'?`,"GENSYNC_EXPECTED_START"))}function u({value:e,done:t},n){(t||e!==r)&&d(n,a(t?"Unexpected generator completion. If you get this, it is probably a gensync bug.":`Expected GENSYNC_SUSPEND, got ${JSON.stringify(e)}. If you get this, it is probably a gensync bug.`,"GENSYNC_EXPECTED_SUSPEND"))}function d(e,t){throw e.throw&&e.throw(t),t}function f(e,t,r){if("string"==typeof e){const t=Object.getOwnPropertyDescriptor(r,"name");t&&!t.configurable||Object.defineProperty(r,"name",Object.assign(t||{},{configurable:!0,value:e}))}if("number"==typeof t){const e=Object.getOwnPropertyDescriptor(r,"length");e&&!e.configurable||Object.defineProperty(r,"length",Object.assign(e||{},{configurable:!0,value:t}))}return r}e.exports=Object.assign((function(e){let t=e;return t="function"!=typeof e?function({name:e,arity:t,sync:r,async:s,errback:l}){if(i("string","name",e,!0),i("number","arity",t,!0),i("function","sync",r),i("function","async",s,!0),i("function","errback",l,!0),s&&l)throw a("Expected one of either opts.async or opts.errback, but got _both_.",n);if("string"!=typeof e){let t;l&&l.name&&"errback"!==l.name&&(t=l.name),s&&s.name&&"async"!==s.name&&(t=s.name.replace(/Async$/,"")),r&&r.name&&"sync"!==r.name&&(t=r.name.replace(/Sync$/,"")),"string"==typeof t&&(e=t)}return"number"!=typeof t&&(t=r.length),o({name:e,arity:t,sync:function(e){return r.apply(this,e)},async:function(e,t,n){s?s.apply(this,e).then(t,n):l?l.call(this,...e,((e,r)=>{null==e?t(r):n(e)})):t(r.apply(this,e))}})}(e):function(e){return f(e.name,e.length,(function(...t){return e.apply(this,t)}))}(e),Object.assign(t,function(e){return{sync:function(...t){return l(e.apply(this,t))},async:function(...t){return new Promise(((r,n)=>{c(e.apply(this,t),r,n)}))},errback:function(...t){const r=t.pop();if("function"!=typeof r)throw a("Asynchronous function called without callback","GENSYNC_ERRBACK_NO_CALLBACK");let n;try{n=e.apply(this,t)}catch(e){return void r(e)}c(n,(e=>r(void 0,e)),(e=>r(e)))}}}(t))}),{all:o({name:"all",arity:1,sync:function(e){return Array.from(e[0]).map((e=>l(e)))},async:function(e,t,r){const n=Array.from(e[0]);if(0===n.length)return void Promise.resolve().then((()=>t([])));let s=0;const i=n.map((()=>{}));n.forEach(((e,n)=>{c(e,(e=>{i[n]=e,s+=1,s===i.length&&t(i)}),r)}))}}),race:o({name:"race",arity:1,sync:function(e){const t=Array.from(e[0]);if(0===t.length)throw a("Must race at least 1 item",s);return l(t[0])},async:function(e,t,r){const n=Array.from(e[0]);if(0===n.length)throw a("Must race at least 1 item",s);for(const e of n)c(e,t,r)}})})},3908:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return!(!e||!n.VISITOR_KEYS[e.type])};var n=r(9793)},3909:e=>{"use strict";e.exports=JSON.parse('[{"name":"nodejs","version":"0.2.0","date":"2011-08-26","lts":false,"security":false,"v8":"2.3.8.0"},{"name":"nodejs","version":"0.3.0","date":"2011-08-26","lts":false,"security":false,"v8":"2.5.1.0"},{"name":"nodejs","version":"0.4.0","date":"2011-08-26","lts":false,"security":false,"v8":"3.1.2.0"},{"name":"nodejs","version":"0.5.0","date":"2011-08-26","lts":false,"security":false,"v8":"3.1.8.25"},{"name":"nodejs","version":"0.6.0","date":"2011-11-04","lts":false,"security":false,"v8":"3.6.6.6"},{"name":"nodejs","version":"0.7.0","date":"2012-01-17","lts":false,"security":false,"v8":"3.8.6.0"},{"name":"nodejs","version":"0.8.0","date":"2012-06-22","lts":false,"security":false,"v8":"3.11.10.10"},{"name":"nodejs","version":"0.9.0","date":"2012-07-20","lts":false,"security":false,"v8":"3.11.10.15"},{"name":"nodejs","version":"0.10.0","date":"2013-03-11","lts":false,"security":false,"v8":"3.14.5.8"},{"name":"nodejs","version":"0.11.0","date":"2013-03-28","lts":false,"security":false,"v8":"3.17.13.0"},{"name":"nodejs","version":"0.12.0","date":"2015-02-06","lts":false,"security":false,"v8":"3.28.73.0"},{"name":"nodejs","version":"4.0.0","date":"2015-09-08","lts":false,"security":false,"v8":"4.5.103.30"},{"name":"nodejs","version":"4.1.0","date":"2015-09-17","lts":false,"security":false,"v8":"4.5.103.33"},{"name":"nodejs","version":"4.2.0","date":"2015-10-12","lts":"Argon","security":false,"v8":"4.5.103.35"},{"name":"nodejs","version":"4.3.0","date":"2016-02-09","lts":"Argon","security":false,"v8":"4.5.103.35"},{"name":"nodejs","version":"4.4.0","date":"2016-03-08","lts":"Argon","security":false,"v8":"4.5.103.35"},{"name":"nodejs","version":"4.5.0","date":"2016-08-16","lts":"Argon","security":false,"v8":"4.5.103.37"},{"name":"nodejs","version":"4.6.0","date":"2016-09-27","lts":"Argon","security":true,"v8":"4.5.103.37"},{"name":"nodejs","version":"4.7.0","date":"2016-12-06","lts":"Argon","security":false,"v8":"4.5.103.43"},{"name":"nodejs","version":"4.8.0","date":"2017-02-21","lts":"Argon","security":false,"v8":"4.5.103.45"},{"name":"nodejs","version":"4.9.0","date":"2018-03-28","lts":"Argon","security":true,"v8":"4.5.103.53"},{"name":"nodejs","version":"5.0.0","date":"2015-10-29","lts":false,"security":false,"v8":"4.6.85.28"},{"name":"nodejs","version":"5.1.0","date":"2015-11-17","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.2.0","date":"2015-12-09","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.3.0","date":"2015-12-15","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.4.0","date":"2016-01-06","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.5.0","date":"2016-01-21","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.6.0","date":"2016-02-09","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.7.0","date":"2016-02-23","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.8.0","date":"2016-03-09","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.9.0","date":"2016-03-16","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.10.0","date":"2016-04-01","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.11.0","date":"2016-04-21","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.12.0","date":"2016-06-23","lts":false,"security":false,"v8":"4.6.85.32"},{"name":"nodejs","version":"6.0.0","date":"2016-04-26","lts":false,"security":false,"v8":"5.0.71.35"},{"name":"nodejs","version":"6.1.0","date":"2016-05-05","lts":false,"security":false,"v8":"5.0.71.35"},{"name":"nodejs","version":"6.2.0","date":"2016-05-17","lts":false,"security":false,"v8":"5.0.71.47"},{"name":"nodejs","version":"6.3.0","date":"2016-07-06","lts":false,"security":false,"v8":"5.0.71.52"},{"name":"nodejs","version":"6.4.0","date":"2016-08-12","lts":false,"security":false,"v8":"5.0.71.60"},{"name":"nodejs","version":"6.5.0","date":"2016-08-26","lts":false,"security":false,"v8":"5.1.281.81"},{"name":"nodejs","version":"6.6.0","date":"2016-09-14","lts":false,"security":false,"v8":"5.1.281.83"},{"name":"nodejs","version":"6.7.0","date":"2016-09-27","lts":false,"security":true,"v8":"5.1.281.83"},{"name":"nodejs","version":"6.8.0","date":"2016-10-12","lts":false,"security":false,"v8":"5.1.281.84"},{"name":"nodejs","version":"6.9.0","date":"2016-10-18","lts":"Boron","security":false,"v8":"5.1.281.84"},{"name":"nodejs","version":"6.10.0","date":"2017-02-21","lts":"Boron","security":false,"v8":"5.1.281.93"},{"name":"nodejs","version":"6.11.0","date":"2017-06-06","lts":"Boron","security":false,"v8":"5.1.281.102"},{"name":"nodejs","version":"6.12.0","date":"2017-11-06","lts":"Boron","security":false,"v8":"5.1.281.108"},{"name":"nodejs","version":"6.13.0","date":"2018-02-10","lts":"Boron","security":false,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.14.0","date":"2018-03-28","lts":"Boron","security":true,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.15.0","date":"2018-11-27","lts":"Boron","security":true,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.16.0","date":"2018-12-26","lts":"Boron","security":false,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.17.0","date":"2019-02-28","lts":"Boron","security":true,"v8":"5.1.281.111"},{"name":"nodejs","version":"7.0.0","date":"2016-10-25","lts":false,"security":false,"v8":"5.4.500.36"},{"name":"nodejs","version":"7.1.0","date":"2016-11-08","lts":false,"security":false,"v8":"5.4.500.36"},{"name":"nodejs","version":"7.2.0","date":"2016-11-22","lts":false,"security":false,"v8":"5.4.500.43"},{"name":"nodejs","version":"7.3.0","date":"2016-12-20","lts":false,"security":false,"v8":"5.4.500.45"},{"name":"nodejs","version":"7.4.0","date":"2017-01-04","lts":false,"security":false,"v8":"5.4.500.45"},{"name":"nodejs","version":"7.5.0","date":"2017-01-31","lts":false,"security":false,"v8":"5.4.500.48"},{"name":"nodejs","version":"7.6.0","date":"2017-02-21","lts":false,"security":false,"v8":"5.5.372.40"},{"name":"nodejs","version":"7.7.0","date":"2017-02-28","lts":false,"security":false,"v8":"5.5.372.41"},{"name":"nodejs","version":"7.8.0","date":"2017-03-29","lts":false,"security":false,"v8":"5.5.372.43"},{"name":"nodejs","version":"7.9.0","date":"2017-04-11","lts":false,"security":false,"v8":"5.5.372.43"},{"name":"nodejs","version":"7.10.0","date":"2017-05-02","lts":false,"security":false,"v8":"5.5.372.43"},{"name":"nodejs","version":"8.0.0","date":"2017-05-30","lts":false,"security":false,"v8":"5.8.283.41"},{"name":"nodejs","version":"8.1.0","date":"2017-06-08","lts":false,"security":false,"v8":"5.8.283.41"},{"name":"nodejs","version":"8.2.0","date":"2017-07-19","lts":false,"security":false,"v8":"5.8.283.41"},{"name":"nodejs","version":"8.3.0","date":"2017-08-08","lts":false,"security":false,"v8":"6.0.286.52"},{"name":"nodejs","version":"8.4.0","date":"2017-08-15","lts":false,"security":false,"v8":"6.0.286.52"},{"name":"nodejs","version":"8.5.0","date":"2017-09-12","lts":false,"security":false,"v8":"6.0.287.53"},{"name":"nodejs","version":"8.6.0","date":"2017-09-26","lts":false,"security":false,"v8":"6.0.287.53"},{"name":"nodejs","version":"8.7.0","date":"2017-10-11","lts":false,"security":false,"v8":"6.1.534.42"},{"name":"nodejs","version":"8.8.0","date":"2017-10-24","lts":false,"security":false,"v8":"6.1.534.42"},{"name":"nodejs","version":"8.9.0","date":"2017-10-31","lts":"Carbon","security":false,"v8":"6.1.534.46"},{"name":"nodejs","version":"8.10.0","date":"2018-03-06","lts":"Carbon","security":false,"v8":"6.2.414.50"},{"name":"nodejs","version":"8.11.0","date":"2018-03-28","lts":"Carbon","security":true,"v8":"6.2.414.50"},{"name":"nodejs","version":"8.12.0","date":"2018-09-10","lts":"Carbon","security":false,"v8":"6.2.414.66"},{"name":"nodejs","version":"8.13.0","date":"2018-11-20","lts":"Carbon","security":false,"v8":"6.2.414.72"},{"name":"nodejs","version":"8.14.0","date":"2018-11-27","lts":"Carbon","security":true,"v8":"6.2.414.72"},{"name":"nodejs","version":"8.15.0","date":"2018-12-26","lts":"Carbon","security":false,"v8":"6.2.414.75"},{"name":"nodejs","version":"8.16.0","date":"2019-04-16","lts":"Carbon","security":false,"v8":"6.2.414.77"},{"name":"nodejs","version":"8.17.0","date":"2019-12-17","lts":"Carbon","security":true,"v8":"6.2.414.78"},{"name":"nodejs","version":"9.0.0","date":"2017-10-31","lts":false,"security":false,"v8":"6.2.414.32"},{"name":"nodejs","version":"9.1.0","date":"2017-11-07","lts":false,"security":false,"v8":"6.2.414.32"},{"name":"nodejs","version":"9.2.0","date":"2017-11-14","lts":false,"security":false,"v8":"6.2.414.44"},{"name":"nodejs","version":"9.3.0","date":"2017-12-12","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.4.0","date":"2018-01-10","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.5.0","date":"2018-01-31","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.6.0","date":"2018-02-21","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.7.0","date":"2018-03-01","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.8.0","date":"2018-03-07","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.9.0","date":"2018-03-21","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.10.0","date":"2018-03-28","lts":false,"security":true,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.11.0","date":"2018-04-04","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"10.0.0","date":"2018-04-24","lts":false,"security":false,"v8":"6.6.346.24"},{"name":"nodejs","version":"10.1.0","date":"2018-05-08","lts":false,"security":false,"v8":"6.6.346.27"},{"name":"nodejs","version":"10.2.0","date":"2018-05-23","lts":false,"security":false,"v8":"6.6.346.32"},{"name":"nodejs","version":"10.3.0","date":"2018-05-29","lts":false,"security":false,"v8":"6.6.346.32"},{"name":"nodejs","version":"10.4.0","date":"2018-06-06","lts":false,"security":false,"v8":"6.7.288.43"},{"name":"nodejs","version":"10.5.0","date":"2018-06-20","lts":false,"security":false,"v8":"6.7.288.46"},{"name":"nodejs","version":"10.6.0","date":"2018-07-04","lts":false,"security":false,"v8":"6.7.288.46"},{"name":"nodejs","version":"10.7.0","date":"2018-07-18","lts":false,"security":false,"v8":"6.7.288.49"},{"name":"nodejs","version":"10.8.0","date":"2018-08-01","lts":false,"security":false,"v8":"6.7.288.49"},{"name":"nodejs","version":"10.9.0","date":"2018-08-15","lts":false,"security":false,"v8":"6.8.275.24"},{"name":"nodejs","version":"10.10.0","date":"2018-09-06","lts":false,"security":false,"v8":"6.8.275.30"},{"name":"nodejs","version":"10.11.0","date":"2018-09-19","lts":false,"security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.12.0","date":"2018-10-10","lts":false,"security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.13.0","date":"2018-10-30","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.14.0","date":"2018-11-27","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.15.0","date":"2018-12-26","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.16.0","date":"2019-05-28","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.17.0","date":"2019-10-22","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.18.0","date":"2019-12-17","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.19.0","date":"2020-02-05","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.20.0","date":"2020-03-26","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.21.0","date":"2020-06-02","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.22.0","date":"2020-07-21","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.23.0","date":"2020-10-27","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.24.0","date":"2021-02-23","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"11.0.0","date":"2018-10-23","lts":false,"security":false,"v8":"7.0.276.28"},{"name":"nodejs","version":"11.1.0","date":"2018-10-30","lts":false,"security":false,"v8":"7.0.276.32"},{"name":"nodejs","version":"11.2.0","date":"2018-11-15","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.3.0","date":"2018-11-27","lts":false,"security":true,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.4.0","date":"2018-12-07","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.5.0","date":"2018-12-18","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.6.0","date":"2018-12-26","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.7.0","date":"2019-01-17","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.8.0","date":"2019-01-24","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.9.0","date":"2019-01-30","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.10.0","date":"2019-02-14","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.11.0","date":"2019-03-05","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.12.0","date":"2019-03-14","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.13.0","date":"2019-03-28","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.14.0","date":"2019-04-10","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.15.0","date":"2019-04-30","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"12.0.0","date":"2019-04-23","lts":false,"security":false,"v8":"7.4.288.21"},{"name":"nodejs","version":"12.1.0","date":"2019-04-29","lts":false,"security":false,"v8":"7.4.288.21"},{"name":"nodejs","version":"12.2.0","date":"2019-05-07","lts":false,"security":false,"v8":"7.4.288.21"},{"name":"nodejs","version":"12.3.0","date":"2019-05-21","lts":false,"security":false,"v8":"7.4.288.27"},{"name":"nodejs","version":"12.4.0","date":"2019-06-04","lts":false,"security":false,"v8":"7.4.288.27"},{"name":"nodejs","version":"12.5.0","date":"2019-06-26","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.6.0","date":"2019-07-03","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.7.0","date":"2019-07-23","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.8.0","date":"2019-08-06","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.9.0","date":"2019-08-20","lts":false,"security":false,"v8":"7.6.303.29"},{"name":"nodejs","version":"12.10.0","date":"2019-09-04","lts":false,"security":false,"v8":"7.6.303.29"},{"name":"nodejs","version":"12.11.0","date":"2019-09-25","lts":false,"security":false,"v8":"7.7.299.11"},{"name":"nodejs","version":"12.12.0","date":"2019-10-11","lts":false,"security":false,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.13.0","date":"2019-10-21","lts":"Erbium","security":false,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.14.0","date":"2019-12-17","lts":"Erbium","security":true,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.15.0","date":"2020-02-05","lts":"Erbium","security":true,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.16.0","date":"2020-02-11","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.17.0","date":"2020-05-26","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.18.0","date":"2020-06-02","lts":"Erbium","security":true,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.19.0","date":"2020-10-06","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.20.0","date":"2020-11-24","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.21.0","date":"2021-02-23","lts":"Erbium","security":true,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.22.0","date":"2021-03-30","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"13.0.0","date":"2019-10-22","lts":false,"security":false,"v8":"7.8.279.17"},{"name":"nodejs","version":"13.1.0","date":"2019-11-05","lts":false,"security":false,"v8":"7.8.279.17"},{"name":"nodejs","version":"13.2.0","date":"2019-11-21","lts":false,"security":false,"v8":"7.9.317.23"},{"name":"nodejs","version":"13.3.0","date":"2019-12-03","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.4.0","date":"2019-12-17","lts":false,"security":true,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.5.0","date":"2019-12-18","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.6.0","date":"2020-01-07","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.7.0","date":"2020-01-21","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.8.0","date":"2020-02-05","lts":false,"security":true,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.9.0","date":"2020-02-18","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.10.0","date":"2020-03-04","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.11.0","date":"2020-03-12","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.12.0","date":"2020-03-26","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.13.0","date":"2020-04-14","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.14.0","date":"2020-04-29","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"14.0.0","date":"2020-04-21","lts":false,"security":false,"v8":"8.1.307.30"},{"name":"nodejs","version":"14.1.0","date":"2020-04-29","lts":false,"security":false,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.2.0","date":"2020-05-05","lts":false,"security":false,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.3.0","date":"2020-05-19","lts":false,"security":false,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.4.0","date":"2020-06-02","lts":false,"security":true,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.5.0","date":"2020-06-30","lts":false,"security":false,"v8":"8.3.110.9"},{"name":"nodejs","version":"14.6.0","date":"2020-07-20","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.7.0","date":"2020-07-29","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.8.0","date":"2020-08-11","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.9.0","date":"2020-08-27","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.10.0","date":"2020-09-08","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.11.0","date":"2020-09-15","lts":false,"security":true,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.12.0","date":"2020-09-22","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.13.0","date":"2020-09-29","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.14.0","date":"2020-10-15","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.15.0","date":"2020-10-27","lts":"Fermium","security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.16.0","date":"2021-02-23","lts":"Fermium","security":true,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.17.0","date":"2021-05-11","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.18.0","date":"2021-09-28","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.19.0","date":"2022-02-01","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.20.0","date":"2022-07-07","lts":"Fermium","security":true,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.21.0","date":"2022-11-01","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"15.0.0","date":"2020-10-20","lts":false,"security":false,"v8":"8.6.395.16"},{"name":"nodejs","version":"15.1.0","date":"2020-11-04","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.2.0","date":"2020-11-10","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.3.0","date":"2020-11-24","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.4.0","date":"2020-12-09","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.5.0","date":"2020-12-22","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.6.0","date":"2021-01-14","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.7.0","date":"2021-01-25","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.8.0","date":"2021-02-02","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.9.0","date":"2021-02-18","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.10.0","date":"2021-02-23","lts":false,"security":true,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.11.0","date":"2021-03-03","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.12.0","date":"2021-03-17","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.13.0","date":"2021-03-31","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.14.0","date":"2021-04-06","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"16.0.0","date":"2021-04-20","lts":false,"security":false,"v8":"9.0.257.17"},{"name":"nodejs","version":"16.1.0","date":"2021-05-04","lts":false,"security":false,"v8":"9.0.257.24"},{"name":"nodejs","version":"16.2.0","date":"2021-05-19","lts":false,"security":false,"v8":"9.0.257.25"},{"name":"nodejs","version":"16.3.0","date":"2021-06-03","lts":false,"security":false,"v8":"9.0.257.25"},{"name":"nodejs","version":"16.4.0","date":"2021-06-23","lts":false,"security":false,"v8":"9.1.269.36"},{"name":"nodejs","version":"16.5.0","date":"2021-07-14","lts":false,"security":false,"v8":"9.1.269.38"},{"name":"nodejs","version":"16.6.0","date":"2021-07-29","lts":false,"security":true,"v8":"9.2.230.21"},{"name":"nodejs","version":"16.7.0","date":"2021-08-18","lts":false,"security":false,"v8":"9.2.230.21"},{"name":"nodejs","version":"16.8.0","date":"2021-08-25","lts":false,"security":false,"v8":"9.2.230.21"},{"name":"nodejs","version":"16.9.0","date":"2021-09-07","lts":false,"security":false,"v8":"9.3.345.16"},{"name":"nodejs","version":"16.10.0","date":"2021-09-22","lts":false,"security":false,"v8":"9.3.345.19"},{"name":"nodejs","version":"16.11.0","date":"2021-10-08","lts":false,"security":false,"v8":"9.4.146.19"},{"name":"nodejs","version":"16.12.0","date":"2021-10-20","lts":false,"security":false,"v8":"9.4.146.19"},{"name":"nodejs","version":"16.13.0","date":"2021-10-26","lts":"Gallium","security":false,"v8":"9.4.146.19"},{"name":"nodejs","version":"16.14.0","date":"2022-02-08","lts":"Gallium","security":false,"v8":"9.4.146.24"},{"name":"nodejs","version":"16.15.0","date":"2022-04-26","lts":"Gallium","security":false,"v8":"9.4.146.24"},{"name":"nodejs","version":"16.16.0","date":"2022-07-07","lts":"Gallium","security":true,"v8":"9.4.146.24"},{"name":"nodejs","version":"16.17.0","date":"2022-08-16","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"16.18.0","date":"2022-10-12","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"16.19.0","date":"2022-12-13","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"16.20.0","date":"2023-03-28","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"17.0.0","date":"2021-10-19","lts":false,"security":false,"v8":"9.5.172.21"},{"name":"nodejs","version":"17.1.0","date":"2021-11-09","lts":false,"security":false,"v8":"9.5.172.25"},{"name":"nodejs","version":"17.2.0","date":"2021-11-30","lts":false,"security":false,"v8":"9.6.180.14"},{"name":"nodejs","version":"17.3.0","date":"2021-12-17","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.4.0","date":"2022-01-18","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.5.0","date":"2022-02-10","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.6.0","date":"2022-02-22","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.7.0","date":"2022-03-09","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.8.0","date":"2022-03-22","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.9.0","date":"2022-04-07","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"18.0.0","date":"2022-04-18","lts":false,"security":false,"v8":"10.1.124.8"},{"name":"nodejs","version":"18.1.0","date":"2022-05-03","lts":false,"security":false,"v8":"10.1.124.8"},{"name":"nodejs","version":"18.2.0","date":"2022-05-17","lts":false,"security":false,"v8":"10.1.124.8"},{"name":"nodejs","version":"18.3.0","date":"2022-06-02","lts":false,"security":false,"v8":"10.2.154.4"},{"name":"nodejs","version":"18.4.0","date":"2022-06-16","lts":false,"security":false,"v8":"10.2.154.4"},{"name":"nodejs","version":"18.5.0","date":"2022-07-06","lts":false,"security":true,"v8":"10.2.154.4"},{"name":"nodejs","version":"18.6.0","date":"2022-07-13","lts":false,"security":false,"v8":"10.2.154.13"},{"name":"nodejs","version":"18.7.0","date":"2022-07-26","lts":false,"security":false,"v8":"10.2.154.13"},{"name":"nodejs","version":"18.8.0","date":"2022-08-24","lts":false,"security":false,"v8":"10.2.154.13"},{"name":"nodejs","version":"18.9.0","date":"2022-09-07","lts":false,"security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.10.0","date":"2022-09-28","lts":false,"security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.11.0","date":"2022-10-13","lts":false,"security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.12.0","date":"2022-10-25","lts":"Hydrogen","security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.13.0","date":"2023-01-05","lts":"Hydrogen","security":false,"v8":"10.2.154.23"},{"name":"nodejs","version":"18.14.0","date":"2023-02-01","lts":"Hydrogen","security":false,"v8":"10.2.154.23"},{"name":"nodejs","version":"18.15.0","date":"2023-03-05","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.16.0","date":"2023-04-12","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.17.0","date":"2023-07-18","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.18.0","date":"2023-09-18","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.19.0","date":"2023-11-29","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.20.0","date":"2024-03-26","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"19.0.0","date":"2022-10-17","lts":false,"security":false,"v8":"10.7.193.13"},{"name":"nodejs","version":"19.1.0","date":"2022-11-14","lts":false,"security":false,"v8":"10.7.193.20"},{"name":"nodejs","version":"19.2.0","date":"2022-11-29","lts":false,"security":false,"v8":"10.8.168.20"},{"name":"nodejs","version":"19.3.0","date":"2022-12-14","lts":false,"security":false,"v8":"10.8.168.21"},{"name":"nodejs","version":"19.4.0","date":"2023-01-05","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.5.0","date":"2023-01-24","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.6.0","date":"2023-02-01","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.7.0","date":"2023-02-21","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.8.0","date":"2023-03-14","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.9.0","date":"2023-04-10","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"20.0.0","date":"2023-04-17","lts":false,"security":false,"v8":"11.3.244.4"},{"name":"nodejs","version":"20.1.0","date":"2023-05-03","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.2.0","date":"2023-05-16","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.3.0","date":"2023-06-08","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.4.0","date":"2023-07-04","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.5.0","date":"2023-07-19","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.6.0","date":"2023-08-23","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.7.0","date":"2023-09-18","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.8.0","date":"2023-09-28","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.9.0","date":"2023-10-24","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.10.0","date":"2023-11-22","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.11.0","date":"2024-01-09","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.12.0","date":"2024-03-26","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.13.0","date":"2024-05-07","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.14.0","date":"2024-05-28","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.15.0","date":"2024-06-20","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.16.0","date":"2024-07-24","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.17.0","date":"2024-08-21","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.18.0","date":"2024-10-03","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"21.0.0","date":"2023-10-17","lts":false,"security":false,"v8":"11.8.172.13"},{"name":"nodejs","version":"21.1.0","date":"2023-10-24","lts":false,"security":false,"v8":"11.8.172.15"},{"name":"nodejs","version":"21.2.0","date":"2023-11-14","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.3.0","date":"2023-11-30","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.4.0","date":"2023-12-05","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.5.0","date":"2023-12-19","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.6.0","date":"2024-01-14","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.7.0","date":"2024-03-06","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"22.0.0","date":"2024-04-24","lts":false,"security":false,"v8":"12.4.254.14"},{"name":"nodejs","version":"22.1.0","date":"2024-05-02","lts":false,"security":false,"v8":"12.4.254.14"},{"name":"nodejs","version":"22.2.0","date":"2024-05-15","lts":false,"security":false,"v8":"12.4.254.14"},{"name":"nodejs","version":"22.3.0","date":"2024-06-11","lts":false,"security":false,"v8":"12.4.254.20"},{"name":"nodejs","version":"22.4.0","date":"2024-07-02","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.5.0","date":"2024-07-17","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.6.0","date":"2024-08-06","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.7.0","date":"2024-08-21","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.8.0","date":"2024-09-03","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.9.0","date":"2024-09-17","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.10.0","date":"2024-10-16","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.11.0","date":"2024-10-29","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.12.0","date":"2024-12-02","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"23.0.0","date":"2024-10-16","lts":false,"security":false,"v8":"12.9.202.26"},{"name":"nodejs","version":"23.1.0","date":"2024-10-24","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.2.0","date":"2024-11-11","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.3.0","date":"2024-11-20","lts":false,"security":false,"v8":"12.9.202.28"}]')},3917:(e,t,r)=>{"use strict";function n(){const e=r(906);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.resolveBrowserslistConfigFile=function(e,t){},t.resolveTargets=function(e,t){const r=e.targets;let s;return"string"==typeof r||Array.isArray(r)?s={browsers:r}:r&&(s="esmodules"in r?Object.assign({},r,{esmodules:"intersect"}):r),(0,n().default)(s,{ignoreBrowserslistConfig:!0,browserslistEnv:e.browserslistEnv})}},3918:(e,t,r)=>{"use strict";var n=r(5606);function s(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?s(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):s(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function a(e,t,r){return(t=l(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,l(n.key),n)}}function l(e){var t=function(e){if("object"!==y(e)||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!==y(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"===y(t)?t:String(t)}function c(e,t){if(t&&("object"===y(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return p(e)}function p(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function u(e){var t="function"==typeof Map?new Map:void 0;return u=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return d(e,arguments,m(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),h(n,e)},u(e)}function d(e,t,r){return d=f()?Reflect.construct.bind():function(e,t,r){var n=[null];n.push.apply(n,t);var s=new(Function.bind.apply(e,n));return r&&h(s,r.prototype),s},d.apply(null,arguments)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function m(e){return m=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},m(e)}function y(e){return y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},y(e)}var g=r(537).inspect,b=r(9597).codes.ERR_INVALID_ARG_TYPE;function v(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}var T="",x="",S="",E="",P={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"};function A(e){var t=Object.keys(e),r=Object.create(Object.getPrototypeOf(e));return t.forEach((function(t){r[t]=e[t]})),Object.defineProperty(r,"message",{value:e.message}),r}function w(e){return g(e,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}var C=function(e,t){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&h(e,t)}(d,e);var r,s,a,l,u=(r=d,s=f(),function(){var e,t=m(r);if(s){var n=m(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return c(this,e)});function d(e){var t;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,d),"object"!==y(e)||null===e)throw new b("options","Object",e);var r=e.message,s=e.operator,i=e.stackStartFn,a=e.actual,o=e.expected,l=Error.stackTraceLimit;if(Error.stackTraceLimit=0,null!=r)t=u.call(this,String(r));else if(n.stderr&&n.stderr.isTTY&&(n.stderr&&n.stderr.getColorDepth&&1!==n.stderr.getColorDepth()?(T="",x="",E="",S=""):(T="",x="",E="",S="")),"object"===y(a)&&null!==a&&"object"===y(o)&&null!==o&&"stack"in a&&a instanceof Error&&"stack"in o&&o instanceof Error&&(a=A(a),o=A(o)),"deepStrictEqual"===s||"strictEqual"===s)t=u.call(this,function(e,t,r){var s="",i="",a=0,o="",l=!1,c=w(e),p=c.split("\n"),u=w(t).split("\n"),d=0,f="";if("strictEqual"===r&&"object"===y(e)&&"object"===y(t)&&null!==e&&null!==t&&(r="strictEqualObject"),1===p.length&&1===u.length&&p[0]!==u[0]){var h=p[0].length+u[0].length;if(h<=10){if(!("object"===y(e)&&null!==e||"object"===y(t)&&null!==t||0===e&&0===t))return"".concat(P[r],"\n\n")+"".concat(p[0]," !== ").concat(u[0],"\n")}else if("strictEqualObject"!==r&&h<(n.stderr&&n.stderr.isTTY?n.stderr.columns:80)){for(;p[0][d]===u[0][d];)d++;d>2&&(f="\n ".concat(function(e,t){if(t=Math.floor(t),0==e.length||0==t)return"";var r=e.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)e+=e,t--;return e+e.substring(0,r-e.length)}(" ",d),"^"),d=0)}}for(var m=p[p.length-1],g=u[u.length-1];m===g&&(d++<2?o="\n ".concat(m).concat(o):s=m,p.pop(),u.pop(),0!==p.length&&0!==u.length);)m=p[p.length-1],g=u[u.length-1];var b=Math.max(p.length,u.length);if(0===b){var A=c.split("\n");if(A.length>30)for(A[26]="".concat(T,"...").concat(E);A.length>27;)A.pop();return"".concat(P.notIdentical,"\n\n").concat(A.join("\n"),"\n")}d>3&&(o="\n".concat(T,"...").concat(E).concat(o),l=!0),""!==s&&(o="\n ".concat(s).concat(o),s="");var C=0,O=P[r]+"\n".concat(x,"+ actual").concat(E," ").concat(S,"- expected").concat(E),I=" ".concat(T,"...").concat(E," Lines skipped");for(d=0;d<b;d++){var N=d-a;if(p.length<d+1)N>1&&d>2&&(N>4?(i+="\n".concat(T,"...").concat(E),l=!0):N>3&&(i+="\n ".concat(u[d-2]),C++),i+="\n ".concat(u[d-1]),C++),a=d,s+="\n".concat(S,"-").concat(E," ").concat(u[d]),C++;else if(u.length<d+1)N>1&&d>2&&(N>4?(i+="\n".concat(T,"...").concat(E),l=!0):N>3&&(i+="\n ".concat(p[d-2]),C++),i+="\n ".concat(p[d-1]),C++),a=d,i+="\n".concat(x,"+").concat(E," ").concat(p[d]),C++;else{var k=u[d],_=p[d],D=_!==k&&(!v(_,",")||_.slice(0,-1)!==k);D&&v(k,",")&&k.slice(0,-1)===_&&(D=!1,_+=","),D?(N>1&&d>2&&(N>4?(i+="\n".concat(T,"...").concat(E),l=!0):N>3&&(i+="\n ".concat(p[d-2]),C++),i+="\n ".concat(p[d-1]),C++),a=d,i+="\n".concat(x,"+").concat(E," ").concat(_),s+="\n".concat(S,"-").concat(E," ").concat(k),C+=2):(i+=s,s="",1!==N&&0!==d||(i+="\n ".concat(_),C++))}if(C>20&&d<b-2)return"".concat(O).concat(I,"\n").concat(i,"\n").concat(T,"...").concat(E).concat(s,"\n")+"".concat(T,"...").concat(E)}return"".concat(O).concat(l?I:"","\n").concat(i).concat(s).concat(o).concat(f)}(a,o,s));else if("notDeepStrictEqual"===s||"notStrictEqual"===s){var f=P[s],h=w(a).split("\n");if("notStrictEqual"===s&&"object"===y(a)&&null!==a&&(f=P.notStrictEqualObject),h.length>30)for(h[26]="".concat(T,"...").concat(E);h.length>27;)h.pop();t=1===h.length?u.call(this,"".concat(f," ").concat(h[0])):u.call(this,"".concat(f,"\n\n").concat(h.join("\n"),"\n"))}else{var m=w(a),g="",C=P[s];"notDeepEqual"===s||"notEqual"===s?(m="".concat(P[s],"\n\n").concat(m)).length>1024&&(m="".concat(m.slice(0,1021),"...")):(g="".concat(w(o)),m.length>512&&(m="".concat(m.slice(0,509),"...")),g.length>512&&(g="".concat(g.slice(0,509),"...")),"deepEqual"===s||"equal"===s?m="".concat(C,"\n\n").concat(m,"\n\nshould equal\n\n"):g=" ".concat(s," ").concat(g)),t=u.call(this,"".concat(m).concat(g))}return Error.stackTraceLimit=l,t.generatedMessage=!r,Object.defineProperty(p(t),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),t.code="ERR_ASSERTION",t.actual=a,t.expected=o,t.operator=s,Error.captureStackTrace&&Error.captureStackTrace(p(t),i),t.stack,t.name="AssertionError",c(t)}return a=d,(l=[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:t,value:function(e,t){return g(this,i(i({},t),{},{customInspect:!1,depth:0}))}}])&&o(a.prototype,l),Object.defineProperty(a,"prototype",{writable:!1}),d}(u(Error),g.custom);e.exports=C},3928:(e,t,r)=>{var n=r(4150);function s(){}e.exports={loadQueries:function(){throw new n("Sharable configs are not supported in client-side build of Browserslist")},getStat:function(e){return e.stats},loadConfig:function(e){if(e.config)throw new n("Browserslist config are not supported in client-side build")},loadCountry:function(){throw new n("Country statistics are not supported in client-side build of Browserslist")},loadFeature:function(){throw new n("Supports queries are not available in client-side build of Browserslist")},currentNode:function(e,t){return e(["maintained node versions"],t)[0]},parseConfig:s,readConfig:s,findConfig:s,findConfigFile:s,clearCaches:s,oldDataWarning:s,env:{}}},3937:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const r=e.split(".");return e=>(0,n.default)(e,r,t)};var n=r(4965)},3962:(e,t)=>{"use strict";function r(){this.space()}Object.defineProperty(t,"__esModule",{value:!0}),t.JSXAttribute=function(e){this.print(e.name),e.value&&(this.tokenChar(61),this.print(e.value))},t.JSXClosingElement=function(e){this.tokenChar(60),this.tokenChar(47),this.print(e.name),this.tokenChar(62)},t.JSXClosingFragment=function(){this.token("</"),this.tokenChar(62)},t.JSXElement=function(e){const t=e.openingElement;if(this.print(t),!t.selfClosing){this.indent();for(const t of e.children)this.print(t);this.dedent(),this.print(e.closingElement)}},t.JSXEmptyExpression=function(){this.printInnerComments()},t.JSXExpressionContainer=function(e){this.tokenChar(123),this.print(e.expression),this.rightBrace(e)},t.JSXFragment=function(e){this.print(e.openingFragment),this.indent();for(const t of e.children)this.print(t);this.dedent(),this.print(e.closingFragment)},t.JSXIdentifier=function(e){this.word(e.name)},t.JSXMemberExpression=function(e){this.print(e.object),this.tokenChar(46),this.print(e.property)},t.JSXNamespacedName=function(e){this.print(e.namespace),this.tokenChar(58),this.print(e.name)},t.JSXOpeningElement=function(e){this.tokenChar(60),this.print(e.name),e.typeArguments&&this.print(e.typeArguments),this.print(e.typeParameters),e.attributes.length>0&&(this.space(),this.printJoin(e.attributes,void 0,void 0,r)),e.selfClosing&&(this.space(),this.tokenChar(47)),this.tokenChar(62)},t.JSXOpeningFragment=function(){this.tokenChar(60),this.tokenChar(62)},t.JSXSpreadAttribute=function(e){this.tokenChar(123),this.token("..."),this.print(e.argument),this.rightBrace(e)},t.JSXSpreadChild=function(e){this.tokenChar(123),this.token("..."),this.print(e.expression),this.rightBrace(e)},t.JSXText=function(e){const t=this.getPossibleRaw(e);void 0!==t?this.token(t,!0):this.token(e.value,!0)}},3973:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readCodePoint=c,t.readInt=l,t.readStringContents=function(e,t,r,n,s,o){const l=r,c=n,p=s;let u="",d=null,f=r;const{length:h}=t;for(;;){if(r>=h){o.unterminated(l,c,p),u+=t.slice(f,r);break}const m=t.charCodeAt(r);if(i(e,m,t,r)){u+=t.slice(f,r);break}if(92===m){u+=t.slice(f,r);const i=a(t,r,n,s,"template"===e,o);null!==i.ch||d?u+=i.ch:d={pos:r,lineStart:n,curLine:s},({pos:r,lineStart:n,curLine:s}=i),f=r}else 8232===m||8233===m?(++s,n=++r):10===m||13===m?"template"===e?(u+=t.slice(f,r)+"\n",++r,13===m&&10===t.charCodeAt(r)&&++r,++s,f=n=r):o.unterminated(l,c,p):++r}return{pos:r,str:u,firstInvalidLoc:d,lineStart:n,curLine:s,containsInvalid:!!d}};var r=function(e){return e>=48&&e<=57};const n={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},s={bin:e=>48===e||49===e,oct:e=>e>=48&&e<=55,dec:e=>e>=48&&e<=57,hex:e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102};function i(e,t,r,n){return"template"===e?96===t||36===t&&123===r.charCodeAt(n+1):t===("double"===e?34:39)}function a(e,t,r,n,s,i){const a=!s;t++;const l=e=>({pos:t,ch:e,lineStart:r,curLine:n}),p=e.charCodeAt(t++);switch(p){case 110:return l("\n");case 114:return l("\r");case 120:{let s;return({code:s,pos:t}=o(e,t,r,n,2,!1,a,i)),l(null===s?null:String.fromCharCode(s))}case 117:{let s;return({code:s,pos:t}=c(e,t,r,n,a,i)),l(null===s?null:String.fromCodePoint(s))}case 116:return l("\t");case 98:return l("\b");case 118:return l("\v");case 102:return l("\f");case 13:10===e.charCodeAt(t)&&++t;case 10:r=t,++n;case 8232:case 8233:return l("");case 56:case 57:if(s)return l(null);i.strictNumericEscape(t-1,r,n);default:if(p>=48&&p<=55){const a=t-1;let o=/^[0-7]+/.exec(e.slice(a,t+2))[0],c=parseInt(o,8);c>255&&(o=o.slice(0,-1),c=parseInt(o,8)),t+=o.length-1;const p=e.charCodeAt(t);if("0"!==o||56===p||57===p){if(s)return l(null);i.strictNumericEscape(a,r,n)}return l(String.fromCharCode(c))}return l(String.fromCharCode(p))}}function o(e,t,r,n,s,i,a,o){const c=t;let p;return({n:p,pos:t}=l(e,t,r,n,16,s,i,!1,o,!a)),null===p&&(a?o.invalidEscapeSequence(c,r,n):t=c-1),{code:p,pos:t}}function l(e,t,i,a,o,l,c,p,u,d){const f=t,h=16===o?n.hex:n.decBinOct,m=16===o?s.hex:10===o?s.dec:8===o?s.oct:s.bin;let y=!1,g=0;for(let n=0,s=null==l?1/0:l;n<s;++n){const n=e.charCodeAt(t);let s;if(95!==n||"bail"===p){if(s=n>=97?n-97+10:n>=65?n-65+10:r(n)?n-48:1/0,s>=o){if(s<=9&&d)return{n:null,pos:t};if(s<=9&&u.invalidDigit(t,i,a,o))s=0;else{if(!c)break;s=0,y=!0}}++t,g=g*o+s}else{const r=e.charCodeAt(t-1),n=e.charCodeAt(t+1);if(p){if(Number.isNaN(n)||!m(n)||h.has(r)||h.has(n)){if(d)return{n:null,pos:t};u.unexpectedNumericSeparator(t,i,a)}}else{if(d)return{n:null,pos:t};u.numericSeparatorInEscapeSequence(t,i,a)}++t}}return t===f||null!=l&&t-f!==l||y?{n:null,pos:t}:{n:g,pos:t}}function c(e,t,r,n,s,i){let a;if(123===e.charCodeAt(t)){if(++t,({code:a,pos:t}=o(e,t,r,n,e.indexOf("}",t)-t,!0,s,i)),++t,null!==a&&a>1114111){if(!s)return{code:null,pos:t};i.invalidCodePoint(t,r,n)}}else({code:a,pos:t}=o(e,t,r,n,4,!1,s,i));return{code:a,pos:t}}},4001:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r=!1){return e.object=(0,n.memberExpression)(e.object,e.property,e.computed),e.property=t,e.computed=!!r,e};var n=r(8079)},4014:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDeprecatedGenerators=function(e){{const t={Noop(){},TSExpressionWithTypeArguments(e){this.print(e.expression),this.print(e.typeParameters)},DecimalLiteral(e){const t=this.getPossibleRaw(e);this.format.minified||void 0===t?this.word(e.value+"m"):this.word(t)}};Object.assign(e.prototype,t)}}},4035:(e,t,r)=>{"use strict";var n,s=r(6556),i=r(9092)(),a=r(9957),o=r(5795);if(i){var l=s("RegExp.prototype.exec"),c={},p=function(){throw c},u={toString:p,valueOf:p};"symbol"==typeof Symbol.toPrimitive&&(u[Symbol.toPrimitive]=p),n=function(e){if(!e||"object"!=typeof e)return!1;var t=o(e,"lastIndex");if(!t||!a(t,"value"))return!1;try{l(e,u)}catch(e){return e===c}}}else{var d=s("Object.prototype.toString");n=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&"[object RegExp]"===d(e)}}e.exports=n},4039:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,s=r(1333);e.exports=function(){return"function"==typeof n&&"function"==typeof Symbol&&"symbol"==typeof n("foo")&&"symbol"==typeof Symbol("bar")&&s()}},4068:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(9320),s=r(2802);t.default=class{constructor(e,t){var r;this._map=void 0,this._rawMappings=void 0,this._sourceFileName=void 0,this._lastGenLine=0,this._lastSourceLine=0,this._lastSourceColumn=0,this._inputMap=void 0;const i=this._map=new n.GenMapping({sourceRoot:e.sourceRoot});if(this._sourceFileName=null==(r=e.sourceFileName)?void 0:r.replace(/\\/g,"/"),this._rawMappings=void 0,e.inputSourceMap){this._inputMap=new s.TraceMap(e.inputSourceMap);const t=this._inputMap.resolvedSources;if(t.length)for(let e=0;e<t.length;e++){var a;(0,n.setSourceContent)(i,t[e],null==(a=this._inputMap.sourcesContent)?void 0:a[e])}}if("string"!=typeof t||e.inputSourceMap){if("object"==typeof t)for(const e of Object.keys(t))(0,n.setSourceContent)(i,e.replace(/\\/g,"/"),t[e])}else(0,n.setSourceContent)(i,this._sourceFileName,t)}get(){return(0,n.toEncodedMap)(this._map)}getDecoded(){return(0,n.toDecodedMap)(this._map)}getRawMappings(){return this._rawMappings||(this._rawMappings=(0,n.allMappings)(this._map))}mark(e,t,r,i,a,o){var l;let c;if(this._rawMappings=void 0,null!=t)if(this._inputMap){if(c=(0,s.originalPositionFor)(this._inputMap,{line:t,column:r}),!c.name&&a){const e=(0,s.originalPositionFor)(this._inputMap,a);e.name&&(i=e.name)}}else c={source:(null==o?void 0:o.replace(/\\/g,"/"))||this._sourceFileName,line:t,column:r};(0,n.maybeAddMapping)(this._map,{name:i,generated:e,source:null==(l=c)?void 0:l.source,original:c})}}},4089:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(t,r){const l=[];let c=!0;for(const p of t)if((0,s.isEmptyStatement)(p)||(c=!1),(0,s.isExpression)(p))l.push(p);else if((0,s.isExpressionStatement)(p))l.push(p.expression);else if((0,s.isVariableDeclaration)(p)){if("var"!==p.kind)return;for(const e of p.declarations){const t=(0,n.default)(e);for(const e of Object.keys(t))r.push({kind:p.kind,id:(0,o.default)(t[e])});e.init&&l.push((0,i.assignmentExpression)("=",e.id,e.init))}c=!0}else if((0,s.isIfStatement)(p)){const t=p.consequent?e([p.consequent],r):(0,a.buildUndefinedNode)(),n=p.alternate?e([p.alternate],r):(0,a.buildUndefinedNode)();if(!t||!n)return;l.push((0,i.conditionalExpression)(p.test,t,n))}else if((0,s.isBlockStatement)(p)){const t=e(p.body,r);if(!t)return;l.push(t)}else{if(!(0,s.isEmptyStatement)(p))return;0===t.indexOf(p)&&(c=!0)}return c&&l.push((0,a.buildUndefinedNode)()),1===l.length?l[0]:(0,i.sequenceExpression)(l)};var n=r(329),s=r(8960),i=r(8079),a=r(985),o=r(5279)},4092:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.get=p,t.getDependencies=function(e){return c(e).getDependencies()},t.list=void 0,t.minVersion=function(e){return c(e).minVersion};var n=r(2352),s=r(9889);const{cloneNode:i,identifier:a}=n;function o(e,t,r){try{const n=t.split(".");let s=n.shift();for(;n.length>0;)e=e[s],s=n.shift();if(!(arguments.length>2))return e[s];e[s]=r}catch(e){throw e.message+=` (when accessing ${t})`,e}}const l=Object.create(null);function c(e){if(!l[e]){const t=s.default[e];if(!t)throw Object.assign(new ReferenceError(`Unknown helper ${e}`),{code:"BABEL_HELPER_UNKNOWN",helper:e});l[e]={minVersion:t.minVersion,build(e,r,n,s){const l=t.ast();return function(e,t,r,n,s,l){const{locals:c,dependencies:p,exportBindingAssignments:u,exportName:d}=t,f=new Set(n||[]);r&&f.add(r);for(const[t,n]of(Object.entries||(e=>Object.keys(e).map((t=>[t,e[t]]))))(c)){let s=t;if(r&&t===d)s=r;else for(;f.has(s);)s="_"+s;if(s!==t)for(const t of n)o(e,t,a(s))}for(const[t,r]of(Object.entries||(e=>Object.keys(e).map((t=>[t,e[t]]))))(p)){const n="function"==typeof s&&s(t)||a(t);for(const t of r)o(e,t,i(n))}null==l||l(e,d,(t=>{u.forEach((r=>o(e,r,t(o(e,r)))))}))}(l,t.metadata,r,n,e,s),{nodes:l.body,globals:t.metadata.globals}},getDependencies:()=>Object.keys(t.metadata.dependencies)}}return l[e]}function p(e,t,r,n,s){if("object"==typeof r){const e=r;r="Identifier"===(null==e?void 0:e.type)?e.name:void 0}return c(e).build(t,r,n,s)}t.ensure=e=>{c(e)},t.list=Object.keys(s.default).map((e=>e.replace(/^_/,""))),t.default=p},4133:(e,t,r)=>{"use strict";var n=r(487),s=r(8452),i=r(3003),a=r(6642),o=r(2464),l=n(a(),Number);s(l,{getPolyfill:a,implementation:i,shim:o}),e.exports=l},4148:(e,t,r)=>{"use strict";var n=r(5606);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function i(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,(void 0,i=function(e){if("object"!==s(e)||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!==s(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(n.key),"symbol"===s(i)?i:String(i)),n)}var i}function a(e,t,r){return t&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}var o,l,c=r(9597).codes,p=c.ERR_AMBIGUOUS_ARGUMENT,u=c.ERR_INVALID_ARG_TYPE,d=c.ERR_INVALID_ARG_VALUE,f=c.ERR_INVALID_RETURN_VALUE,h=c.ERR_MISSING_ARGS,m=r(3918),y=r(537).inspect,g=r(537).types,b=g.isPromise,v=g.isRegExp,T=r(9133)(),x=r(9394)(),S=r(8075)("RegExp.prototype.test");function E(){var e=r(2299);o=e.isDeepEqual,l=e.isDeepStrictEqual}new Map;var P=!1,A=e.exports=I,w={};function C(e){if(e.message instanceof Error)throw e.message;throw new m(e)}function O(e,t,r,n){if(!r){var s=!1;if(0===t)s=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;var i=new m({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw i.generatedMessage=s,i}}function I(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];O.apply(void 0,[I,t.length].concat(t))}A.fail=function e(t,r,s,i,a){var o,l=arguments.length;if(0===l?o="Failed":1===l?(s=t,t=void 0):(!1===P&&(P=!0,(n.emitWarning?n.emitWarning:console.warn.bind(console))("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.","DeprecationWarning","DEP0094")),2===l&&(i="!=")),s instanceof Error)throw s;var c={actual:t,expected:r,operator:void 0===i?"fail":i,stackStartFn:a||e};void 0!==s&&(c.message=s);var p=new m(c);throw o&&(p.message=o,p.generatedMessage=!0),p},A.AssertionError=m,A.ok=I,A.equal=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");t!=r&&C({actual:t,expected:r,message:n,operator:"==",stackStartFn:e})},A.notEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");t==r&&C({actual:t,expected:r,message:n,operator:"!=",stackStartFn:e})},A.deepEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");void 0===o&&E(),o(t,r)||C({actual:t,expected:r,message:n,operator:"deepEqual",stackStartFn:e})},A.notDeepEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");void 0===o&&E(),o(t,r)&&C({actual:t,expected:r,message:n,operator:"notDeepEqual",stackStartFn:e})},A.deepStrictEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");void 0===o&&E(),l(t,r)||C({actual:t,expected:r,message:n,operator:"deepStrictEqual",stackStartFn:e})},A.notDeepStrictEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");void 0===o&&E(),l(t,r)&&C({actual:t,expected:r,message:n,operator:"notDeepStrictEqual",stackStartFn:e})},A.strictEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");x(t,r)||C({actual:t,expected:r,message:n,operator:"strictEqual",stackStartFn:e})},A.notStrictEqual=function e(t,r,n){if(arguments.length<2)throw new h("actual","expected");x(t,r)&&C({actual:t,expected:r,message:n,operator:"notStrictEqual",stackStartFn:e})};var N=a((function e(t,r,n){var s=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),r.forEach((function(e){e in t&&(void 0!==n&&"string"==typeof n[e]&&v(t[e])&&S(t[e],n[e])?s[e]=n[e]:s[e]=t[e])}))}));function k(e,t,r,n){if("function"!=typeof t){if(v(t))return S(t,e);if(2===arguments.length)throw new u("expected",["Function","RegExp"],t);if("object"!==s(e)||null===e){var i=new m({actual:e,expected:t,message:r,operator:"deepStrictEqual",stackStartFn:n});throw i.operator=n.name,i}var a=Object.keys(t);if(t instanceof Error)a.push("name","message");else if(0===a.length)throw new d("error",t,"may not be an empty object");return void 0===o&&E(),a.forEach((function(s){"string"==typeof e[s]&&v(t[s])&&S(t[s],e[s])||function(e,t,r,n,s,i){if(!(r in e)||!l(e[r],t[r])){if(!n){var a=new N(e,s),o=new N(t,s,e),c=new m({actual:a,expected:o,operator:"deepStrictEqual",stackStartFn:i});throw c.actual=e,c.expected=t,c.operator=i.name,c}C({actual:e,expected:t,message:n,operator:i.name,stackStartFn:i})}}(e,t,s,r,a,n)})),!0}return void 0!==t.prototype&&e instanceof t||!Error.isPrototypeOf(t)&&!0===t.call({},e)}function _(e){if("function"!=typeof e)throw new u("fn","Function",e);try{e()}catch(e){return e}return w}function D(e){return b(e)||null!==e&&"object"===s(e)&&"function"==typeof e.then&&"function"==typeof e.catch}function j(e){return Promise.resolve().then((function(){var t;if("function"==typeof e){if(!D(t=e()))throw new f("instance of Promise","promiseFn",t)}else{if(!D(e))throw new u("promiseFn",["Function","Promise"],e);t=e}return Promise.resolve().then((function(){return t})).then((function(){return w})).catch((function(e){return e}))}))}function B(e,t,r,n){if("string"==typeof r){if(4===arguments.length)throw new u("error",["Object","Error","Function","RegExp"],r);if("object"===s(t)&&null!==t){if(t.message===r)throw new p("error/message",'The error message "'.concat(t.message,'" is identical to the message.'))}else if(t===r)throw new p("error/message",'The error "'.concat(t,'" is identical to the message.'));n=r,r=void 0}else if(null!=r&&"object"!==s(r)&&"function"!=typeof r)throw new u("error",["Object","Error","Function","RegExp"],r);if(t===w){var i="";r&&r.name&&(i+=" (".concat(r.name,")")),i+=n?": ".concat(n):".";var a="rejects"===e.name?"rejection":"exception";C({actual:void 0,expected:r,operator:e.name,message:"Missing expected ".concat(a).concat(i),stackStartFn:e})}if(r&&!k(t,r,n,e))throw t}function M(e,t,r,n){if(t!==w){if("string"==typeof r&&(n=r,r=void 0),!r||k(t,r)){var s=n?": ".concat(n):".",i="doesNotReject"===e.name?"rejection":"exception";C({actual:t,expected:r,operator:e.name,message:"Got unwanted ".concat(i).concat(s,"\n")+'Actual message: "'.concat(t&&t.message,'"'),stackStartFn:e})}throw t}}function L(e,t,r,n,i){if(!v(t))throw new u("regexp","RegExp",t);var a="match"===i;if("string"!=typeof e||S(t,e)!==a){if(r instanceof Error)throw r;var o=!r;r=r||("string"!=typeof e?'The "string" argument must be of type string. Received type '+"".concat(s(e)," (").concat(y(e),")"):(a?"The input did not match the regular expression ":"The input was expected to not match the regular expression ")+"".concat(y(t),". Input:\n\n").concat(y(e),"\n"));var l=new m({actual:e,expected:t,message:r,operator:i,stackStartFn:n});throw l.generatedMessage=o,l}}function F(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];O.apply(void 0,[F,t.length].concat(t))}A.throws=function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];B.apply(void 0,[e,_(t)].concat(n))},A.rejects=function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return j(t).then((function(t){return B.apply(void 0,[e,t].concat(n))}))},A.doesNotThrow=function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];M.apply(void 0,[e,_(t)].concat(n))},A.doesNotReject=function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return j(t).then((function(t){return M.apply(void 0,[e,t].concat(n))}))},A.ifError=function e(t){if(null!=t){var r="ifError got unwanted exception: ";"object"===s(t)&&"string"==typeof t.message?0===t.message.length&&t.constructor?r+=t.constructor.name:r+=t.message:r+=y(t);var n=new m({actual:t,expected:null,operator:"ifError",message:r,stackStartFn:e}),i=t.stack;if("string"==typeof i){var a=i.split("\n");a.shift();for(var o=n.stack.split("\n"),l=0;l<a.length;l++){var c=o.indexOf(a[l]);if(-1!==c){o=o.slice(0,c);break}}n.stack="".concat(o.join("\n"),"\n").concat(a.join("\n"))}throw n}},A.match=function e(t,r,n){L(t,r,n,e,"match")},A.doesNotMatch=function e(t,r,n){L(t,r,n,e,"doesNotMatch")},A.strict=T(F,A,{equal:A.strictEqual,deepEqual:A.deepStrictEqual,notEqual:A.notStrictEqual,notDeepEqual:A.notDeepStrictEqual}),A.strict.strict=A.strict},4150:e=>{function t(e){this.name="BrowserslistError",this.message=e,this.browserslist=!0,Error.captureStackTrace&&Error.captureStackTrace(this,t)}t.prototype=Error.prototype,e.exports=t},4184:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toGetWrapperPayload=function(e){return(t,r)=>{if(!1===e)return null;if((0,s.isSideEffectImport)(r)||r.reexportAll)return null;if(!0===e)return t.includes(".")?null:"lazy";if(Array.isArray(e))return e.includes(t)?"lazy":null;if("function"==typeof e)return e(t)?"lazy":null;throw new Error(".lazy must be a boolean, string array, or function")}},t.wrapReference=function(e,t){return"lazy"===t?n.types.callExpression(e,[]):null};var n=r(6416),s=r(7372)},4318:function(e,t){!function(e){"use strict";const t=",".charCodeAt(0),r=";".charCodeAt(0),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(64),i=new Uint8Array(128);for(let e=0;e<64;e++){const t=n.charCodeAt(e);s[e]=t,i[t]=e}function a(e,t){let r=0,n=0,s=0;do{const t=e.next();s=i[t],r|=(31&s)<<n,n+=5}while(32&s);const a=1&r;return r>>>=1,a&&(r=-2147483648|-r),t+r}function o(e,t,r){let n=t-r;n=n<0?-n<<1|1:n<<1;do{let t=31&n;n>>>=5,n>0&&(t|=32),e.write(s[t])}while(n>0);return t}function l(e,r){return!(e.pos>=r)&&e.peek()!==t}const c="undefined"!=typeof TextDecoder?new TextDecoder:"undefined"!=typeof Buffer?{decode:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString()}:{decode(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}};class p{constructor(){this.pos=0,this.out="",this.buffer=new Uint8Array(16384)}write(e){const{buffer:t}=this;t[this.pos++]=e,16384===this.pos&&(this.out+=c.decode(t),this.pos=0)}flush(){const{buffer:e,out:t,pos:r}=this;return r>0?t+c.decode(e.subarray(0,r)):t}}class u{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){const{buffer:t,pos:r}=this,n=t.indexOf(e,r);return-1===n?t.length:n}}const d=[];function f(e,r,n,s){const i=e[r],{0:a,1:l,2:c,3:p,4:u,vars:d}=i;r>0&&n.write(t),s[0]=o(n,a,s[0]),o(n,l,0),o(n,u,0),o(n,6===i.length?1:0,0),6===i.length&&o(n,i[5],0);for(const e of d)o(n,e,0);for(r++;r<e.length;){const t=e[r],{0:i,1:a}=t;if(i>c||i===c&&a>=p)break;r=f(e,r,n,s)}return n.write(t),s[0]=o(n,c,s[0]),o(n,p,0),r}function h(e,r,n,s){const i=e[r],{0:a,1:l,2:c,3:p,isScope:u,callsite:d,bindings:f}=i;if(s[0]<a?(m(n,s[0],a),s[0]=a,s[1]=0):r>0&&n.write(t),s[1]=o(n,i[1],s[1]),o(n,(6===i.length?1:0)|(d?2:0)|(u?4:0),0),6===i.length){const{4:e,5:t}=i;e!==s[2]&&(s[3]=0),s[2]=o(n,e,s[2]),s[3]=o(n,t,s[3])}if(d){const{0:e,1:t,2:r}=i.callsite;e!==s[4]?(s[5]=0,s[6]=0):t!==s[5]&&(s[6]=0),s[4]=o(n,e,s[4]),s[5]=o(n,t,s[5]),s[6]=o(n,r,s[6])}if(f)for(const e of f){e.length>1&&o(n,-e.length,0),o(n,e[0][0],0);let t=a,r=l;for(let s=1;s<e.length;s++){const i=e[s];t=o(n,i[1],t),r=o(n,i[2],r),o(n,i[0],0)}}for(r++;r<e.length;){const t=e[r],{0:i,1:a}=t;if(i>c||i===c&&a>=p)break;r=h(e,r,n,s)}return s[0]<c?(m(n,s[0],c),s[0]=c,s[1]=0):n.write(t),s[1]=o(n,p,s[1]),r}function m(e,t,n){do{e.write(r)}while(++t<n)}function y(e){e.sort(g)}function g(e,t){return e[0]-t[0]}e.decode=function(e){const{length:t}=e,r=new u(e),n=[];let s=0,i=0,o=0,c=0,p=0;do{const e=r.indexOf(";"),t=[];let u=!0,d=0;for(s=0;r.pos<e;){let n;s=a(r,s),s<d&&(u=!1),d=s,l(r,e)?(i=a(r,i),o=a(r,o),c=a(r,c),l(r,e)?(p=a(r,p),n=[s,i,o,c,p]):n=[s,i,o,c]):n=[s],t.push(n),r.pos++}u||y(t),n.push(t),r.pos=e+1}while(r.pos<=t);return n},e.decodeGeneratedRanges=function(e){const{length:t}=e,r=new u(e),n=[],s=[];let i=0,o=0,c=0,p=0,f=0,h=0,m=0,y=0;do{const e=r.indexOf(";");let t=0;for(;r.pos<e;r.pos++){if(t=a(r,t),!l(r,e)){const e=s.pop();e[2]=i,e[3]=t;continue}const u=a(r,0),g=2&u,b=4&u;let v,T=null,x=d;if(1&u){const e=a(r,o);c=a(r,o===e?c:0),o=e,v=[i,t,0,0,e,c]}else v=[i,t,0,0];if(v.isScope=!!b,g){const e=p,t=f;p=a(r,p);const n=e===p;f=a(r,n?f:0),h=a(r,n&&t===f?h:0),T=[p,f,h]}if(v.callsite=T,l(r,e)){x=[];do{m=i,y=t;const e=a(r,0);let n;if(e<-1){n=[[a(r,0)]];for(let t=-1;t>e;t--){const e=m;m=a(r,m),y=a(r,m===e?y:0);const t=a(r,0);n.push([t,m,y])}}else n=[[e]];x.push(n)}while(l(r,e))}v.bindings=x,n.push(v),s.push(v)}i++,r.pos=e+1}while(r.pos<t);return n},e.decodeOriginalScopes=function(e){const{length:t}=e,r=new u(e),n=[],s=[];let i=0;for(;r.pos<t;r.pos++){i=a(r,i);const e=a(r,0);if(!l(r,t)){const t=s.pop();t[2]=i,t[3]=e;continue}const o=a(r,0),c=1&a(r,0)?[i,e,0,0,o,a(r,0)]:[i,e,0,0,o];let p=d;if(l(r,t)){p=[];do{const e=a(r,0);p.push(e)}while(l(r,t))}c.vars=p,n.push(c),s.push(c)}return n},e.encode=function(e){const n=new p;let s=0,i=0,a=0,l=0;for(let c=0;c<e.length;c++){const p=e[c];if(c>0&&n.write(r),0===p.length)continue;let u=0;for(let e=0;e<p.length;e++){const r=p[e];e>0&&n.write(t),u=o(n,r[0],u),1!==r.length&&(s=o(n,r[1],s),i=o(n,r[2],i),a=o(n,r[3],a),4!==r.length&&(l=o(n,r[4],l)))}}return n.flush()},e.encodeGeneratedRanges=function(e){if(0===e.length)return"";const t=new p;for(let r=0;r<e.length;)r=h(e,r,t,[0,0,0,0,0,0,0]);return t.flush()},e.encodeOriginalScopes=function(e){const t=new p;for(let r=0;r<e.length;)r=f(e,r,t,[0]);return t.flush()},Object.defineProperty(e,"__esModule",{value:!0})}(t)},4364:(e,t,r)=>{var n=r(3909),s=r(6019).X,i=r(8093),a=r(3147),o=r(8411),l=r(4150),c=r(3928),p=r(6319);function u(e,t){return 0===(e+".").indexOf(t+".")}function d(e){return e.filter((function(e){return"string"==typeof e}))}function f(e){var t=e;return 3===e.split(".").length&&(t=e.split(".").slice(0,-1).join(".")),t}function h(e){return function(t){return e+" "+t}}function m(e){return parseInt(e.split(".")[0])}function y(e,t){if(0===e.length)return[];var r=g(e.map(m)),n=r[r.length-t];if(!n)return e;for(var s=[],i=e.length-1;i>=0&&!(n>m(e[i]));i--)s.unshift(e[i]);return s}function g(e){for(var t=[],r=0;r<e.length;r++)-1===t.indexOf(e[r])&&t.push(e[r]);return t}function b(e,t,r){for(var n in r)e[t+" "+n]=r[n]}function v(e,t){return t=parseFloat(t),">"===e?function(e){return r(e)>t}:">="===e?function(e){return r(e)>=t}:"<"===e?function(e){return parseFloat(e)<t}:function(e){return parseFloat(e)<=t};function r(e){return parseFloat(e.split("-")[1]||e)}}function T(e){return parseInt(e)}function x(e,t){return e<t?-1:e>t?1:0}function S(e,t){return x(parseInt(e[0]),parseInt(t[0]))||x(parseInt(e[1]||"0"),parseInt(t[1]||"0"))||x(parseInt(e[2]||"0"),parseInt(t[2]||"0"))}function E(e,t){return void 0===(t=t.split(".").map(T))[1]&&(t[1]="x"),"<="===e?function(e){return P(e=e.split(".").map(T),t)<=0}:function(e){return P(e=e.split(".").map(T),t)>=0}}function P(e,t){return e[0]!==t[0]?e[0]<t[0]?-1:1:"x"===t[1]?0:e[1]!==t[1]?e[1]<t[1]?-1:1:0}function A(e,t){var r=function(e,t){return-1!==e.versions.indexOf(t)?t:!!R.versionAliases[e.name][t]&&R.versionAliases[e.name][t]}(e,t);return r||1===e.versions.length&&e.versions[0]}function w(e,t){return e/=1e3,Object.keys(s).reduce((function(r,n){var s=O(n,t);if(!s)return r;var i=Object.keys(s.releaseDate).filter((function(t){var r=s.releaseDate[t];return null!==r&&r>=e}));return r.concat(i.map(h(s.name)))}),[])}function C(e){return{name:e.name,versions:e.versions,released:e.released,releaseDate:e.releaseDate}}function O(e,t){if(e=e.toLowerCase(),e=R.aliases[e]||e,t.mobileToDesktop&&R.desktopNames[e]){var r=R.data[R.desktopNames[e]];if("android"===e)return s=C(R.data[e]),i=r,s.released=I(s.released,i.released),s.versions=I(s.versions,i.versions),s.releaseDate=function(e){var t={};for(var r in e)t[r]=e[r];return t}(s.releaseDate),s.released.forEach((function(e){void 0===s.releaseDate[e]&&(s.releaseDate[e]=i.releaseDate[e])})),s;var n=C(r);return n.name=e,n}var s,i;return R.data[e]}function I(e,t){var r=t.indexOf("37");return e.filter((function(e){return/^(?:[2-4]\.|[34]$)/.test(e)})).concat(t.slice(r))}function N(e,t){var r=O(e,t);if(!r)throw new l("Unknown browser "+e);return r}function k(e,t,r,n){var s=1;switch(t){case"android":if(n.mobileToDesktop)return e;var i=R.data.chrome.released;s=i.length-i.indexOf("37");break;case"op_mob":s=m(R.data.op_mob.released.slice(-1)[0])-14+1;break;default:return e}return r<=s?e.slice(-1):e.slice(s-1-r)}function _(e,t){return"string"==typeof e&&(e.indexOf("y")>=0||t&&e.indexOf("a")>=0)}function D(e,t){return U(e).reduce((function(e,r,n){if(r.not&&0===n)throw new l("Write any browsers query (for instance, `defaults`) before `"+r.query+"`");var s=K[r.type].select.call(R,t,r).map((function(e){var r=e.split(" ");return"0"===r[1]?r[0]+" "+O(r[0],t).versions[0]:e}));if("and"===r.compose)return r.not?e.filter((function(e){return-1===s.indexOf(e)})):e.filter((function(e){return-1!==s.indexOf(e)}));if(r.not){var i={};return s.forEach((function(e){i[e]=!0})),e.filter((function(e){return!i[e]}))}return e.concat(s)}),[])}function j(e){return void 0===e&&(e={}),void 0===e.path&&(e.path=o.resolve?o.resolve("."):"."),e}function B(e,t){null==e&&(e=R.loadConfig(t)||R.defaults);return e}function M(e){if("string"!=typeof e&&!Array.isArray(e))throw new l("Browser queries must be an array or string. Got "+typeof e+".")}var L={},F={};function R(e,t){M(e=B(e,t=j(t)));var r=U(e).some((function(e){return K[e.type].needsPath})),n={ignoreUnknownVersions:t.ignoreUnknownVersions,dangerousExtend:t.dangerousExtend,mobileToDesktop:t.mobileToDesktop,env:t.env};r&&(n.path=t.path),c.oldDataWarning(R.data);var s=c.getStat(t,R.data);if(s)for(var i in n.customUsage={},s)b(n.customUsage,i,s[i]);var a=JSON.stringify([e,n]);if(L[a])return L[a];var o=g(D(e,n)).sort((function(e,t){if(e=e.split(" "),t=t.split(" "),e[0]===t[0]){var r=e[1].split("-")[0];return S(t[1].split("-")[0].split("."),r.split("."))}return x(e[0],t[0])}));return c.env.BROWSERSLIST_DISABLE_CACHE||(L[a]=o),o}function U(e){var t=JSON.stringify(e);if(t in F)return F[t];var r=p(K,e);return c.env.BROWSERSLIST_DISABLE_CACHE||(F[t]=r),r}function V(e,t){var r=R.nodeVersions.filter((function(e){return u(e,t.version)}));if(0===r.length){if(e.ignoreUnknownVersions)return[];throw new l("Unknown version "+t.version+" of Node.js")}return["node "+r[r.length-1]]}function q(e,t){var r=parseInt(t.year),n=parseInt(t.month||"01")-1,s=parseInt(t.day||"01");return w(Date.UTC(r,n,s,0,0,0),e)}function W(e,t){var r=parseFloat(t.coverage),n=R.usage.global;if(t.place)if(t.place.match(/^my\s+stats$/i)){if(!e.customUsage)throw new l("Custom usage statistics was not provided");n=e.customUsage}else{var s;s=2===t.place.length?t.place.toUpperCase():t.place.toLowerCase(),c.loadCountry(R.usage,s,R.data),n=R.usage[s]}for(var i,a=Object.keys(n).sort((function(e,t){return n[t]-n[e]})),o=0,p=[],u=0;u<a.length&&(i=a[u],0!==n[i])&&(o+=n[i],p.push(i),!(o>=r));u++);return p}R.parse=function(e,t){return M(e=B(e,t=j(t))),U(e)},R.cache={},R.data={},R.usage={global:{},custom:null},R.defaults=["> 0.5%","last 2 versions","Firefox ESR","not dead"],R.aliases={fx:"firefox",ff:"firefox",ios:"ios_saf",explorer:"ie",blackberry:"bb",explorermobile:"ie_mob",operamini:"op_mini",operamobile:"op_mob",chromeandroid:"and_chr",firefoxandroid:"and_ff",ucandroid:"and_uc",qqandroid:"and_qq"},R.desktopNames={and_chr:"chrome",and_ff:"firefox",ie_mob:"ie",android:"chrome"},R.versionAliases={},R.clearCaches=c.clearCaches,R.parseConfig=c.parseConfig,R.readConfig=c.readConfig,R.findConfigFile=c.findConfigFile,R.findConfig=c.findConfig,R.loadConfig=c.loadConfig,R.coverage=function(e,t){var r;if(void 0===t)r=R.usage.global;else if("my stats"===t){var n={};n.path=o.resolve?o.resolve("."):".";var s=c.getStat(n);if(!s)throw new l("Custom usage statistics was not provided");for(var i in r={},s)b(r,i,s[i])}else if("string"==typeof t)t=t.length>2?t.toLowerCase():t.toUpperCase(),c.loadCountry(R.usage,t,R.data),r=R.usage[t];else for(var a in"dataByBrowser"in t&&(t=t.dataByBrowser),r={},t)for(var p in t[a])r[a+" "+p]=t[a][p];return e.reduce((function(e,t){var n=r[t];return void 0===n&&(n=r[t.replace(/ \S+$/," 0")]),e+(n||0)}),0)};var K={last_major_versions:{matches:["versions"],regexp:/^last\s+(\d+)\s+major\s+versions?$/i,select:function(e,t){return Object.keys(s).reduce((function(r,n){var s=O(n,e);if(!s)return r;var i=y(s.released,t.versions);return i=k(i=i.map(h(s.name)),s.name,t.versions,e),r.concat(i)}),[])}},last_versions:{matches:["versions"],regexp:/^last\s+(\d+)\s+versions?$/i,select:function(e,t){return Object.keys(s).reduce((function(r,n){var s=O(n,e);if(!s)return r;var i=s.released.slice(-t.versions);return i=k(i=i.map(h(s.name)),s.name,t.versions,e),r.concat(i)}),[])}},last_electron_major_versions:{matches:["versions"],regexp:/^last\s+(\d+)\s+electron\s+major\s+versions?$/i,select:function(e,t){return y(Object.keys(i),t.versions).map((function(e){return"chrome "+i[e]}))}},last_node_major_versions:{matches:["versions"],regexp:/^last\s+(\d+)\s+node\s+major\s+versions?$/i,select:function(e,t){return y(R.nodeVersions,t.versions).map((function(e){return"node "+e}))}},last_browser_major_versions:{matches:["versions","browser"],regexp:/^last\s+(\d+)\s+(\w+)\s+major\s+versions?$/i,select:function(e,t){var r=N(t.browser,e),n=y(r.released,t.versions).map(h(r.name));return k(n,r.name,t.versions,e)}},last_electron_versions:{matches:["versions"],regexp:/^last\s+(\d+)\s+electron\s+versions?$/i,select:function(e,t){return Object.keys(i).slice(-t.versions).map((function(e){return"chrome "+i[e]}))}},last_node_versions:{matches:["versions"],regexp:/^last\s+(\d+)\s+node\s+versions?$/i,select:function(e,t){return R.nodeVersions.slice(-t.versions).map((function(e){return"node "+e}))}},last_browser_versions:{matches:["versions","browser"],regexp:/^last\s+(\d+)\s+(\w+)\s+versions?$/i,select:function(e,t){var r=N(t.browser,e),n=r.released.slice(-t.versions).map(h(r.name));return k(n,r.name,t.versions,e)}},unreleased_versions:{matches:[],regexp:/^unreleased\s+versions$/i,select:function(e){return Object.keys(s).reduce((function(t,r){var n=O(r,e);if(!n)return t;var s=n.versions.filter((function(e){return-1===n.released.indexOf(e)}));return s=s.map(h(n.name)),t.concat(s)}),[])}},unreleased_electron_versions:{matches:[],regexp:/^unreleased\s+electron\s+versions?$/i,select:function(){return[]}},unreleased_browser_versions:{matches:["browser"],regexp:/^unreleased\s+(\w+)\s+versions?$/i,select:function(e,t){var r=N(t.browser,e);return r.versions.filter((function(e){return-1===r.released.indexOf(e)})).map(h(r.name))}},last_years:{matches:["years"],regexp:/^last\s+(\d*.?\d+)\s+years?$/i,select:function(e,t){return w(Date.now()-31558432982.4*t.years,e)}},since_y:{matches:["year"],regexp:/^since (\d+)$/i,select:q},since_y_m:{matches:["year","month"],regexp:/^since (\d+)-(\d+)$/i,select:q},since_y_m_d:{matches:["year","month","day"],regexp:/^since (\d+)-(\d+)-(\d+)$/i,select:q},popularity:{matches:["sign","popularity"],regexp:/^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%$/,select:function(e,t){var r=parseFloat(t.popularity),n=R.usage.global;return Object.keys(n).reduce((function(e,s){return">"===t.sign?n[s]>r&&e.push(s):"<"===t.sign?n[s]<r&&e.push(s):"<="===t.sign?n[s]<=r&&e.push(s):n[s]>=r&&e.push(s),e}),[])}},popularity_in_my_stats:{matches:["sign","popularity"],regexp:/^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%\s+in\s+my\s+stats$/,select:function(e,t){var r=parseFloat(t.popularity);if(!e.customUsage)throw new l("Custom usage statistics was not provided");var n=e.customUsage;return Object.keys(n).reduce((function(e,s){var i=n[s];return null==i||(">"===t.sign?i>r&&e.push(s):"<"===t.sign?i<r&&e.push(s):"<="===t.sign?i<=r&&e.push(s):i>=r&&e.push(s)),e}),[])}},popularity_in_config_stats:{matches:["sign","popularity","config"],regexp:/^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%\s+in\s+(\S+)\s+stats$/,select:function(e,t){var r=parseFloat(t.popularity),n=c.loadStat(e,t.config,R.data);if(n)for(var s in e.customUsage={},n)b(e.customUsage,s,n[s]);if(!e.customUsage)throw new l("Custom usage statistics was not provided");var i=e.customUsage;return Object.keys(i).reduce((function(e,n){var s=i[n];return null==s||(">"===t.sign?s>r&&e.push(n):"<"===t.sign?s<r&&e.push(n):"<="===t.sign?s<=r&&e.push(n):s>=r&&e.push(n)),e}),[])}},popularity_in_place:{matches:["sign","popularity","place"],regexp:/^(>=?|<=?)\s*(\d+|\d+\.\d+|\.\d+)%\s+in\s+((alt-)?\w\w)$/,select:function(e,t){var r=parseFloat(t.popularity),n=t.place;n=2===n.length?n.toUpperCase():n.toLowerCase(),c.loadCountry(R.usage,n,R.data);var s=R.usage[n];return Object.keys(s).reduce((function(e,n){var i=s[n];return null==i||(">"===t.sign?i>r&&e.push(n):"<"===t.sign?i<r&&e.push(n):"<="===t.sign?i<=r&&e.push(n):i>=r&&e.push(n)),e}),[])}},cover:{matches:["coverage"],regexp:/^cover\s+(\d+|\d+\.\d+|\.\d+)%$/i,select:W},cover_in:{matches:["coverage","place"],regexp:/^cover\s+(\d+|\d+\.\d+|\.\d+)%\s+in\s+(my\s+stats|(alt-)?\w\w)$/i,select:W},supports:{matches:["supportType","feature"],regexp:/^(?:(fully|partially)\s+)?supports\s+([\w-]+)$/,select:function(e,t){c.loadFeature(R.cache,t.feature);var r="fully"!==t.supportType,n=R.cache[t.feature],s=[];for(var i in n){for(var a=O(i,e),o=a.released.length-1;o>=0&&!(a.released[o]in n[i]);)o--;var l=e.mobileToDesktop&&i in R.desktopNames&&_(n[i][a.released[o]],r);a.versions.forEach((function(e){var t=n[i][e];void 0===t&&l&&(t=n[R.desktopNames[i]][e]),_(t,r)&&s.push(i+" "+e)}))}return s}},electron_range:{matches:["from","to"],regexp:/^electron\s+([\d.]+)\s*-\s*([\d.]+)$/i,select:function(e,t){var r=f(t.from),n=f(t.to),s=parseFloat(t.from),a=parseFloat(t.to);if(!i[r])throw new l("Unknown version "+s+" of electron");if(!i[n])throw new l("Unknown version "+a+" of electron");return Object.keys(i).filter((function(e){var t=parseFloat(e);return t>=s&&t<=a})).map((function(e){return"chrome "+i[e]}))}},node_range:{matches:["from","to"],regexp:/^node\s+([\d.]+)\s*-\s*([\d.]+)$/i,select:function(e,t){return R.nodeVersions.filter(E(">=",t.from)).filter(E("<=",t.to)).map((function(e){return"node "+e}))}},browser_range:{matches:["browser","from","to"],regexp:/^(\w+)\s+([\d.]+)\s*-\s*([\d.]+)$/i,select:function(e,t){var r=N(t.browser,e),n=parseFloat(A(r,t.from)||t.from),s=parseFloat(A(r,t.to)||t.to);return r.released.filter((function(e){var t=parseFloat(e);return t>=n&&t<=s})).map(h(r.name))}},electron_ray:{matches:["sign","version"],regexp:/^electron\s*(>=?|<=?)\s*([\d.]+)$/i,select:function(e,t){var r=f(t.version);return Object.keys(i).filter(v(t.sign,r)).map((function(e){return"chrome "+i[e]}))}},node_ray:{matches:["sign","version"],regexp:/^node\s*(>=?|<=?)\s*([\d.]+)$/i,select:function(e,t){return R.nodeVersions.filter((r=t.sign,n=t.version,(n=n.split(".").map(T))[1]=n[1]||0,n[2]=n[2]||0,">"===r?function(e){return S(e=e.split(".").map(T),n)>0}:">="===r?function(e){return S(e=e.split(".").map(T),n)>=0}:"<"===r?function(e){return e=e.split(".").map(T),S(n,e)>0}:function(e){return e=e.split(".").map(T),S(n,e)>=0})).map((function(e){return"node "+e}));var r,n}},browser_ray:{matches:["browser","sign","version"],regexp:/^(\w+)\s*(>=?|<=?)\s*([\d.]+)$/,select:function(e,t){var r=t.version,n=N(t.browser,e),s=R.versionAliases[n.name][r];return s&&(r=s),n.released.filter(v(t.sign,r)).map((function(e){return n.name+" "+e}))}},firefox_esr:{matches:[],regexp:/^(firefox|ff|fx)\s+esr$/i,select:function(){return["firefox 128"]}},opera_mini_all:{matches:[],regexp:/(operamini|op_mini)\s+all/i,select:function(){return["op_mini all"]}},electron_version:{matches:["version"],regexp:/^electron\s+([\d.]+)$/i,select:function(e,t){var r=f(t.version),n=i[r];if(!n)throw new l("Unknown version "+t.version+" of electron");return["chrome "+n]}},node_major_version:{matches:["version"],regexp:/^node\s+(\d+)$/i,select:V},node_minor_version:{matches:["version"],regexp:/^node\s+(\d+\.\d+)$/i,select:V},node_patch_version:{matches:["version"],regexp:/^node\s+(\d+\.\d+\.\d+)$/i,select:V},current_node:{matches:[],regexp:/^current\s+node$/i,select:function(e){return[c.currentNode(D,e)]}},maintained_node:{matches:[],regexp:/^maintained\s+node\s+versions$/i,select:function(e){var t=Date.now();return D(Object.keys(a).filter((function(e){return t<Date.parse(a[e].end)&&t>Date.parse(a[e].start)&&(r=e.slice(1),R.nodeVersions.some((function(e){return u(e,r)})));var r})).map((function(e){return"node "+e.slice(1)})),e)}},phantomjs_1_9:{matches:[],regexp:/^phantomjs\s+1.9$/i,select:function(){return["safari 5"]}},phantomjs_2_1:{matches:[],regexp:/^phantomjs\s+2.1$/i,select:function(){return["safari 6"]}},browser_version:{matches:["browser","version"],regexp:/^(\w+)\s+(tp|[\d.]+)$/i,select:function(e,t){var r=t.version;/^tp$/i.test(r)&&(r="TP");var n=N(t.browser,e),s=A(n,r);if(s)r=s;else{if(!(s=A(n,s=-1===r.indexOf(".")?r+".0":r.replace(/\.0$/,"")))){if(e.ignoreUnknownVersions)return[];throw new l("Unknown version "+r+" of "+t.browser)}r=s}return[n.name+" "+r]}},browserslist_config:{matches:[],regexp:/^browserslist config$/i,needsPath:!0,select:function(e){return R(void 0,e)}},extends:{matches:["config"],regexp:/^extends (.+)$/i,needsPath:!0,select:function(e,t){return D(c.loadQueries(e,t.config),e)}},defaults:{matches:[],regexp:/^defaults$/i,select:function(e){return D(R.defaults,e)}},dead:{matches:[],regexp:/^dead$/i,select:function(e){return D(["Baidu >= 0","ie <= 11","ie_mob <= 11","bb <= 10","op_mob <= 12.1","samsung 4"],e)}},unknown:{matches:[],regexp:/^(\w+)$/i,select:function(e,t){throw O(t.query,e)?new l("Specify versions in Browserslist query for browser "+t.query):(r=t.query,new l("Unknown browser query `"+r+"`. Maybe you are using old Browserslist or made typo in query."));var r}}};!function(){for(var e in s){var t=s[e];R.data[e]={name:e,versions:d(s[e].versions),released:d(s[e].versions.slice(0,-3)),releaseDate:s[e].release_date},b(R.usage.global,e,t.usage_global),R.versionAliases[e]={};for(var r=0;r<t.versions.length;r++){var i=t.versions[r];if(i&&-1!==i.indexOf("-"))for(var a=i.split("-"),o=0;o<a.length;o++)R.versionAliases[e][a[o]]=i}}R.nodeVersions=n.map((function(e){return e.version}))}(),e.exports=R},4374:(e,t,r)=>{"use strict";function n(){const e=r(906);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.access=a,t.assertArray=c,t.assertAssumptions=function(e,t){if(void 0===t)return;if("object"!=typeof t||null===t)throw new Error(`${i(e)} must be an object or undefined.`);let r=e;do{r=r.parent}while("root"!==r.type);const n="preset"===r.source;for(const r of Object.keys(t)){const o=a(e,r);if(!s.assumptionsNames.has(r))throw new Error(`${i(o)} is not a supported assumption.`);if("boolean"!=typeof t[r])throw new Error(`${i(o)} must be a boolean.`);if(n&&!1===t[r])throw new Error(`${i(o)} cannot be set to 'false' inside presets.`)}return t},t.assertBabelrcSearch=function(e,t){if(void 0===t||"boolean"==typeof t)return t;if(Array.isArray(t))t.forEach(((t,r)=>{if(!p(t))throw new Error(`${i(a(e,r))} must be a string/Function/RegExp.`)}));else if(!p(t))throw new Error(`${i(e)} must be a undefined, a boolean, a string/Function/RegExp or an array of those, got ${JSON.stringify(t)}`);return t},t.assertBoolean=o,t.assertCallerMetadata=function(e,t){const r=l(e,t);if(r){if("string"!=typeof r.name)throw new Error(`${i(e)} set but does not contain "name" property string`);for(const t of Object.keys(r)){const n=a(e,t),s=r[t];if(null!=s&&"boolean"!=typeof s&&"string"!=typeof s&&"number"!=typeof s)throw new Error(`${i(n)} must be null, undefined, a boolean, a string, or a number.`)}}return t},t.assertCompact=function(e,t){if(void 0!==t&&"boolean"!=typeof t&&"auto"!==t)throw new Error(`${i(e)} must be a boolean, "auto", or undefined`);return t},t.assertConfigApplicableTest=function(e,t){if(void 0===t)return t;if(Array.isArray(t))t.forEach(((t,r)=>{if(!p(t))throw new Error(`${i(a(e,r))} must be a string/Function/RegExp.`)}));else if(!p(t))throw new Error(`${i(e)} must be a string/Function/RegExp, or an array of those`);return t},t.assertConfigFileSearch=function(e,t){if(void 0!==t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error(`${i(e)} must be a undefined, a boolean, a string, got ${JSON.stringify(t)}`);return t},t.assertFunction=function(e,t){if(void 0!==t&&"function"!=typeof t)throw new Error(`${i(e)} must be a function, or undefined`);return t},t.assertIgnoreList=function(e,t){const r=c(e,t);return null==r||r.forEach(((t,r)=>function(e,t){if("string"!=typeof t&&"function"!=typeof t&&!(t instanceof RegExp))throw new Error(`${i(e)} must be an array of string/Function/RegExp values, or undefined`);return t}(a(e,r),t))),r},t.assertInputSourceMap=function(e,t){if(void 0!==t&&"boolean"!=typeof t&&("object"!=typeof t||!t))throw new Error(`${i(e)} must be a boolean, object, or undefined`);return t},t.assertObject=l,t.assertPluginList=function(e,t){const r=c(e,t);return r&&r.forEach(((t,r)=>function(e,t){if(Array.isArray(t)){if(0===t.length)throw new Error(`${i(e)} must include an object`);if(t.length>3)throw new Error(`${i(e)} may only be a two-tuple or three-tuple`);if(u(a(e,0),t[0]),t.length>1){const r=t[1];if(void 0!==r&&!1!==r&&("object"!=typeof r||Array.isArray(r)||null===r))throw new Error(`${i(a(e,1))} must be an object, false, or undefined`)}if(3===t.length){const r=t[2];if(void 0!==r&&"string"!=typeof r)throw new Error(`${i(a(e,2))} must be a string, or undefined`)}}else u(e,t);return t}(a(e,r),t))),r},t.assertRootMode=function(e,t){if(void 0!==t&&"root"!==t&&"upward"!==t&&"upward-optional"!==t)throw new Error(`${i(e)} must be a "root", "upward", "upward-optional" or undefined`);return t},t.assertSourceMaps=function(e,t){if(void 0!==t&&"boolean"!=typeof t&&"inline"!==t&&"both"!==t)throw new Error(`${i(e)} must be a boolean, "inline", "both", or undefined`);return t},t.assertSourceType=function(e,t){if(void 0!==t&&"module"!==t&&"script"!==t&&"unambiguous"!==t)throw new Error(`${i(e)} must be "module", "script", "unambiguous", or undefined`);return t},t.assertString=function(e,t){if(void 0!==t&&"string"!=typeof t)throw new Error(`${i(e)} must be a string, or undefined`);return t},t.assertTargets=function(e,t){if((0,n().isBrowsersQueryValid)(t))return t;if("object"!=typeof t||!t||Array.isArray(t))throw new Error(`${i(e)} must be a string, an array of strings or an object`);const r=a(e,"browsers"),s=a(e,"esmodules");d(r,t.browsers),o(s,t.esmodules);for(const r of Object.keys(t)){const s=t[r],l=a(e,r);if("esmodules"===r)o(l,s);else if("browsers"===r)d(l,s);else{if(!hasOwnProperty.call(n().TargetNames,r)){const e=Object.keys(n().TargetNames).join(", ");throw new Error(`${i(l)} is not a valid target. Supported targets are ${e}`)}f(l,s)}}return t},t.msg=i;var s=r(7165);function i(e){switch(e.type){case"root":return"";case"env":return`${i(e.parent)}.env["${e.name}"]`;case"overrides":return`${i(e.parent)}.overrides[${e.index}]`;case"option":return`${i(e.parent)}.${e.name}`;case"access":return`${i(e.parent)}[${JSON.stringify(e.name)}]`;default:throw new Error(`Assertion failure: Unknown type ${e.type}`)}}function a(e,t){return{type:"access",name:t,parent:e}}function o(e,t){if(void 0!==t&&"boolean"!=typeof t)throw new Error(`${i(e)} must be a boolean, or undefined`);return t}function l(e,t){if(void 0!==t&&("object"!=typeof t||Array.isArray(t)||!t))throw new Error(`${i(e)} must be an object, or undefined`);return t}function c(e,t){if(null!=t&&!Array.isArray(t))throw new Error(`${i(e)} must be an array, or undefined`);return t}function p(e){return"string"==typeof e||"function"==typeof e||e instanceof RegExp}function u(e,t){if(("object"!=typeof t||!t)&&"string"!=typeof t&&"function"!=typeof t)throw new Error(`${i(e)} must be a string, object, function`);return t}function d(e,t){if(void 0!==t&&!(0,n().isBrowsersQueryValid)(t))throw new Error(`${i(e)} must be undefined, a string or an array of strings`)}function f(e,t){if(("number"!=typeof t||Math.round(t)!==t)&&"string"!=typeof t)throw new Error(`${i(e)} must be a string or an integer number`)}},4418:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(4148),s=r(2352);const{callExpression:i,cloneNode:a,expressionStatement:o,identifier:l,importDeclaration:c,importDefaultSpecifier:p,importNamespaceSpecifier:u,importSpecifier:d,memberExpression:f,stringLiteral:h,variableDeclaration:m,variableDeclarator:y}=s;t.default=class{constructor(e,t,r){this._statements=[],this._resultName=null,this._importedSource=void 0,this._scope=t,this._hub=r,this._importedSource=e}done(){return{statements:this._statements,resultName:this._resultName}}import(){return this._statements.push(c([],h(this._importedSource))),this}require(){return this._statements.push(o(i(l("require"),[h(this._importedSource)]))),this}namespace(e="namespace"){const t=this._scope.generateUidIdentifier(e),r=this._statements[this._statements.length-1];return n("ImportDeclaration"===r.type),n(0===r.specifiers.length),r.specifiers=[u(t)],this._resultName=a(t),this}default(e){const t=this._scope.generateUidIdentifier(e),r=this._statements[this._statements.length-1];return n("ImportDeclaration"===r.type),n(0===r.specifiers.length),r.specifiers=[p(t)],this._resultName=a(t),this}named(e,t){if("default"===t)return this.default(e);const r=this._scope.generateUidIdentifier(e),s=this._statements[this._statements.length-1];return n("ImportDeclaration"===s.type),n(0===s.specifiers.length),s.specifiers=[d(r,l(t))],this._resultName=a(r),this}var(e){const t=this._scope.generateUidIdentifier(e);let r=this._statements[this._statements.length-1];return"ExpressionStatement"!==r.type&&(n(this._resultName),r=o(this._resultName),this._statements.push(r)),this._statements[this._statements.length-1]=m("var",[y(t,r.expression)]),this._resultName=a(t),this}defaultInterop(){return this._interop(this._hub.addHelper("interopRequireDefault"))}wildcardInterop(){return this._interop(this._hub.addHelper("interopRequireWildcard"))}_interop(e){const t=this._statements[this._statements.length-1];return"ExpressionStatement"===t.type?t.expression=i(e,[t.expression]):"VariableDeclaration"===t.type?(n(1===t.declarations.length),t.declarations[0].init=i(e,[t.declarations[0].init])):n.fail("Unexpected type."),this}prop(e){const t=this._statements[this._statements.length-1];return"ExpressionStatement"===t.type?t.expression=f(t.expression,l(e)):"VariableDeclaration"===t.type?(n(1===t.declarations.length),t.declarations[0].init=f(t.declarations[0].init,l(e))):n.fail("Unexpected type:"+t.type),this}read(e){this._resultName=f(this._resultName,l(e))}}},4424:function(e){e.exports=function(){"use strict";const e=/^[\w+.-]+:\/\//,t=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,r=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function n(e){return e.startsWith("/")}function s(e){return/^[.?#]/.test(e)}function i(e){const r=t.exec(e);return a(r[1],r[2]||"",r[3],r[4]||"",r[5]||"/",r[6]||"",r[7]||"")}function a(e,t,r,n,s,i,a){return{scheme:e,user:t,host:r,port:n,path:s,query:i,hash:a,type:7}}function o(t){if(function(e){return e.startsWith("//")}(t)){const e=i("http:"+t);return e.scheme="",e.type=6,e}if(n(t)){const e=i("http://foo.com"+t);return e.scheme="",e.host="",e.type=5,e}if(function(e){return e.startsWith("file:")}(t))return function(e){const t=r.exec(e),s=t[2];return a("file:","",t[1]||"","",n(s)?s:"/"+s,t[3]||"",t[4]||"")}(t);if(function(t){return e.test(t)}(t))return i(t);const s=i("http://foo.com/"+t);return s.scheme="",s.host="",s.type=t?t.startsWith("?")?3:t.startsWith("#")?2:4:1,s}function l(e,t){const r=t<=4,n=e.path.split("/");let s=1,i=0,a=!1;for(let e=1;e<n.length;e++){const t=n[e];t?(a=!1,"."!==t&&(".."!==t?(n[s++]=t,i++):i?(a=!0,i--,s--):r&&(n[s++]=t))):a=!0}let o="";for(let e=1;e<s;e++)o+="/"+n[e];(!o||a&&!o.endsWith("/.."))&&(o+="/"),e.path=o}return function(e,t){if(!e&&!t)return"";const r=o(e);let n=r.type;if(t&&7!==n){const e=o(t),s=e.type;switch(n){case 1:r.hash=e.hash;case 2:r.query=e.query;case 3:case 4:!function(e,t){l(t,t.type),"/"===e.path?e.path=t.path:e.path=function(e){if(e.endsWith("/.."))return e;const t=e.lastIndexOf("/");return e.slice(0,t+1)}(t.path)+e.path}(r,e);case 5:r.user=e.user,r.host=e.host,r.port=e.port;case 6:r.scheme=e.scheme}s>n&&(n=s)}l(r,n);const i=r.query+r.hash;switch(n){case 2:case 3:return i;case 4:{const n=r.path.slice(1);return n?s(t||e)&&!s(n)?"./"+n+i:n+i:i||"."}case 5:return r.path+i;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+i}}}()},4436:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogicalExpression=t.BinaryExpression=t.AssignmentExpression=function(e){this.print(e.left),this.space(),"in"===e.operator||"instanceof"===e.operator?this.word(e.operator):(this.token(e.operator),this._endsWithDiv="/"===e.operator),this.space(),this.print(e.right)},t.AssignmentPattern=function(e){this.print(e.left),("Identifier"===e.left.type||c(e.left))&&(e.left.optional&&this.tokenChar(63),this.print(e.left.typeAnnotation)),this.space(),this.tokenChar(61),this.space(),this.print(e.right)},t.AwaitExpression=function(e){this.word("await"),e.argument&&(this.space(),this.printTerminatorless(e.argument))},t.BindExpression=function(e){this.print(e.object),this.token("::"),this.print(e.callee)},t.CallExpression=function(e){this.print(e.callee),this.print(e.typeArguments),this.print(e.typeParameters),this.tokenChar(40);const t=this.enterDelimited();this.printList(e.arguments,this.shouldPrintTrailingComma(")")),t(),this.rightParens(e)},t.ConditionalExpression=function(e){this.print(e.test),this.space(),this.tokenChar(63),this.space(),this.print(e.consequent),this.space(),this.tokenChar(58),this.space(),this.print(e.alternate)},t.Decorator=function(e){this.tokenChar(64),this.print(e.expression),this.newline()},t.DoExpression=function(e){e.async&&(this.word("async",!0),this.space()),this.word("do"),this.space(),this.print(e.body)},t.EmptyStatement=function(){this.semicolon(!0)},t.ExpressionStatement=function(e){this.tokenContext|=s.TokenContext.expressionStatement,this.print(e.expression),this.semicolon()},t.Import=function(){this.word("import")},t.MemberExpression=function(e){if(this.print(e.object),!e.computed&&o(e.property))throw new TypeError("Got a MemberExpression for MemberExpression property");let t=e.computed;if(a(e.property)&&"number"==typeof e.property.value&&(t=!0),t){const t=this.enterDelimited();this.tokenChar(91),this.print(e.property),this.tokenChar(93),t()}else this.tokenChar(46),this.print(e.property)},t.MetaProperty=function(e){this.print(e.meta),this.tokenChar(46),this.print(e.property)},t.ModuleExpression=function(e){this.word("module",!0),this.space(),this.tokenChar(123),this.indent();const{body:t}=e;(t.body.length||t.directives.length)&&this.newline(),this.print(t),this.dedent(),this.rightBrace(e)},t.NewExpression=function(e,t){if(this.word("new"),this.space(),this.print(e.callee),this.format.minified&&0===e.arguments.length&&!e.optional&&!i(t,{callee:e})&&!o(t)&&!l(t))return;if(this.print(e.typeArguments),this.print(e.typeParameters),e.optional&&this.token("?."),0===e.arguments.length&&this.tokenMap&&!this.tokenMap.endMatches(e,")"))return;this.tokenChar(40);const r=this.enterDelimited();this.printList(e.arguments,this.shouldPrintTrailingComma(")")),r(),this.rightParens(e)},t.OptionalCallExpression=function(e){this.print(e.callee),this.print(e.typeParameters),e.optional&&this.token("?."),this.print(e.typeArguments),this.tokenChar(40);const t=this.enterDelimited();this.printList(e.arguments),t(),this.rightParens(e)},t.OptionalMemberExpression=function(e){let{computed:t}=e;const{optional:r,property:n}=e;if(this.print(e.object),!t&&o(n))throw new TypeError("Got a MemberExpression for MemberExpression property");a(n)&&"number"==typeof n.value&&(t=!0),r&&this.token("?."),t?(this.tokenChar(91),this.print(n),this.tokenChar(93)):(r||this.tokenChar(46),this.print(n))},t.ParenthesizedExpression=function(e){this.tokenChar(40);const t=this.enterDelimited();this.print(e.expression),t(),this.rightParens(e)},t.PrivateName=function(e){this.tokenChar(35),this.print(e.id)},t.SequenceExpression=function(e){this.printList(e.expressions)},t.Super=function(){this.word("super")},t.ThisExpression=function(){this.word("this")},t.UnaryExpression=function(e){const{operator:t}=e;"void"===t||"delete"===t||"typeof"===t||"throw"===t?(this.word(t),this.space()):this.token(t),this.print(e.argument)},t.UpdateExpression=function(e){e.prefix?(this.token(e.operator),this.print(e.argument)):(this.print(e.argument,!0),this.token(e.operator))},t.V8IntrinsicIdentifier=function(e){this.tokenChar(37),this.word(e.name)},t.YieldExpression=function(e){this.word("yield",!0),e.delegate?(this.tokenChar(42),e.argument&&(this.space(),this.print(e.argument))):e.argument&&(this.space(),this.printTerminatorless(e.argument))},t._shouldPrintDecoratorsBeforeExport=function(e){return"boolean"==typeof this.format.decoratorsBeforeExport?this.format.decoratorsBeforeExport:"number"==typeof e.start&&e.start===e.declaration.start};var n=r(2352),s=r(1373);const{isCallExpression:i,isLiteral:a,isMemberExpression:o,isNewExpression:l,isPattern:c}=n},4459:e=>{"use strict";e.exports=Number.isNaN||function(e){return e!=e}},4460:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(e===t)return!0;if(null==e)return!1;if(n.ALIAS_KEYS[t])return!1;const r=n.FLIPPED_ALIAS_KEYS[t];if(r){if(r[0]===e)return!0;for(const t of r)if(e===t)return!0}return!1};var n=r(9793)},4466:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(t,r){const l=new WeakMap,c=new WeakMap,p=r||(0,n.validate)(null);return Object.assign(((r,...a)=>{if("string"==typeof r){if(a.length>1)throw new Error("Unexpected extra params.");return o((0,s.default)(t,r,(0,n.merge)(p,(0,n.validate)(a[0]))))}if(Array.isArray(r)){let e=l.get(r);return e||(e=(0,i.default)(t,r,p),l.set(r,e)),o(e(a))}if("object"==typeof r&&r){if(a.length>0)throw new Error("Unexpected extra params.");return e(t,(0,n.merge)(p,(0,n.validate)(r)))}throw new Error("Unexpected template param "+typeof r)}),{ast:(e,...r)=>{if("string"==typeof e){if(r.length>1)throw new Error("Unexpected extra params.");return(0,s.default)(t,e,(0,n.merge)((0,n.merge)(p,(0,n.validate)(r[0])),a))()}if(Array.isArray(e)){let s=c.get(e);return s||(s=(0,i.default)(t,e,(0,n.merge)(p,a)),c.set(e,s)),s(r)()}throw new Error("Unexpected template param "+typeof e)}})};var n=r(9815),s=r(5252),i=r(3438);const a=(0,n.validate)({placeholderPattern:!1});function o(e){let t="";try{throw new Error}catch(e){e.stack&&(t=e.stack.split("\n").slice(3).join("\n"))}return r=>{try{return e(r)}catch(e){throw e.stack+=`\n =============\n${t}`,e}}}},4544:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(983),s=r(8079);t.default=function e(t){if(void 0===t)return(0,s.identifier)("undefined");if(!0===t||!1===t)return(0,s.booleanLiteral)(t);if(null===t)return(0,s.nullLiteral)();if("string"==typeof t)return(0,s.stringLiteral)(t);if("number"==typeof t){let e;if(Number.isFinite(t))e=(0,s.numericLiteral)(Math.abs(t));else{let r;r=Number.isNaN(t)?(0,s.numericLiteral)(0):(0,s.numericLiteral)(1),e=(0,s.binaryExpression)("/",r,(0,s.numericLiteral)(0))}return(t<0||Object.is(t,-0))&&(e=(0,s.unaryExpression)("-",e)),e}if(function(e){return"[object RegExp]"===i(e)}(t)){const e=t.source,r=/\/([a-z]*)$/.exec(t.toString())[1];return(0,s.regExpLiteral)(e,r)}if(Array.isArray(t))return(0,s.arrayExpression)(t.map(e));if(function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}(t)){const r=[];for(const i of Object.keys(t)){let a;a=(0,n.default)(i)?(0,s.identifier)(i):(0,s.stringLiteral)(i),r.push((0,s.objectProperty)(a,e(t[i])))}return(0,s.objectExpression)(r)}throw new Error("don't know how to turn this value into a node")};const i=Function.call.bind(Object.prototype.toString)},4568:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if(!(0,n.default)(e)){var t;const r=null!=(t=null==e?void 0:e.type)?t:JSON.stringify(e);throw new TypeError(`Not a valid node of type "${r}"`)}};var n=r(3908)},4652:e=>{"use strict";e.exports=JSON.parse('{"builtin":{"Array":false,"ArrayBuffer":false,"Atomics":false,"BigInt":false,"BigInt64Array":false,"BigUint64Array":false,"Boolean":false,"constructor":false,"DataView":false,"Date":false,"decodeURI":false,"decodeURIComponent":false,"encodeURI":false,"encodeURIComponent":false,"Error":false,"escape":false,"eval":false,"EvalError":false,"Float32Array":false,"Float64Array":false,"Function":false,"globalThis":false,"hasOwnProperty":false,"Infinity":false,"Int16Array":false,"Int32Array":false,"Int8Array":false,"isFinite":false,"isNaN":false,"isPrototypeOf":false,"JSON":false,"Map":false,"Math":false,"NaN":false,"Number":false,"Object":false,"parseFloat":false,"parseInt":false,"Promise":false,"propertyIsEnumerable":false,"Proxy":false,"RangeError":false,"ReferenceError":false,"Reflect":false,"RegExp":false,"Set":false,"SharedArrayBuffer":false,"String":false,"Symbol":false,"SyntaxError":false,"toLocaleString":false,"toString":false,"TypeError":false,"Uint16Array":false,"Uint32Array":false,"Uint8Array":false,"Uint8ClampedArray":false,"undefined":false,"unescape":false,"URIError":false,"valueOf":false,"WeakMap":false,"WeakSet":false},"es5":{"Array":false,"Boolean":false,"constructor":false,"Date":false,"decodeURI":false,"decodeURIComponent":false,"encodeURI":false,"encodeURIComponent":false,"Error":false,"escape":false,"eval":false,"EvalError":false,"Function":false,"hasOwnProperty":false,"Infinity":false,"isFinite":false,"isNaN":false,"isPrototypeOf":false,"JSON":false,"Math":false,"NaN":false,"Number":false,"Object":false,"parseFloat":false,"parseInt":false,"propertyIsEnumerable":false,"RangeError":false,"ReferenceError":false,"RegExp":false,"String":false,"SyntaxError":false,"toLocaleString":false,"toString":false,"TypeError":false,"undefined":false,"unescape":false,"URIError":false,"valueOf":false},"es2015":{"Array":false,"ArrayBuffer":false,"Boolean":false,"constructor":false,"DataView":false,"Date":false,"decodeURI":false,"decodeURIComponent":false,"encodeURI":false,"encodeURIComponent":false,"Error":false,"escape":false,"eval":false,"EvalError":false,"Float32Array":false,"Float64Array":false,"Function":false,"hasOwnProperty":false,"Infinity":false,"Int16Array":false,"Int32Array":false,"Int8Array":false,"isFinite":false,"isNaN":false,"isPrototypeOf":false,"JSON":false,"Map":false,"Math":false,"NaN":false,"Number":false,"Object":false,"parseFloat":false,"parseInt":false,"Promise":false,"propertyIsEnumerable":false,"Proxy":false,"RangeError":false,"ReferenceError":false,"Reflect":false,"RegExp":false,"Set":false,"String":false,"Symbol":false,"SyntaxError":false,"toLocaleString":false,"toString":false,"TypeError":false,"Uint16Array":false,"Uint32Array":false,"Uint8Array":false,"Uint8ClampedArray":false,"undefined":false,"unescape":false,"URIError":false,"valueOf":false,"WeakMap":false,"WeakSet":false},"es2017":{"Array":false,"ArrayBuffer":false,"Atomics":false,"Boolean":false,"constructor":false,"DataView":false,"Date":false,"decodeURI":false,"decodeURIComponent":false,"encodeURI":false,"encodeURIComponent":false,"Error":false,"escape":false,"eval":false,"EvalError":false,"Float32Array":false,"Float64Array":false,"Function":false,"hasOwnProperty":false,"Infinity":false,"Int16Array":false,"Int32Array":false,"Int8Array":false,"isFinite":false,"isNaN":false,"isPrototypeOf":false,"JSON":false,"Map":false,"Math":false,"NaN":false,"Number":false,"Object":false,"parseFloat":false,"parseInt":false,"Promise":false,"propertyIsEnumerable":false,"Proxy":false,"RangeError":false,"ReferenceError":false,"Reflect":false,"RegExp":false,"Set":false,"SharedArrayBuffer":false,"String":false,"Symbol":false,"SyntaxError":false,"toLocaleString":false,"toString":false,"TypeError":false,"Uint16Array":false,"Uint32Array":false,"Uint8Array":false,"Uint8ClampedArray":false,"undefined":false,"unescape":false,"URIError":false,"valueOf":false,"WeakMap":false,"WeakSet":false},"browser":{"AbortController":false,"AbortSignal":false,"addEventListener":false,"alert":false,"AnalyserNode":false,"Animation":false,"AnimationEffectReadOnly":false,"AnimationEffectTiming":false,"AnimationEffectTimingReadOnly":false,"AnimationEvent":false,"AnimationPlaybackEvent":false,"AnimationTimeline":false,"applicationCache":false,"ApplicationCache":false,"ApplicationCacheErrorEvent":false,"atob":false,"Attr":false,"Audio":false,"AudioBuffer":false,"AudioBufferSourceNode":false,"AudioContext":false,"AudioDestinationNode":false,"AudioListener":false,"AudioNode":false,"AudioParam":false,"AudioProcessingEvent":false,"AudioScheduledSourceNode":false,"AudioWorkletGlobalScope ":false,"AudioWorkletNode":false,"AudioWorkletProcessor":false,"BarProp":false,"BaseAudioContext":false,"BatteryManager":false,"BeforeUnloadEvent":false,"BiquadFilterNode":false,"Blob":false,"BlobEvent":false,"blur":false,"BroadcastChannel":false,"btoa":false,"BudgetService":false,"ByteLengthQueuingStrategy":false,"Cache":false,"caches":false,"CacheStorage":false,"cancelAnimationFrame":false,"cancelIdleCallback":false,"CanvasCaptureMediaStreamTrack":false,"CanvasGradient":false,"CanvasPattern":false,"CanvasRenderingContext2D":false,"ChannelMergerNode":false,"ChannelSplitterNode":false,"CharacterData":false,"clearInterval":false,"clearTimeout":false,"clientInformation":false,"ClipboardEvent":false,"close":false,"closed":false,"CloseEvent":false,"Comment":false,"CompositionEvent":false,"confirm":false,"console":false,"ConstantSourceNode":false,"ConvolverNode":false,"CountQueuingStrategy":false,"createImageBitmap":false,"Credential":false,"CredentialsContainer":false,"crypto":false,"Crypto":false,"CryptoKey":false,"CSS":false,"CSSConditionRule":false,"CSSFontFaceRule":false,"CSSGroupingRule":false,"CSSImportRule":false,"CSSKeyframeRule":false,"CSSKeyframesRule":false,"CSSMediaRule":false,"CSSNamespaceRule":false,"CSSPageRule":false,"CSSRule":false,"CSSRuleList":false,"CSSStyleDeclaration":false,"CSSStyleRule":false,"CSSStyleSheet":false,"CSSSupportsRule":false,"CustomElementRegistry":false,"customElements":false,"CustomEvent":false,"DataTransfer":false,"DataTransferItem":false,"DataTransferItemList":false,"defaultstatus":false,"defaultStatus":false,"DelayNode":false,"DeviceMotionEvent":false,"DeviceOrientationEvent":false,"devicePixelRatio":false,"dispatchEvent":false,"document":false,"Document":false,"DocumentFragment":false,"DocumentType":false,"DOMError":false,"DOMException":false,"DOMImplementation":false,"DOMMatrix":false,"DOMMatrixReadOnly":false,"DOMParser":false,"DOMPoint":false,"DOMPointReadOnly":false,"DOMQuad":false,"DOMRect":false,"DOMRectReadOnly":false,"DOMStringList":false,"DOMStringMap":false,"DOMTokenList":false,"DragEvent":false,"DynamicsCompressorNode":false,"Element":false,"ErrorEvent":false,"event":false,"Event":false,"EventSource":false,"EventTarget":false,"external":false,"fetch":false,"File":false,"FileList":false,"FileReader":false,"find":false,"focus":false,"FocusEvent":false,"FontFace":false,"FontFaceSetLoadEvent":false,"FormData":false,"frameElement":false,"frames":false,"GainNode":false,"Gamepad":false,"GamepadButton":false,"GamepadEvent":false,"getComputedStyle":false,"getSelection":false,"HashChangeEvent":false,"Headers":false,"history":false,"History":false,"HTMLAllCollection":false,"HTMLAnchorElement":false,"HTMLAreaElement":false,"HTMLAudioElement":false,"HTMLBaseElement":false,"HTMLBodyElement":false,"HTMLBRElement":false,"HTMLButtonElement":false,"HTMLCanvasElement":false,"HTMLCollection":false,"HTMLContentElement":false,"HTMLDataElement":false,"HTMLDataListElement":false,"HTMLDetailsElement":false,"HTMLDialogElement":false,"HTMLDirectoryElement":false,"HTMLDivElement":false,"HTMLDListElement":false,"HTMLDocument":false,"HTMLElement":false,"HTMLEmbedElement":false,"HTMLFieldSetElement":false,"HTMLFontElement":false,"HTMLFormControlsCollection":false,"HTMLFormElement":false,"HTMLFrameElement":false,"HTMLFrameSetElement":false,"HTMLHeadElement":false,"HTMLHeadingElement":false,"HTMLHRElement":false,"HTMLHtmlElement":false,"HTMLIFrameElement":false,"HTMLImageElement":false,"HTMLInputElement":false,"HTMLLabelElement":false,"HTMLLegendElement":false,"HTMLLIElement":false,"HTMLLinkElement":false,"HTMLMapElement":false,"HTMLMarqueeElement":false,"HTMLMediaElement":false,"HTMLMenuElement":false,"HTMLMetaElement":false,"HTMLMeterElement":false,"HTMLModElement":false,"HTMLObjectElement":false,"HTMLOListElement":false,"HTMLOptGroupElement":false,"HTMLOptionElement":false,"HTMLOptionsCollection":false,"HTMLOutputElement":false,"HTMLParagraphElement":false,"HTMLParamElement":false,"HTMLPictureElement":false,"HTMLPreElement":false,"HTMLProgressElement":false,"HTMLQuoteElement":false,"HTMLScriptElement":false,"HTMLSelectElement":false,"HTMLShadowElement":false,"HTMLSlotElement":false,"HTMLSourceElement":false,"HTMLSpanElement":false,"HTMLStyleElement":false,"HTMLTableCaptionElement":false,"HTMLTableCellElement":false,"HTMLTableColElement":false,"HTMLTableElement":false,"HTMLTableRowElement":false,"HTMLTableSectionElement":false,"HTMLTemplateElement":false,"HTMLTextAreaElement":false,"HTMLTimeElement":false,"HTMLTitleElement":false,"HTMLTrackElement":false,"HTMLUListElement":false,"HTMLUnknownElement":false,"HTMLVideoElement":false,"IDBCursor":false,"IDBCursorWithValue":false,"IDBDatabase":false,"IDBFactory":false,"IDBIndex":false,"IDBKeyRange":false,"IDBObjectStore":false,"IDBOpenDBRequest":false,"IDBRequest":false,"IDBTransaction":false,"IDBVersionChangeEvent":false,"IdleDeadline":false,"IIRFilterNode":false,"Image":false,"ImageBitmap":false,"ImageBitmapRenderingContext":false,"ImageCapture":false,"ImageData":false,"indexedDB":false,"innerHeight":false,"innerWidth":false,"InputEvent":false,"IntersectionObserver":false,"IntersectionObserverEntry":false,"Intl":false,"isSecureContext":false,"KeyboardEvent":false,"KeyframeEffect":false,"KeyframeEffectReadOnly":false,"length":false,"localStorage":false,"location":true,"Location":false,"locationbar":false,"matchMedia":false,"MediaDeviceInfo":false,"MediaDevices":false,"MediaElementAudioSourceNode":false,"MediaEncryptedEvent":false,"MediaError":false,"MediaKeyMessageEvent":false,"MediaKeySession":false,"MediaKeyStatusMap":false,"MediaKeySystemAccess":false,"MediaList":false,"MediaQueryList":false,"MediaQueryListEvent":false,"MediaRecorder":false,"MediaSettingsRange":false,"MediaSource":false,"MediaStream":false,"MediaStreamAudioDestinationNode":false,"MediaStreamAudioSourceNode":false,"MediaStreamEvent":false,"MediaStreamTrack":false,"MediaStreamTrackEvent":false,"menubar":false,"MessageChannel":false,"MessageEvent":false,"MessagePort":false,"MIDIAccess":false,"MIDIConnectionEvent":false,"MIDIInput":false,"MIDIInputMap":false,"MIDIMessageEvent":false,"MIDIOutput":false,"MIDIOutputMap":false,"MIDIPort":false,"MimeType":false,"MimeTypeArray":false,"MouseEvent":false,"moveBy":false,"moveTo":false,"MutationEvent":false,"MutationObserver":false,"MutationRecord":false,"name":false,"NamedNodeMap":false,"NavigationPreloadManager":false,"navigator":false,"Navigator":false,"NetworkInformation":false,"Node":false,"NodeFilter":false,"NodeIterator":false,"NodeList":false,"Notification":false,"OfflineAudioCompletionEvent":false,"OfflineAudioContext":false,"offscreenBuffering":false,"OffscreenCanvas":true,"onabort":true,"onafterprint":true,"onanimationend":true,"onanimationiteration":true,"onanimationstart":true,"onappinstalled":true,"onauxclick":true,"onbeforeinstallprompt":true,"onbeforeprint":true,"onbeforeunload":true,"onblur":true,"oncancel":true,"oncanplay":true,"oncanplaythrough":true,"onchange":true,"onclick":true,"onclose":true,"oncontextmenu":true,"oncuechange":true,"ondblclick":true,"ondevicemotion":true,"ondeviceorientation":true,"ondeviceorientationabsolute":true,"ondrag":true,"ondragend":true,"ondragenter":true,"ondragleave":true,"ondragover":true,"ondragstart":true,"ondrop":true,"ondurationchange":true,"onemptied":true,"onended":true,"onerror":true,"onfocus":true,"ongotpointercapture":true,"onhashchange":true,"oninput":true,"oninvalid":true,"onkeydown":true,"onkeypress":true,"onkeyup":true,"onlanguagechange":true,"onload":true,"onloadeddata":true,"onloadedmetadata":true,"onloadstart":true,"onlostpointercapture":true,"onmessage":true,"onmessageerror":true,"onmousedown":true,"onmouseenter":true,"onmouseleave":true,"onmousemove":true,"onmouseout":true,"onmouseover":true,"onmouseup":true,"onmousewheel":true,"onoffline":true,"ononline":true,"onpagehide":true,"onpageshow":true,"onpause":true,"onplay":true,"onplaying":true,"onpointercancel":true,"onpointerdown":true,"onpointerenter":true,"onpointerleave":true,"onpointermove":true,"onpointerout":true,"onpointerover":true,"onpointerup":true,"onpopstate":true,"onprogress":true,"onratechange":true,"onrejectionhandled":true,"onreset":true,"onresize":true,"onscroll":true,"onsearch":true,"onseeked":true,"onseeking":true,"onselect":true,"onstalled":true,"onstorage":true,"onsubmit":true,"onsuspend":true,"ontimeupdate":true,"ontoggle":true,"ontransitionend":true,"onunhandledrejection":true,"onunload":true,"onvolumechange":true,"onwaiting":true,"onwheel":true,"open":false,"openDatabase":false,"opener":false,"Option":false,"origin":false,"OscillatorNode":false,"outerHeight":false,"outerWidth":false,"PageTransitionEvent":false,"pageXOffset":false,"pageYOffset":false,"PannerNode":false,"parent":false,"Path2D":false,"PaymentAddress":false,"PaymentRequest":false,"PaymentRequestUpdateEvent":false,"PaymentResponse":false,"performance":false,"Performance":false,"PerformanceEntry":false,"PerformanceLongTaskTiming":false,"PerformanceMark":false,"PerformanceMeasure":false,"PerformanceNavigation":false,"PerformanceNavigationTiming":false,"PerformanceObserver":false,"PerformanceObserverEntryList":false,"PerformancePaintTiming":false,"PerformanceResourceTiming":false,"PerformanceTiming":false,"PeriodicWave":false,"Permissions":false,"PermissionStatus":false,"personalbar":false,"PhotoCapabilities":false,"Plugin":false,"PluginArray":false,"PointerEvent":false,"PopStateEvent":false,"postMessage":false,"Presentation":false,"PresentationAvailability":false,"PresentationConnection":false,"PresentationConnectionAvailableEvent":false,"PresentationConnectionCloseEvent":false,"PresentationConnectionList":false,"PresentationReceiver":false,"PresentationRequest":false,"print":false,"ProcessingInstruction":false,"ProgressEvent":false,"PromiseRejectionEvent":false,"prompt":false,"PushManager":false,"PushSubscription":false,"PushSubscriptionOptions":false,"queueMicrotask":false,"RadioNodeList":false,"Range":false,"ReadableStream":false,"registerProcessor":false,"RemotePlayback":false,"removeEventListener":false,"Request":false,"requestAnimationFrame":false,"requestIdleCallback":false,"resizeBy":false,"ResizeObserver":false,"ResizeObserverEntry":false,"resizeTo":false,"Response":false,"RTCCertificate":false,"RTCDataChannel":false,"RTCDataChannelEvent":false,"RTCDtlsTransport":false,"RTCIceCandidate":false,"RTCIceGatherer":false,"RTCIceTransport":false,"RTCPeerConnection":false,"RTCPeerConnectionIceEvent":false,"RTCRtpContributingSource":false,"RTCRtpReceiver":false,"RTCRtpSender":false,"RTCSctpTransport":false,"RTCSessionDescription":false,"RTCStatsReport":false,"RTCTrackEvent":false,"screen":false,"Screen":false,"screenLeft":false,"ScreenOrientation":false,"screenTop":false,"screenX":false,"screenY":false,"ScriptProcessorNode":false,"scroll":false,"scrollbars":false,"scrollBy":false,"scrollTo":false,"scrollX":false,"scrollY":false,"SecurityPolicyViolationEvent":false,"Selection":false,"self":false,"ServiceWorker":false,"ServiceWorkerContainer":false,"ServiceWorkerRegistration":false,"sessionStorage":false,"setInterval":false,"setTimeout":false,"ShadowRoot":false,"SharedWorker":false,"SourceBuffer":false,"SourceBufferList":false,"speechSynthesis":false,"SpeechSynthesisEvent":false,"SpeechSynthesisUtterance":false,"StaticRange":false,"status":false,"statusbar":false,"StereoPannerNode":false,"stop":false,"Storage":false,"StorageEvent":false,"StorageManager":false,"styleMedia":false,"StyleSheet":false,"StyleSheetList":false,"SubtleCrypto":false,"SVGAElement":false,"SVGAngle":false,"SVGAnimatedAngle":false,"SVGAnimatedBoolean":false,"SVGAnimatedEnumeration":false,"SVGAnimatedInteger":false,"SVGAnimatedLength":false,"SVGAnimatedLengthList":false,"SVGAnimatedNumber":false,"SVGAnimatedNumberList":false,"SVGAnimatedPreserveAspectRatio":false,"SVGAnimatedRect":false,"SVGAnimatedString":false,"SVGAnimatedTransformList":false,"SVGAnimateElement":false,"SVGAnimateMotionElement":false,"SVGAnimateTransformElement":false,"SVGAnimationElement":false,"SVGCircleElement":false,"SVGClipPathElement":false,"SVGComponentTransferFunctionElement":false,"SVGDefsElement":false,"SVGDescElement":false,"SVGDiscardElement":false,"SVGElement":false,"SVGEllipseElement":false,"SVGFEBlendElement":false,"SVGFEColorMatrixElement":false,"SVGFEComponentTransferElement":false,"SVGFECompositeElement":false,"SVGFEConvolveMatrixElement":false,"SVGFEDiffuseLightingElement":false,"SVGFEDisplacementMapElement":false,"SVGFEDistantLightElement":false,"SVGFEDropShadowElement":false,"SVGFEFloodElement":false,"SVGFEFuncAElement":false,"SVGFEFuncBElement":false,"SVGFEFuncGElement":false,"SVGFEFuncRElement":false,"SVGFEGaussianBlurElement":false,"SVGFEImageElement":false,"SVGFEMergeElement":false,"SVGFEMergeNodeElement":false,"SVGFEMorphologyElement":false,"SVGFEOffsetElement":false,"SVGFEPointLightElement":false,"SVGFESpecularLightingElement":false,"SVGFESpotLightElement":false,"SVGFETileElement":false,"SVGFETurbulenceElement":false,"SVGFilterElement":false,"SVGForeignObjectElement":false,"SVGGElement":false,"SVGGeometryElement":false,"SVGGradientElement":false,"SVGGraphicsElement":false,"SVGImageElement":false,"SVGLength":false,"SVGLengthList":false,"SVGLinearGradientElement":false,"SVGLineElement":false,"SVGMarkerElement":false,"SVGMaskElement":false,"SVGMatrix":false,"SVGMetadataElement":false,"SVGMPathElement":false,"SVGNumber":false,"SVGNumberList":false,"SVGPathElement":false,"SVGPatternElement":false,"SVGPoint":false,"SVGPointList":false,"SVGPolygonElement":false,"SVGPolylineElement":false,"SVGPreserveAspectRatio":false,"SVGRadialGradientElement":false,"SVGRect":false,"SVGRectElement":false,"SVGScriptElement":false,"SVGSetElement":false,"SVGStopElement":false,"SVGStringList":false,"SVGStyleElement":false,"SVGSVGElement":false,"SVGSwitchElement":false,"SVGSymbolElement":false,"SVGTextContentElement":false,"SVGTextElement":false,"SVGTextPathElement":false,"SVGTextPositioningElement":false,"SVGTitleElement":false,"SVGTransform":false,"SVGTransformList":false,"SVGTSpanElement":false,"SVGUnitTypes":false,"SVGUseElement":false,"SVGViewElement":false,"TaskAttributionTiming":false,"Text":false,"TextDecoder":false,"TextEncoder":false,"TextEvent":false,"TextMetrics":false,"TextTrack":false,"TextTrackCue":false,"TextTrackCueList":false,"TextTrackList":false,"TimeRanges":false,"toolbar":false,"top":false,"Touch":false,"TouchEvent":false,"TouchList":false,"TrackEvent":false,"TransitionEvent":false,"TreeWalker":false,"UIEvent":false,"URL":false,"URLSearchParams":false,"ValidityState":false,"visualViewport":false,"VisualViewport":false,"VTTCue":false,"WaveShaperNode":false,"WebAssembly":false,"WebGL2RenderingContext":false,"WebGLActiveInfo":false,"WebGLBuffer":false,"WebGLContextEvent":false,"WebGLFramebuffer":false,"WebGLProgram":false,"WebGLQuery":false,"WebGLRenderbuffer":false,"WebGLRenderingContext":false,"WebGLSampler":false,"WebGLShader":false,"WebGLShaderPrecisionFormat":false,"WebGLSync":false,"WebGLTexture":false,"WebGLTransformFeedback":false,"WebGLUniformLocation":false,"WebGLVertexArrayObject":false,"WebSocket":false,"WheelEvent":false,"window":false,"Window":false,"Worker":false,"WritableStream":false,"XMLDocument":false,"XMLHttpRequest":false,"XMLHttpRequestEventTarget":false,"XMLHttpRequestUpload":false,"XMLSerializer":false,"XPathEvaluator":false,"XPathExpression":false,"XPathResult":false,"XSLTProcessor":false},"worker":{"addEventListener":false,"applicationCache":false,"atob":false,"Blob":false,"BroadcastChannel":false,"btoa":false,"Cache":false,"caches":false,"clearInterval":false,"clearTimeout":false,"close":true,"console":false,"fetch":false,"FileReaderSync":false,"FormData":false,"Headers":false,"IDBCursor":false,"IDBCursorWithValue":false,"IDBDatabase":false,"IDBFactory":false,"IDBIndex":false,"IDBKeyRange":false,"IDBObjectStore":false,"IDBOpenDBRequest":false,"IDBRequest":false,"IDBTransaction":false,"IDBVersionChangeEvent":false,"ImageData":false,"importScripts":true,"indexedDB":false,"location":false,"MessageChannel":false,"MessagePort":false,"name":false,"navigator":false,"Notification":false,"onclose":true,"onconnect":true,"onerror":true,"onlanguagechange":true,"onmessage":true,"onoffline":true,"ononline":true,"onrejectionhandled":true,"onunhandledrejection":true,"performance":false,"Performance":false,"PerformanceEntry":false,"PerformanceMark":false,"PerformanceMeasure":false,"PerformanceNavigation":false,"PerformanceResourceTiming":false,"PerformanceTiming":false,"postMessage":true,"Promise":false,"queueMicrotask":false,"removeEventListener":false,"Request":false,"Response":false,"self":true,"ServiceWorkerRegistration":false,"setInterval":false,"setTimeout":false,"TextDecoder":false,"TextEncoder":false,"URL":false,"URLSearchParams":false,"WebSocket":false,"Worker":false,"WorkerGlobalScope":false,"XMLHttpRequest":false},"node":{"__dirname":false,"__filename":false,"Buffer":false,"clearImmediate":false,"clearInterval":false,"clearTimeout":false,"console":false,"exports":true,"global":false,"Intl":false,"module":false,"process":false,"queueMicrotask":false,"require":false,"setImmediate":false,"setInterval":false,"setTimeout":false,"TextDecoder":false,"TextEncoder":false,"URL":false,"URLSearchParams":false},"commonjs":{"exports":true,"global":false,"module":false,"require":false},"amd":{"define":false,"require":false},"mocha":{"after":false,"afterEach":false,"before":false,"beforeEach":false,"context":false,"describe":false,"it":false,"mocha":false,"run":false,"setup":false,"specify":false,"suite":false,"suiteSetup":false,"suiteTeardown":false,"teardown":false,"test":false,"xcontext":false,"xdescribe":false,"xit":false,"xspecify":false},"jasmine":{"afterAll":false,"afterEach":false,"beforeAll":false,"beforeEach":false,"describe":false,"expect":false,"fail":false,"fdescribe":false,"fit":false,"it":false,"jasmine":false,"pending":false,"runs":false,"spyOn":false,"spyOnProperty":false,"waits":false,"waitsFor":false,"xdescribe":false,"xit":false},"jest":{"afterAll":false,"afterEach":false,"beforeAll":false,"beforeEach":false,"describe":false,"expect":false,"fdescribe":false,"fit":false,"it":false,"jest":false,"pit":false,"require":false,"test":false,"xdescribe":false,"xit":false,"xtest":false},"qunit":{"asyncTest":false,"deepEqual":false,"equal":false,"expect":false,"module":false,"notDeepEqual":false,"notEqual":false,"notOk":false,"notPropEqual":false,"notStrictEqual":false,"ok":false,"propEqual":false,"QUnit":false,"raises":false,"start":false,"stop":false,"strictEqual":false,"test":false,"throws":false},"phantomjs":{"console":true,"exports":true,"phantom":true,"require":true,"WebPage":true},"couch":{"emit":false,"exports":false,"getRow":false,"log":false,"module":false,"provides":false,"require":false,"respond":false,"send":false,"start":false,"sum":false},"rhino":{"defineClass":false,"deserialize":false,"gc":false,"help":false,"importClass":false,"importPackage":false,"java":false,"load":false,"loadClass":false,"Packages":false,"print":false,"quit":false,"readFile":false,"readUrl":false,"runCommand":false,"seal":false,"serialize":false,"spawn":false,"sync":false,"toint32":false,"version":false},"nashorn":{"__DIR__":false,"__FILE__":false,"__LINE__":false,"com":false,"edu":false,"exit":false,"java":false,"Java":false,"javafx":false,"JavaImporter":false,"javax":false,"JSAdapter":false,"load":false,"loadWithNewGlobal":false,"org":false,"Packages":false,"print":false,"quit":false},"wsh":{"ActiveXObject":true,"Enumerator":true,"GetObject":true,"ScriptEngine":true,"ScriptEngineBuildVersion":true,"ScriptEngineMajorVersion":true,"ScriptEngineMinorVersion":true,"VBArray":true,"WScript":true,"WSH":true,"XDomainRequest":true},"jquery":{"$":false,"jQuery":false},"yui":{"YAHOO":false,"YAHOO_config":false,"YUI":false,"YUI_config":false},"shelljs":{"cat":false,"cd":false,"chmod":false,"config":false,"cp":false,"dirs":false,"echo":false,"env":false,"error":false,"exec":false,"exit":false,"find":false,"grep":false,"ln":false,"ls":false,"mkdir":false,"mv":false,"popd":false,"pushd":false,"pwd":false,"rm":false,"sed":false,"set":false,"target":false,"tempdir":false,"test":false,"touch":false,"which":false},"prototypejs":{"$":false,"$$":false,"$A":false,"$break":false,"$continue":false,"$F":false,"$H":false,"$R":false,"$w":false,"Abstract":false,"Ajax":false,"Autocompleter":false,"Builder":false,"Class":false,"Control":false,"Draggable":false,"Draggables":false,"Droppables":false,"Effect":false,"Element":false,"Enumerable":false,"Event":false,"Field":false,"Form":false,"Hash":false,"Insertion":false,"ObjectRange":false,"PeriodicalExecuter":false,"Position":false,"Prototype":false,"Scriptaculous":false,"Selector":false,"Sortable":false,"SortableObserver":false,"Sound":false,"Template":false,"Toggle":false,"Try":false},"meteor":{"_":false,"$":false,"Accounts":false,"AccountsClient":false,"AccountsCommon":false,"AccountsServer":false,"App":false,"Assets":false,"Blaze":false,"check":false,"Cordova":false,"DDP":false,"DDPRateLimiter":false,"DDPServer":false,"Deps":false,"EJSON":false,"Email":false,"HTTP":false,"Log":false,"Match":false,"Meteor":false,"Mongo":false,"MongoInternals":false,"Npm":false,"Package":false,"Plugin":false,"process":false,"Random":false,"ReactiveDict":false,"ReactiveVar":false,"Router":false,"ServiceConfiguration":false,"Session":false,"share":false,"Spacebars":false,"Template":false,"Tinytest":false,"Tracker":false,"UI":false,"Utils":false,"WebApp":false,"WebAppInternals":false},"mongo":{"_isWindows":false,"_rand":false,"BulkWriteResult":false,"cat":false,"cd":false,"connect":false,"db":false,"getHostName":false,"getMemInfo":false,"hostname":false,"ISODate":false,"listFiles":false,"load":false,"ls":false,"md5sumFile":false,"mkdir":false,"Mongo":false,"NumberInt":false,"NumberLong":false,"ObjectId":false,"PlanCache":false,"print":false,"printjson":false,"pwd":false,"quit":false,"removeFile":false,"rs":false,"sh":false,"UUID":false,"version":false,"WriteResult":false},"applescript":{"$":false,"Application":false,"Automation":false,"console":false,"delay":false,"Library":false,"ObjC":false,"ObjectSpecifier":false,"Path":false,"Progress":false,"Ref":false},"serviceworker":{"addEventListener":false,"applicationCache":false,"atob":false,"Blob":false,"BroadcastChannel":false,"btoa":false,"Cache":false,"caches":false,"CacheStorage":false,"clearInterval":false,"clearTimeout":false,"Client":false,"clients":false,"Clients":false,"close":true,"console":false,"ExtendableEvent":false,"ExtendableMessageEvent":false,"fetch":false,"FetchEvent":false,"FileReaderSync":false,"FormData":false,"Headers":false,"IDBCursor":false,"IDBCursorWithValue":false,"IDBDatabase":false,"IDBFactory":false,"IDBIndex":false,"IDBKeyRange":false,"IDBObjectStore":false,"IDBOpenDBRequest":false,"IDBRequest":false,"IDBTransaction":false,"IDBVersionChangeEvent":false,"ImageData":false,"importScripts":false,"indexedDB":false,"location":false,"MessageChannel":false,"MessagePort":false,"name":false,"navigator":false,"Notification":false,"onclose":true,"onconnect":true,"onerror":true,"onfetch":true,"oninstall":true,"onlanguagechange":true,"onmessage":true,"onmessageerror":true,"onnotificationclick":true,"onnotificationclose":true,"onoffline":true,"ononline":true,"onpush":true,"onpushsubscriptionchange":true,"onrejectionhandled":true,"onsync":true,"onunhandledrejection":true,"performance":false,"Performance":false,"PerformanceEntry":false,"PerformanceMark":false,"PerformanceMeasure":false,"PerformanceNavigation":false,"PerformanceResourceTiming":false,"PerformanceTiming":false,"postMessage":true,"Promise":false,"queueMicrotask":false,"registration":false,"removeEventListener":false,"Request":false,"Response":false,"self":false,"ServiceWorker":false,"ServiceWorkerContainer":false,"ServiceWorkerGlobalScope":false,"ServiceWorkerMessageEvent":false,"ServiceWorkerRegistration":false,"setInterval":false,"setTimeout":false,"skipWaiting":false,"TextDecoder":false,"TextEncoder":false,"URL":false,"URLSearchParams":false,"WebSocket":false,"WindowClient":false,"Worker":false,"WorkerGlobalScope":false,"XMLHttpRequest":false},"atomtest":{"advanceClock":false,"fakeClearInterval":false,"fakeClearTimeout":false,"fakeSetInterval":false,"fakeSetTimeout":false,"resetTimeouts":false,"waitsForPromise":false},"embertest":{"andThen":false,"click":false,"currentPath":false,"currentRouteName":false,"currentURL":false,"fillIn":false,"find":false,"findAll":false,"findWithAssert":false,"keyEvent":false,"pauseTest":false,"resumeTest":false,"triggerEvent":false,"visit":false,"wait":false},"protractor":{"$":false,"$$":false,"browser":false,"by":false,"By":false,"DartObject":false,"element":false,"protractor":false},"shared-node-browser":{"clearInterval":false,"clearTimeout":false,"console":false,"setInterval":false,"setTimeout":false,"URL":false,"URLSearchParams":false},"webextensions":{"browser":false,"chrome":false,"opr":false},"greasemonkey":{"cloneInto":false,"createObjectIn":false,"exportFunction":false,"GM":false,"GM_addStyle":false,"GM_deleteValue":false,"GM_getResourceText":false,"GM_getResourceURL":false,"GM_getValue":false,"GM_info":false,"GM_listValues":false,"GM_log":false,"GM_openInTab":false,"GM_registerMenuCommand":false,"GM_setClipboard":false,"GM_setValue":false,"GM_xmlhttpRequest":false,"unsafeWindow":false},"devtools":{"$":false,"$_":false,"$$":false,"$0":false,"$1":false,"$2":false,"$3":false,"$4":false,"$x":false,"chrome":false,"clear":false,"copy":false,"debug":false,"dir":false,"dirxml":false,"getEventListeners":false,"inspect":false,"keys":false,"monitor":false,"monitorEvents":false,"profile":false,"profileEnd":false,"queryObjects":false,"table":false,"undebug":false,"unmonitor":false,"unmonitorEvents":false,"values":false}}')},4777:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;{const e=r;t.default=r=function(t,r){var n,s,i,a;return e(t,{moduleId:null!=(n=r.moduleId)?n:t.moduleId,moduleIds:null!=(s=r.moduleIds)?s:t.moduleIds,getModuleId:null!=(i=r.getModuleId)?i:t.getModuleId,moduleRoot:null!=(a=r.moduleRoot)?a:t.moduleRoot})}}function r(e,t){const{filename:r,filenameRelative:n=r,sourceRoot:s=t.moduleRoot}=e,{moduleId:i,moduleIds:a=!!i,getModuleId:o,moduleRoot:l=s}=t;if(!a)return null;if(null!=i&&!o)return i;let c=null!=l?l+"/":"";if(n){const e=null!=s?new RegExp("^"+s+"/?"):"";c+=n.replace(e,"").replace(/\.\w*$/,"")}return c=c.replace(/\\/g,"/"),o&&o(c)||c}},4797:(e,t,r)=>{"use strict";function n(){const e=r(4092);return n=function(){return e},e}function s(){const e=r(5781);return s=function(){return e},e}function i(){const e=r(2882);return i=function(){return e},e}function a(){const e=r(2352);return a=function(){return e},e}function o(){const e=r(5345);return o=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var l=r(1156);const{cloneNode:c,interpreterDirective:p}=a(),u={enter(e,t){const r=e.node.loc;r&&(t.loc=r,e.stop())}};class d{constructor(e,{code:t,ast:r,inputMap:n}){this._map=new Map,this.opts=void 0,this.declarations={},this.path=void 0,this.ast=void 0,this.scope=void 0,this.metadata={},this.code="",this.inputMap=void 0,this.hub={file:this,getCode:()=>this.code,getScope:()=>this.scope,addHelper:this.addHelper.bind(this),buildError:this.buildCodeFrameError.bind(this)},this.opts=e,this.code=t,this.ast=r,this.inputMap=n,this.path=s().NodePath.get({hub:this.hub,parentPath:null,parent:this.ast,container:this.ast,key:"program"}).setContext(),this.scope=this.path.scope}get shebang(){const{interpreter:e}=this.path.node;return e?e.value:""}set shebang(e){e?this.path.get("interpreter").replaceWith(p(e)):this.path.get("interpreter").remove()}set(e,t){if("helpersNamespace"===e)throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.If you are using @babel/plugin-external-helpers you will need to use a newer version than the one you currently have installed. If you have your own implementation, you'll want to explore using 'helperGenerator' alongside 'file.availableHelper()'.");this._map.set(e,t)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}availableHelper(e,t){let r;try{r=n().minVersion(e)}catch(e){if("BABEL_HELPER_UNKNOWN"!==e.code)throw e;return!1}return"string"!=typeof t||(o().valid(t)&&(t=`^${t}`),!o().intersects(`<${r}`,t)&&!o().intersects(">=8.0.0",t))}addHelper(e){const t=this.declarations[e];if(t)return c(t);const r=this.get("helperGenerator");if(r){const t=r(e);if(t)return t}n().minVersion(e);const s=this.declarations[e]=this.scope.generateUidIdentifier(e),i={};for(const t of n().getDependencies(e))i[t]=this.addHelper(t);const{nodes:a,globals:o}=n().get(e,(e=>i[e]),s.name,Object.keys(this.scope.getAllBindings()));o.forEach((e=>{this.path.scope.hasBinding(e,!0)&&this.path.scope.rename(e)})),a.forEach((e=>{e._compact=!0}));const l=this.path.unshiftContainer("body",a);for(const e of l)e.isVariableDeclaration()&&this.scope.registerDeclaration(e);return s}buildCodeFrameError(e,t,r=SyntaxError){let n=null==e?void 0:e.loc;if(!n&&e){const r={loc:null};(0,s().default)(e,u,this.scope,r),n=r.loc;let i="This is an error on an internal node. Probably an internal error.";n&&(i+=" Location has been estimated."),t+=` (${i})`}if(n){const{highlightCode:e=!0}=this.opts;t+="\n"+(0,i().codeFrameColumns)(this.code,{start:{line:n.start.line,column:n.start.column+1},end:n.end&&n.start.line===n.end.line?{line:n.end.line,column:n.end.column+1}:void 0},{highlightCode:e})}return new r(t)}}t.default=d,d.prototype.addImport=function(){throw new Error("This API has been removed. If you're looking for this functionality in Babel 7, you should import the '@babel/helper-module-imports' module and use the functions exposed from that module, such as 'addNamed' or 'addDefault'.")},d.prototype.addTemplateObject=function(){throw new Error("This function has been moved into the template literal transform itself.")},d.prototype.getModuleName=function(){return l.getModuleName()(this.opts,this.opts)}},4858:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){const{placeholderWhitelist:n,placeholderPattern:a,preserveComments:o,syntacticPlaceholders:l}=r,c=function(e,t,r){const n=(t.plugins||[]).slice();!1!==r&&n.push("placeholders"),t=Object.assign({allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,sourceType:"module"},t,{plugins:n});try{return(0,s.parse)(e,t)}catch(t){const r=t.loc;throw r&&(t.message+="\n"+(0,i.codeFrameColumns)(e,{start:r}),t.code="BABEL_TEMPLATE_PARSE_ERROR"),t}}(t,r.parser,l);m(c,{preserveComments:o}),e.validate(c);const p={syntactic:{placeholders:[],placeholderNames:new Set},legacy:{placeholders:[],placeholderNames:new Set},placeholderWhitelist:n,placeholderPattern:a,syntacticPlaceholders:l};return y(c,b,p),Object.assign({ast:c},p.syntactic.placeholders.length?p.syntactic:p.legacy)};var n=r(2352),s=r(2172),i=r(2882);const{isCallExpression:a,isExpressionStatement:o,isFunction:l,isIdentifier:c,isJSXIdentifier:p,isNewExpression:u,isPlaceholder:d,isStatement:f,isStringLiteral:h,removePropertiesDeep:m,traverse:y}=n,g=/^[_$A-Z0-9]+$/;function b(e,t,r){var n;let s,i=r.syntactic.placeholders.length>0;if(d(e)){if(!1===r.syntacticPlaceholders)throw new Error("%%foo%%-style placeholders can't be used when '.syntacticPlaceholders' is false.");s=e.name.name,i=!0}else{if(i||r.syntacticPlaceholders)return;if(c(e)||p(e))s=e.name;else{if(!h(e))return;s=e.value}}if(i&&(null!=r.placeholderPattern||null!=r.placeholderWhitelist))throw new Error("'.placeholderWhitelist' and '.placeholderPattern' aren't compatible with '.syntacticPlaceholders: true'");if(!(i||!1!==r.placeholderPattern&&(r.placeholderPattern||g).test(s)||null!=(n=r.placeholderWhitelist)&&n.has(s)))return;t=t.slice();const{node:m,key:y}=t[t.length-1];let b;h(e)||d(e,{expectedNode:"StringLiteral"})?b="string":u(m)&&"arguments"===y||a(m)&&"arguments"===y||l(m)&&"params"===y?b="param":o(m)&&!d(e)?(b="statement",t=t.slice(0,-1)):b=f(e)&&d(e)?"statement":"other";const{placeholders:v,placeholderNames:T}=i?r.syntactic:r.legacy;v.push({name:s,type:b,resolve:e=>function(e,t){let r=e;for(let e=0;e<t.length-1;e++){const{key:n,index:s}=t[e];r=void 0===s?r[n]:r[n][s]}const{key:n,index:s}=t[t.length-1];return{parent:r,key:n,index:s}}(e,t),isDuplicate:T.has(s)}),T.add(s)}},4865:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImportInjector",{enumerable:!0,get:function(){return n.default}}),t.addDefault=function(e,t,r){return new n.default(e).addDefault(t,r)},t.addNamed=function(e,t,r,s){return new n.default(e).addNamed(t,r,s)},t.addNamespace=function(e,t,r){return new n.default(e).addNamespace(t,r)},t.addSideEffect=function(e,t,r){return new n.default(e).addSideEffect(t,r)},Object.defineProperty(t,"isModule",{enumerable:!0,get:function(){return s.default}});var n=r(9757),s=r(6818)},4950:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.environmentVisitor=function(e){return y([S,e])},t.explode=f,t.isExplodedVisitor=d,t.merge=y,t.verify=h;var n=r(5562),s=r(7973),i=r(2352),a=r(9578);const{DEPRECATED_KEYS:o,DEPRECATED_ALIASES:l,FLIPPED_ALIAS_KEYS:c,TYPES:p,__internal__deprecationWarning:u}=i;function d(e){return null==e?void 0:e._exploded}function f(e){if(d(e))return e;e._exploded=!0;for(const t of Object.keys(e)){if(T(t))continue;const r=t.split("|");if(1===r.length)continue;const n=e[t];delete e[t];for(const t of r)e[t]=n}h(e),delete e.__esModule,function(e){for(const t of Object.keys(e)){if(T(t))continue;const r=e[t];"function"==typeof r&&(e[t]={enter:r})}}(e),b(e);for(const t of Object.keys(e)){if(T(t))continue;if(!(t in n))continue;const r=e[t];for(const e of Object.keys(r))r[e]=v(t,r[e]);delete e[t];const s=n[t];if(null!==s)for(const t of s)e[t]?x(e[t],r):e[t]=r;else x(e,r)}for(const t of Object.keys(e)){if(T(t))continue;let r=c[t];if(t in o){const e=o[t];u(t,e,"Visitor "),r=[e]}else if(t in l){const e=l[t];u(t,e,"Visitor "),r=c[e]}if(!r)continue;const n=e[t];delete e[t];for(const t of r){const r=e[t];r?x(r,n):e[t]=Object.assign({},n)}}for(const t of Object.keys(e))T(t)||b(e[t]);return e}function h(e){if(!e._verified){if("function"==typeof e)throw new Error("You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?");for(const t of Object.keys(e)){if("enter"!==t&&"exit"!==t||m(t,e[t]),T(t))continue;if(!p.includes(t))throw new Error(`You gave us a visitor for the node type ${t} but it's not a valid type in @babel/traverse 7.26.9`);const r=e[t];if("object"==typeof r)for(const e of Object.keys(r)){if("enter"!==e&&"exit"!==e)throw new Error(`You passed \`traverse()\` a visitor object with the property ${t} that has the invalid property ${e}`);m(`${t}.${e}`,r[e])}}e._verified=!0}}function m(e,t){const r=[].concat(t);for(const t of r)if("function"!=typeof t)throw new TypeError(`Non-function found defined in ${e} with type ${typeof t}`)}function y(e,t=[],r){const n={_verified:!0,_exploded:!0};Object.defineProperty(n,"_exploded",{enumerable:!1}),Object.defineProperty(n,"_verified",{enumerable:!1});for(let s=0;s<e.length;s++){const i=f(e[s]),a=t[s];let o=i;(a||r)&&(o=g(o,a,r)),x(n,o);for(const e of Object.keys(i)){if(T(e))continue;let t=i[e];(a||r)&&(t=g(t,a,r)),x(n[e]||(n[e]={}),t)}}return n}function g(e,t,r){const n={};for(const s of["enter","exit"]){let i=e[s];Array.isArray(i)&&(i=i.map((function(e){let n=e;return t&&(n=function(r){e.call(t,r,t)}),r&&(n=r(null==t?void 0:t.key,s,n)),n!==e&&(n.toString=()=>e.toString()),n})),n[s]=i)}return n}function b(e){e.enter&&!Array.isArray(e.enter)&&(e.enter=[e.enter]),e.exit&&!Array.isArray(e.exit)&&(e.exit=[e.exit])}function v(e,t){const r=s[`is${e}`],n=function(e){if(r.call(e))return t.apply(this,arguments)};return n.toString=()=>t.toString(),n}function T(e){return"_"===e[0]||"enter"===e||"exit"===e||"shouldSkip"===e||"denylist"===e||"noScope"===e||"skipKeys"===e||"blacklist"===e}function x(e,t){for(const r of["enter","exit"])t[r]&&(e[r]=[].concat(e[r]||[],t[r]))}const S={FunctionParent(e){e.isArrowFunctionExpression()||(e.skip(),e.isMethod()&&(e.requeueComputedKeyAndDecorators?e.requeueComputedKeyAndDecorators():a.requeueComputedKeyAndDecorators.call(e)))},Property(e){e.isObjectProperty()||(e.skip(),e.requeueComputedKeyAndDecorators?e.requeueComputedKeyAndDecorators():a.requeueComputedKeyAndDecorators.call(e))}}},4960:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=class{constructor(e,t){this._map=null,this._buf="",this._str="",this._appendCount=0,this._last=0,this._queue=[],this._queueCursor=0,this._canMarkIdName=!0,this._indentChar="",this._fastIndentations=[],this._position={line:1,column:0},this._sourcePosition={identifierName:void 0,identifierNamePos:void 0,line:void 0,column:void 0,filename:void 0},this._map=e,this._indentChar=t;for(let e=0;e<64;e++)this._fastIndentations.push(t.repeat(e));this._allocQueue()}_allocQueue(){const e=this._queue;for(let t=0;t<16;t++)e.push({char:0,repeat:1,line:void 0,column:void 0,identifierName:void 0,identifierNamePos:void 0,filename:""})}_pushQueue(e,t,r,n,s){const i=this._queueCursor;i===this._queue.length&&this._allocQueue();const a=this._queue[i];a.char=e,a.repeat=t,a.line=r,a.column=n,a.filename=s,this._queueCursor++}_popQueue(){if(0===this._queueCursor)throw new Error("Cannot pop from empty queue");return this._queue[--this._queueCursor]}get(){this._flush();const e=this._map,t={code:(this._buf+this._str).trimRight(),decodedMap:null==e?void 0:e.getDecoded(),get __mergedMap(){return this.map},get map(){const r=e?e.get():null;return t.map=r,r},set map(e){Object.defineProperty(t,"map",{value:e,writable:!0})},get rawMappings(){const r=null==e?void 0:e.getRawMappings();return t.rawMappings=r,r},set rawMappings(e){Object.defineProperty(t,"rawMappings",{value:e,writable:!0})}};return t}append(e,t){this._flush(),this._append(e,this._sourcePosition,t)}appendChar(e){this._flush(),this._appendChar(e,1,this._sourcePosition)}queue(e){if(10===e)for(;0!==this._queueCursor;){const e=this._queue[this._queueCursor-1].char;if(32!==e&&9!==e)break;this._queueCursor--}const t=this._sourcePosition;this._pushQueue(e,1,t.line,t.column,t.filename)}queueIndentation(e){0!==e&&this._pushQueue(-1,e,void 0,void 0,void 0)}_flush(){const e=this._queueCursor,t=this._queue;for(let r=0;r<e;r++){const e=t[r];this._appendChar(e.char,e.repeat,e)}this._queueCursor=0}_appendChar(e,t,r){if(this._last=e,-1===e){const e=this._fastIndentations[t];this._str+=void 0!==e?e:t>1?this._indentChar.repeat(t):this._indentChar}else this._str+=t>1?String.fromCharCode(e).repeat(t):String.fromCharCode(e);10!==e?(this._mark(r.line,r.column,r.identifierName,r.identifierNamePos,r.filename),this._position.column+=t):(this._position.line++,this._position.column=0),this._canMarkIdName&&(r.identifierName=void 0,r.identifierNamePos=void 0)}_append(e,t,r){const n=e.length,s=this._position;if(this._last=e.charCodeAt(n-1),++this._appendCount>4096?(this._str,this._buf+=this._str,this._str=e,this._appendCount=0):this._str+=e,!r&&!this._map)return void(s.column+=n);const{column:i,identifierName:a,identifierNamePos:o,filename:l}=t;let c=t.line;null==a&&null==o||!this._canMarkIdName||(t.identifierName=void 0,t.identifierNamePos=void 0);let p=e.indexOf("\n"),u=0;for(0!==p&&this._mark(c,i,a,o,l);-1!==p;)s.line++,s.column=0,u=p+1,u<n&&void 0!==c&&this._mark(++c,0,null,null,l),p=e.indexOf("\n",u);s.column+=n-u}_mark(e,t,r,n,s){var i;null==(i=this._map)||i.mark(this._position,e,t,r,n,s)}removeTrailingNewline(){const e=this._queueCursor;0!==e&&10===this._queue[e-1].char&&this._queueCursor--}removeLastSemicolon(){const e=this._queueCursor;0!==e&&59===this._queue[e-1].char&&this._queueCursor--}getLastChar(){const e=this._queueCursor;return 0!==e?this._queue[e-1].char:this._last}getNewlineCount(){const e=this._queueCursor;let t=0;if(0===e)return 10===this._last?1:0;for(let r=e-1;r>=0&&10===this._queue[r].char;r--)t++;return t===e&&10===this._last?t+1:t}endsWithCharAndNewline(){const e=this._queue,t=this._queueCursor;if(0!==t){if(10!==e[t-1].char)return;return t>1?e[t-2].char:this._last}}hasContent(){return 0!==this._queueCursor||!!this._last}exactSource(e,t){if(!this._map)return void t();this.source("start",e);const r=e.identifierName,n=this._sourcePosition;r&&(this._canMarkIdName=!1,n.identifierName=r),t(),r&&(this._canMarkIdName=!0,n.identifierName=void 0,n.identifierNamePos=void 0),this.source("end",e)}source(e,t){this._map&&this._normalizePosition(e,t,0)}sourceWithOffset(e,t,r){this._map&&this._normalizePosition(e,t,r)}_normalizePosition(e,t,r){const n=t[e],s=this._sourcePosition;n&&(s.line=n.line,s.column=Math.max(n.column+r,0),s.filename=t.filename)}getCurrentColumn(){const e=this._queue,t=this._queueCursor;let r=-1,n=0;for(let s=0;s<t;s++){const t=e[s];10===t.char&&(r=n),n+=t.repeat}return-1===r?this._position.column+n:n-1-r}getCurrentLine(){let e=0;const t=this._queue;for(let r=0;r<this._queueCursor;r++)10===t[r].char&&e++;return this._position.line+e}}},4965:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){if(!(0,n.isMemberExpression)(e))return!1;const s=Array.isArray(t)?t:t.split("."),i=[];let a;for(a=e;(0,n.isMemberExpression)(a);a=a.object)i.push(a.property);if(i.push(a),i.length<s.length)return!1;if(!r&&i.length>s.length)return!1;for(let e=0,t=i.length-1;e<s.length;e++,t--){const r=i[t];let a;if((0,n.isIdentifier)(r))a=r.name;else if((0,n.isStringLiteral)(r))a=r.value;else{if(!(0,n.isThisExpression)(r))return!1;a="this"}if(s[e]!==a)return!1}return!0};var n=r(8960)},5004:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return!!e&&/^[a-z]/.test(e)}},5010:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if((0,n.isBlockStatement)(e))return e;let r=[];return(0,n.isEmptyStatement)(e)?r=[]:((0,n.isStatement)(e)||(e=(0,n.isFunction)(t)?(0,s.returnStatement)(e):(0,s.expressionStatement)(e)),r=[e]),(0,s.blockStatement)(r)};var n=r(8960),s=r(8079)},5040:(e,t,r)=>{e.exports.browserVersions=r(6438)},5104:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=void 0,t.transformAsync=function(...e){return(0,a.beginHiddenCallStack)(o.async)(...e)},t.transformSync=function(...e){return(0,a.beginHiddenCallStack)(o.sync)(...e)};var s=r(6955),i=r(6568),a=r(1339);const o=n()((function*(e,t){const r=yield*(0,s.default)(t);return null===r?null:yield*(0,i.run)(r,e)}));t.transform=function(e,t,r){let n,s;if("function"==typeof t?(s=t,n=void 0):(n=t,s=r),void 0===s)return(0,a.beginHiddenCallStack)(o.sync)(e,n);(0,a.beginHiddenCallStack)(o.errback)(e,n,s)}},5109:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if("id"in e&&e.id)return{name:e.id.name,originalNode:e.id};let r,i="";if((0,n.isObjectProperty)(t,{value:e})?r=s(t):(0,n.isObjectMethod)(e)||(0,n.isClassMethod)(e)?(r=s(e),"get"===e.kind?i="get ":"set"===e.kind&&(i="set ")):(0,n.isVariableDeclarator)(t,{init:e})?r=t.id:(0,n.isAssignmentExpression)(t,{operator:"=",right:e})&&(r=t.left),!r)return null;const a=(0,n.isLiteral)(r)?function(e){return(0,n.isNullLiteral)(e)?"null":(0,n.isRegExpLiteral)(e)?`/${e.pattern}/${e.flags}`:(0,n.isTemplateLiteral)(e)?e.quasis.map((e=>e.value.raw)).join(""):void 0!==e.value?String(e.value):null}(r):(0,n.isIdentifier)(r)?r.name:(0,n.isPrivateName)(r)?r.id.name:null;return null==a?null:{name:i+a,originalNode:r}};var n=r(8960);function s(e){if(!e.computed||(0,n.isLiteral)(e.key))return e.key}},5158:(e,t,r)=>{"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0}),t.patternLikeCommon=t.importAttributes=t.functionTypeAnnotationCommon=t.functionDeclarationCommon=t.functionCommon=t.classMethodOrPropertyCommon=t.classMethodOrDeclareMethodCommon=void 0;var s=r(3828),i=r(983),a=r(1e3),o=r(3973),l=r(3422),c=r(7596);const p=(0,c.defineAliasedType)("Standardized");p("ArrayExpression",{fields:{elements:{validate:(0,c.arrayOf)((0,c.assertNodeOrValueType)("null","Expression","SpreadElement")),default:n.env.BABEL_TYPES_8_BREAKING?void 0:[]}},visitor:["elements"],aliases:["Expression"]}),p("AssignmentExpression",{fields:{operator:{validate:n.env.BABEL_TYPES_8_BREAKING?Object.assign(function(){const e=(0,c.assertOneOf)(...l.ASSIGNMENT_OPERATORS),t=(0,c.assertOneOf)("=");return function(r,n,i){((0,s.default)("Pattern",r.left)?t:e)(r,n,i)}}(),{type:"string"}):(0,c.assertValueType)("string")},left:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.assertNodeType)("Identifier","MemberExpression","OptionalMemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"):(0,c.assertNodeType)("LVal","OptionalMemberExpression")},right:{validate:(0,c.assertNodeType)("Expression")}},builder:["operator","left","right"],visitor:["left","right"],aliases:["Expression"]}),p("BinaryExpression",{builder:["operator","left","right"],fields:{operator:{validate:(0,c.assertOneOf)(...l.BINARY_OPERATORS)},left:{validate:function(){const e=(0,c.assertNodeType)("Expression"),t=(0,c.assertNodeType)("Expression","PrivateName");return Object.assign((function(r,n,s){("in"===r.operator?t:e)(r,n,s)}),{oneOfNodeTypes:["Expression","PrivateName"]})}()},right:{validate:(0,c.assertNodeType)("Expression")}},visitor:["left","right"],aliases:["Binary","Expression"]}),p("InterpreterDirective",{builder:["value"],fields:{value:{validate:(0,c.assertValueType)("string")}}}),p("Directive",{visitor:["value"],fields:{value:{validate:(0,c.assertNodeType)("DirectiveLiteral")}}}),p("DirectiveLiteral",{builder:["value"],fields:{value:{validate:(0,c.assertValueType)("string")}}}),p("BlockStatement",{builder:["body","directives"],visitor:["directives","body"],fields:{directives:{validate:(0,c.arrayOfType)("Directive"),default:[]},body:(0,c.validateArrayOfType)("Statement")},aliases:["Scopable","BlockParent","Block","Statement"]}),p("BreakStatement",{visitor:["label"],fields:{label:{validate:(0,c.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),p("CallExpression",{visitor:["callee","arguments","typeParameters","typeArguments"],builder:["callee","arguments"],aliases:["Expression"],fields:Object.assign({callee:{validate:(0,c.assertNodeType)("Expression","Super","V8IntrinsicIdentifier")},arguments:(0,c.validateArrayOfType)("Expression","SpreadElement","ArgumentPlaceholder"),typeArguments:{validate:(0,c.assertNodeType)("TypeParameterInstantiation"),optional:!0}},{optional:{validate:(0,c.assertValueType)("boolean"),optional:!0},typeParameters:{validate:(0,c.assertNodeType)("TSTypeParameterInstantiation"),optional:!0}},n.env.BABEL_TYPES_8_BREAKING?{}:{optional:{validate:(0,c.assertValueType)("boolean"),optional:!0}})}),p("CatchClause",{visitor:["param","body"],fields:{param:{validate:(0,c.assertNodeType)("Identifier","ArrayPattern","ObjectPattern"),optional:!0},body:{validate:(0,c.assertNodeType)("BlockStatement")}},aliases:["Scopable","BlockParent"]}),p("ConditionalExpression",{visitor:["test","consequent","alternate"],fields:{test:{validate:(0,c.assertNodeType)("Expression")},consequent:{validate:(0,c.assertNodeType)("Expression")},alternate:{validate:(0,c.assertNodeType)("Expression")}},aliases:["Expression","Conditional"]}),p("ContinueStatement",{visitor:["label"],fields:{label:{validate:(0,c.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),p("DebuggerStatement",{aliases:["Statement"]}),p("DoWhileStatement",{builder:["test","body"],visitor:["body","test"],fields:{test:{validate:(0,c.assertNodeType)("Expression")},body:{validate:(0,c.assertNodeType)("Statement")}},aliases:["Statement","BlockParent","Loop","While","Scopable"]}),p("EmptyStatement",{aliases:["Statement"]}),p("ExpressionStatement",{visitor:["expression"],fields:{expression:{validate:(0,c.assertNodeType)("Expression")}},aliases:["Statement","ExpressionWrapper"]}),p("File",{builder:["program","comments","tokens"],visitor:["program"],fields:{program:{validate:(0,c.assertNodeType)("Program")},comments:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.assertEach)((0,c.assertNodeType)("CommentBlock","CommentLine")):Object.assign((()=>{}),{each:{oneOfNodeTypes:["CommentBlock","CommentLine"]}}),optional:!0},tokens:{validate:(0,c.assertEach)(Object.assign((()=>{}),{type:"any"})),optional:!0}}}),p("ForInStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.assertNodeType)("VariableDeclaration","Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"):(0,c.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,c.assertNodeType)("Expression")},body:{validate:(0,c.assertNodeType)("Statement")}}}),p("ForStatement",{visitor:["init","test","update","body"],aliases:["Scopable","Statement","For","BlockParent","Loop"],fields:{init:{validate:(0,c.assertNodeType)("VariableDeclaration","Expression"),optional:!0},test:{validate:(0,c.assertNodeType)("Expression"),optional:!0},update:{validate:(0,c.assertNodeType)("Expression"),optional:!0},body:{validate:(0,c.assertNodeType)("Statement")}}});const u=()=>({params:(0,c.validateArrayOfType)("Identifier","Pattern","RestElement"),generator:{default:!1},async:{default:!1}});t.functionCommon=u;const d=()=>({returnType:{validate:(0,c.assertNodeType)("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},typeParameters:{validate:(0,c.assertNodeType)("TypeParameterDeclaration","TSTypeParameterDeclaration","Noop"),optional:!0}});t.functionTypeAnnotationCommon=d;const f=()=>Object.assign({},u(),{declare:{validate:(0,c.assertValueType)("boolean"),optional:!0},id:{validate:(0,c.assertNodeType)("Identifier"),optional:!0}});t.functionDeclarationCommon=f,p("FunctionDeclaration",{builder:["id","params","body","generator","async"],visitor:["id","typeParameters","params","predicate","returnType","body"],fields:Object.assign({},f(),d(),{body:{validate:(0,c.assertNodeType)("BlockStatement")},predicate:{validate:(0,c.assertNodeType)("DeclaredPredicate","InferredPredicate"),optional:!0}}),aliases:["Scopable","Function","BlockParent","FunctionParent","Statement","Pureish","Declaration"],validate:n.env.BABEL_TYPES_8_BREAKING?function(){const e=(0,c.assertNodeType)("Identifier");return function(t,r,n){(0,s.default)("ExportDefaultDeclaration",t)||e(n,"id",n.id)}}():void 0}),p("FunctionExpression",{inherits:"FunctionDeclaration",aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:Object.assign({},u(),d(),{id:{validate:(0,c.assertNodeType)("Identifier"),optional:!0},body:{validate:(0,c.assertNodeType)("BlockStatement")},predicate:{validate:(0,c.assertNodeType)("DeclaredPredicate","InferredPredicate"),optional:!0}})});const h=()=>({typeAnnotation:{validate:(0,c.assertNodeType)("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},optional:{validate:(0,c.assertValueType)("boolean"),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0}});t.patternLikeCommon=h,p("Identifier",{builder:["name"],visitor:["typeAnnotation","decorators"],aliases:["Expression","PatternLike","LVal","TSEntityName"],fields:Object.assign({},h(),{name:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertValueType)("string"),Object.assign((function(e,t,r){if(!(0,i.default)(r,!1))throw new TypeError(`"${r}" is not a valid identifier name`)}),{type:"string"})):(0,c.assertValueType)("string")}}),validate:n.env.BABEL_TYPES_8_BREAKING?function(e,t,r){const n=/\.(\w+)$/.exec(t);if(!n)return;const[,i]=n,o={computed:!1};if("property"===i){if((0,s.default)("MemberExpression",e,o))return;if((0,s.default)("OptionalMemberExpression",e,o))return}else if("key"===i){if((0,s.default)("Property",e,o))return;if((0,s.default)("Method",e,o))return}else if("exported"===i){if((0,s.default)("ExportSpecifier",e))return}else if("imported"===i){if((0,s.default)("ImportSpecifier",e,{imported:r}))return}else if("meta"===i&&(0,s.default)("MetaProperty",e,{meta:r}))return;if(((0,a.isKeyword)(r.name)||(0,a.isReservedWord)(r.name,!1))&&"this"!==r.name)throw new TypeError(`"${r.name}" is not a valid identifier`)}:void 0}),p("IfStatement",{visitor:["test","consequent","alternate"],aliases:["Statement","Conditional"],fields:{test:{validate:(0,c.assertNodeType)("Expression")},consequent:{validate:(0,c.assertNodeType)("Statement")},alternate:{optional:!0,validate:(0,c.assertNodeType)("Statement")}}}),p("LabeledStatement",{visitor:["label","body"],aliases:["Statement"],fields:{label:{validate:(0,c.assertNodeType)("Identifier")},body:{validate:(0,c.assertNodeType)("Statement")}}}),p("StringLiteral",{builder:["value"],fields:{value:{validate:(0,c.assertValueType)("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),p("NumericLiteral",{builder:["value"],deprecatedAlias:"NumberLiteral",fields:{value:{validate:(0,c.chain)((0,c.assertValueType)("number"),Object.assign((function(e,t,r){(1/r<0||!Number.isFinite(r))&&new Error(`NumericLiterals must be non-negative finite numbers. You can use t.valueToNode(${r}) instead.`)}),{type:"number"}))}},aliases:["Expression","Pureish","Literal","Immutable"]}),p("NullLiteral",{aliases:["Expression","Pureish","Literal","Immutable"]}),p("BooleanLiteral",{builder:["value"],fields:{value:{validate:(0,c.assertValueType)("boolean")}},aliases:["Expression","Pureish","Literal","Immutable"]}),p("RegExpLiteral",{builder:["pattern","flags"],deprecatedAlias:"RegexLiteral",aliases:["Expression","Pureish","Literal"],fields:{pattern:{validate:(0,c.assertValueType)("string")},flags:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertValueType)("string"),Object.assign((function(e,t,r){const n=/[^gimsuy]/.exec(r);if(n)throw new TypeError(`"${n[0]}" is not a valid RegExp flag`)}),{type:"string"})):(0,c.assertValueType)("string"),default:""}}}),p("LogicalExpression",{builder:["operator","left","right"],visitor:["left","right"],aliases:["Binary","Expression"],fields:{operator:{validate:(0,c.assertOneOf)(...l.LOGICAL_OPERATORS)},left:{validate:(0,c.assertNodeType)("Expression")},right:{validate:(0,c.assertNodeType)("Expression")}}}),p("MemberExpression",{builder:["object","property","computed",...n.env.BABEL_TYPES_8_BREAKING?[]:["optional"]],visitor:["object","property"],aliases:["Expression","LVal"],fields:Object.assign({object:{validate:(0,c.assertNodeType)("Expression","Super")},property:{validate:function(){const e=(0,c.assertNodeType)("Identifier","PrivateName"),t=(0,c.assertNodeType)("Expression"),r=function(r,n,s){(r.computed?t:e)(r,n,s)};return r.oneOfNodeTypes=["Expression","Identifier","PrivateName"],r}()},computed:{default:!1}},n.env.BABEL_TYPES_8_BREAKING?{}:{optional:{validate:(0,c.assertValueType)("boolean"),optional:!0}})}),p("NewExpression",{inherits:"CallExpression"}),p("Program",{visitor:["directives","body"],builder:["body","directives","sourceType","interpreter"],fields:{sourceType:{validate:(0,c.assertOneOf)("script","module"),default:"script"},interpreter:{validate:(0,c.assertNodeType)("InterpreterDirective"),default:null,optional:!0},directives:{validate:(0,c.arrayOfType)("Directive"),default:[]},body:(0,c.validateArrayOfType)("Statement")},aliases:["Scopable","BlockParent","Block"]}),p("ObjectExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:(0,c.validateArrayOfType)("ObjectMethod","ObjectProperty","SpreadElement")}}),p("ObjectMethod",{builder:["kind","key","params","body","computed","generator","async"],visitor:["decorators","key","typeParameters","params","returnType","body"],fields:Object.assign({},u(),d(),{kind:Object.assign({validate:(0,c.assertOneOf)("method","get","set")},n.env.BABEL_TYPES_8_BREAKING?{}:{default:"method"}),computed:{default:!1},key:{validate:function(){const e=(0,c.assertNodeType)("Identifier","StringLiteral","NumericLiteral","BigIntLiteral"),t=(0,c.assertNodeType)("Expression"),r=function(r,n,s){(r.computed?t:e)(r,n,s)};return r.oneOfNodeTypes=["Expression","Identifier","StringLiteral","NumericLiteral","BigIntLiteral"],r}()},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0},body:{validate:(0,c.assertNodeType)("BlockStatement")}}),aliases:["UserWhitespacable","Function","Scopable","BlockParent","FunctionParent","Method","ObjectMember"]}),p("ObjectProperty",{builder:["key","value","computed","shorthand",...n.env.BABEL_TYPES_8_BREAKING?[]:["decorators"]],fields:{computed:{default:!1},key:{validate:function(){const e=(0,c.assertNodeType)("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","DecimalLiteral","PrivateName"),t=(0,c.assertNodeType)("Expression");return Object.assign((function(r,n,s){(r.computed?t:e)(r,n,s)}),{oneOfNodeTypes:["Expression","Identifier","StringLiteral","NumericLiteral","BigIntLiteral","DecimalLiteral","PrivateName"]})}()},value:{validate:(0,c.assertNodeType)("Expression","PatternLike")},shorthand:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertValueType)("boolean"),Object.assign((function(e,t,r){if(r){if(e.computed)throw new TypeError("Property shorthand of ObjectProperty cannot be true if computed is true");if(!(0,s.default)("Identifier",e.key))throw new TypeError("Property shorthand of ObjectProperty cannot be true if key is not an Identifier")}}),{type:"boolean"})):(0,c.assertValueType)("boolean"),default:!1},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0}},visitor:["key","value","decorators"],aliases:["UserWhitespacable","Property","ObjectMember"],validate:n.env.BABEL_TYPES_8_BREAKING?function(){const e=(0,c.assertNodeType)("Identifier","Pattern","TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","TSTypeAssertion"),t=(0,c.assertNodeType)("Expression");return function(r,n,i){((0,s.default)("ObjectPattern",r)?e:t)(i,"value",i.value)}}():void 0}),p("RestElement",{visitor:["argument","typeAnnotation"],builder:["argument"],aliases:["LVal","PatternLike"],deprecatedAlias:"RestProperty",fields:Object.assign({},h(),{argument:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.assertNodeType)("Identifier","ArrayPattern","ObjectPattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"):(0,c.assertNodeType)("LVal")}}),validate:n.env.BABEL_TYPES_8_BREAKING?function(e,t){const r=/(\w+)\[(\d+)\]/.exec(t);if(!r)throw new Error("Internal Babel error: malformed key.");const[,n,s]=r;if(e[n].length>+s+1)throw new TypeError(`RestElement must be last element of ${n}`)}:void 0}),p("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,c.assertNodeType)("Expression"),optional:!0}}}),p("SequenceExpression",{visitor:["expressions"],fields:{expressions:(0,c.validateArrayOfType)("Expression")},aliases:["Expression"]}),p("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:(0,c.assertNodeType)("Expression")}}}),p("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:(0,c.assertNodeType)("Expression"),optional:!0},consequent:(0,c.validateArrayOfType)("Statement")}}),p("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:(0,c.assertNodeType)("Expression")},cases:(0,c.validateArrayOfType)("SwitchCase")}}),p("ThisExpression",{aliases:["Expression"]}),p("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,c.assertNodeType)("Expression")}}}),p("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{block:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertNodeType)("BlockStatement"),Object.assign((function(e){if(!e.handler&&!e.finalizer)throw new TypeError("TryStatement expects either a handler or finalizer, or both")}),{oneOfNodeTypes:["BlockStatement"]})):(0,c.assertNodeType)("BlockStatement")},handler:{optional:!0,validate:(0,c.assertNodeType)("CatchClause")},finalizer:{optional:!0,validate:(0,c.assertNodeType)("BlockStatement")}}}),p("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!0},argument:{validate:(0,c.assertNodeType)("Expression")},operator:{validate:(0,c.assertOneOf)(...l.UNARY_OPERATORS)}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),p("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!1},argument:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.assertNodeType)("Identifier","MemberExpression"):(0,c.assertNodeType)("Expression")},operator:{validate:(0,c.assertOneOf)(...l.UPDATE_OPERATORS)}},visitor:["argument"],aliases:["Expression"]}),p("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{declare:{validate:(0,c.assertValueType)("boolean"),optional:!0},kind:{validate:(0,c.assertOneOf)("var","let","const","using","await using")},declarations:(0,c.validateArrayOfType)("VariableDeclarator")},validate:n.env.BABEL_TYPES_8_BREAKING?(()=>{const e=(0,c.assertNodeType)("Identifier");return function(t,r,n){if((0,s.default)("ForXStatement",t,{left:n})){if(1!==n.declarations.length)throw new TypeError(`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${t.type}`)}else n.declarations.forEach((t=>{t.init||e(t,"id",t.id)}))}})():void 0}),p("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.assertNodeType)("Identifier","ArrayPattern","ObjectPattern"):(0,c.assertNodeType)("LVal")},definite:{optional:!0,validate:(0,c.assertValueType)("boolean")},init:{optional:!0,validate:(0,c.assertNodeType)("Expression")}}}),p("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:(0,c.assertNodeType)("Expression")},body:{validate:(0,c.assertNodeType)("Statement")}}}),p("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{validate:(0,c.assertNodeType)("Expression")},body:{validate:(0,c.assertNodeType)("Statement")}}}),p("AssignmentPattern",{visitor:["left","right","decorators"],builder:["left","right"],aliases:["Pattern","PatternLike","LVal"],fields:Object.assign({},h(),{left:{validate:(0,c.assertNodeType)("Identifier","ObjectPattern","ArrayPattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")},right:{validate:(0,c.assertNodeType)("Expression")},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0}})}),p("ArrayPattern",{visitor:["elements","typeAnnotation"],builder:["elements"],aliases:["Pattern","PatternLike","LVal"],fields:Object.assign({},h(),{elements:{validate:(0,c.chain)((0,c.assertValueType)("array"),(0,c.assertEach)((0,c.assertNodeOrValueType)("null","PatternLike","LVal")))}})}),p("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["typeParameters","params","predicate","returnType","body"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:Object.assign({},u(),d(),{expression:{validate:(0,c.assertValueType)("boolean")},body:{validate:(0,c.assertNodeType)("BlockStatement","Expression")},predicate:{validate:(0,c.assertNodeType)("DeclaredPredicate","InferredPredicate"),optional:!0}})}),p("ClassBody",{visitor:["body"],fields:{body:(0,c.validateArrayOfType)("ClassMethod","ClassPrivateMethod","ClassProperty","ClassPrivateProperty","ClassAccessorProperty","TSDeclareMethod","TSIndexSignature","StaticBlock")}}),p("ClassExpression",{builder:["id","superClass","body","decorators"],visitor:["decorators","id","typeParameters","superClass","superTypeParameters","mixins","implements","body"],aliases:["Scopable","Class","Expression"],fields:{id:{validate:(0,c.assertNodeType)("Identifier"),optional:!0},typeParameters:{validate:(0,c.assertNodeType)("TypeParameterDeclaration","TSTypeParameterDeclaration","Noop"),optional:!0},body:{validate:(0,c.assertNodeType)("ClassBody")},superClass:{optional:!0,validate:(0,c.assertNodeType)("Expression")},superTypeParameters:{validate:(0,c.assertNodeType)("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},implements:{validate:(0,c.arrayOfType)("TSExpressionWithTypeArguments","ClassImplements"),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0},mixins:{validate:(0,c.assertNodeType)("InterfaceExtends"),optional:!0}}}),p("ClassDeclaration",{inherits:"ClassExpression",aliases:["Scopable","Class","Statement","Declaration"],fields:{id:{validate:(0,c.assertNodeType)("Identifier"),optional:!0},typeParameters:{validate:(0,c.assertNodeType)("TypeParameterDeclaration","TSTypeParameterDeclaration","Noop"),optional:!0},body:{validate:(0,c.assertNodeType)("ClassBody")},superClass:{optional:!0,validate:(0,c.assertNodeType)("Expression")},superTypeParameters:{validate:(0,c.assertNodeType)("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},implements:{validate:(0,c.arrayOfType)("TSExpressionWithTypeArguments","ClassImplements"),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0},mixins:{validate:(0,c.assertNodeType)("InterfaceExtends"),optional:!0},declare:{validate:(0,c.assertValueType)("boolean"),optional:!0},abstract:{validate:(0,c.assertValueType)("boolean"),optional:!0}},validate:n.env.BABEL_TYPES_8_BREAKING?function(){const e=(0,c.assertNodeType)("Identifier");return function(t,r,n){(0,s.default)("ExportDefaultDeclaration",t)||e(n,"id",n.id)}}():void 0});const m=t.importAttributes={attributes:{optional:!0,validate:(0,c.arrayOfType)("ImportAttribute")},assertions:{deprecated:!0,optional:!0,validate:(0,c.arrayOfType)("ImportAttribute")}};p("ExportAllDeclaration",{builder:["source"],visitor:["source","attributes","assertions"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:Object.assign({source:{validate:(0,c.assertNodeType)("StringLiteral")},exportKind:(0,c.validateOptional)((0,c.assertOneOf)("type","value"))},m)}),p("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:{declaration:(0,c.validateType)("TSDeclareFunction","FunctionDeclaration","ClassDeclaration","Expression"),exportKind:(0,c.validateOptional)((0,c.assertOneOf)("value"))}}),p("ExportNamedDeclaration",{builder:["declaration","specifiers","source"],visitor:n.env?["declaration","specifiers","source","attributes"]:["declaration","specifiers","source","attributes","assertions"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:Object.assign({declaration:{optional:!0,validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertNodeType)("Declaration"),Object.assign((function(e,t,r){if(r&&e.specifiers.length)throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration");if(r&&e.source)throw new TypeError("Cannot export a declaration from a source")}),{oneOfNodeTypes:["Declaration"]})):(0,c.assertNodeType)("Declaration")}},m,{specifiers:{default:[],validate:(0,c.arrayOf)(function(){const e=(0,c.assertNodeType)("ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"),t=(0,c.assertNodeType)("ExportSpecifier");return n.env.BABEL_TYPES_8_BREAKING?Object.assign((function(r,n,s){(r.source?e:t)(r,n,s)}),{oneOfNodeTypes:["ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"]}):e}())},source:{validate:(0,c.assertNodeType)("StringLiteral"),optional:!0},exportKind:(0,c.validateOptional)((0,c.assertOneOf)("type","value"))})}),p("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,c.assertNodeType)("Identifier")},exported:{validate:(0,c.assertNodeType)("Identifier","StringLiteral")},exportKind:{validate:(0,c.assertOneOf)("type","value"),optional:!0}}}),p("ForOfStatement",{visitor:["left","right","body"],builder:["left","right","body","await"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:function(){if(!n.env.BABEL_TYPES_8_BREAKING)return(0,c.assertNodeType)("VariableDeclaration","LVal");const e=(0,c.assertNodeType)("VariableDeclaration"),t=(0,c.assertNodeType)("Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression");return Object.assign((function(r,n,i){(0,s.default)("VariableDeclaration",i)?e(r,n,i):t(r,n,i)}),{oneOfNodeTypes:["VariableDeclaration","Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"]})}()},right:{validate:(0,c.assertNodeType)("Expression")},body:{validate:(0,c.assertNodeType)("Statement")},await:{default:!1}}}),p("ImportDeclaration",{builder:["specifiers","source"],visitor:["specifiers","source","attributes","assertions"],aliases:["Statement","Declaration","ImportOrExportDeclaration"],fields:Object.assign({},m,{module:{optional:!0,validate:(0,c.assertValueType)("boolean")},phase:{default:null,validate:(0,c.assertOneOf)("source","defer")},specifiers:(0,c.validateArrayOfType)("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier"),source:{validate:(0,c.assertNodeType)("StringLiteral")},importKind:{validate:(0,c.assertOneOf)("type","typeof","value"),optional:!0}})}),p("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,c.assertNodeType)("Identifier")}}}),p("ImportNamespaceSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,c.assertNodeType)("Identifier")}}}),p("ImportSpecifier",{visitor:["imported","local"],builder:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,c.assertNodeType)("Identifier")},imported:{validate:(0,c.assertNodeType)("Identifier","StringLiteral")},importKind:{validate:(0,c.assertOneOf)("type","typeof","value"),optional:!0}}}),p("ImportExpression",{visitor:["source","options"],aliases:["Expression"],fields:{phase:{default:null,validate:(0,c.assertOneOf)("source","defer")},source:{validate:(0,c.assertNodeType)("Expression")},options:{validate:(0,c.assertNodeType)("Expression"),optional:!0}}}),p("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertNodeType)("Identifier"),Object.assign((function(e,t,r){let n;switch(r.name){case"function":n="sent";break;case"new":n="target";break;case"import":n="meta"}if(!(0,s.default)("Identifier",e.property,{name:n}))throw new TypeError("Unrecognised MetaProperty")}),{oneOfNodeTypes:["Identifier"]})):(0,c.assertNodeType)("Identifier")},property:{validate:(0,c.assertNodeType)("Identifier")}}});const y=()=>({abstract:{validate:(0,c.assertValueType)("boolean"),optional:!0},accessibility:{validate:(0,c.assertOneOf)("public","private","protected"),optional:!0},static:{default:!1},override:{default:!1},computed:{default:!1},optional:{validate:(0,c.assertValueType)("boolean"),optional:!0},key:{validate:(0,c.chain)(function(){const e=(0,c.assertNodeType)("Identifier","StringLiteral","NumericLiteral","BigIntLiteral"),t=(0,c.assertNodeType)("Expression");return function(r,n,s){(r.computed?t:e)(r,n,s)}}(),(0,c.assertNodeType)("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression"))}});t.classMethodOrPropertyCommon=y;const g=()=>Object.assign({},u(),y(),{params:(0,c.validateArrayOfType)("Identifier","Pattern","RestElement","TSParameterProperty"),kind:{validate:(0,c.assertOneOf)("get","set","method","constructor"),default:"method"},access:{validate:(0,c.chain)((0,c.assertValueType)("string"),(0,c.assertOneOf)("public","private","protected")),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0}});t.classMethodOrDeclareMethodCommon=g,p("ClassMethod",{aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static","generator","async"],visitor:["decorators","key","typeParameters","params","returnType","body"],fields:Object.assign({},g(),d(),{body:{validate:(0,c.assertNodeType)("BlockStatement")}})}),p("ObjectPattern",{visitor:["properties","typeAnnotation","decorators"],builder:["properties"],aliases:["Pattern","PatternLike","LVal"],fields:Object.assign({},h(),{properties:(0,c.validateArrayOfType)("RestElement","ObjectProperty")})}),p("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],deprecatedAlias:"SpreadProperty",fields:{argument:{validate:(0,c.assertNodeType)("Expression")}}}),p("Super",{aliases:["Expression"]}),p("TaggedTemplateExpression",{visitor:["tag","typeParameters","quasi"],builder:["tag","quasi"],aliases:["Expression"],fields:{tag:{validate:(0,c.assertNodeType)("Expression")},quasi:{validate:(0,c.assertNodeType)("TemplateLiteral")},typeParameters:{validate:(0,c.assertNodeType)("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0}}}),p("TemplateElement",{builder:["value","tail"],fields:{value:{validate:(0,c.chain)((0,c.assertShape)({raw:{validate:(0,c.assertValueType)("string")},cooked:{validate:(0,c.assertValueType)("string"),optional:!0}}),(function(e){const t=e.value.raw;let r=!1;const n=()=>{throw new Error("Internal @babel/types error.")},{str:s,firstInvalidLoc:i}=(0,o.readStringContents)("template",t,0,0,0,{unterminated(){r=!0},strictNumericEscape:n,invalidEscapeSequence:n,numericSeparatorInEscapeSequence:n,unexpectedNumericSeparator:n,invalidDigit:n,invalidCodePoint:n});if(!r)throw new Error("Invalid raw");e.value.cooked=i?null:s}))},tail:{default:!1}}}),p("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:(0,c.validateArrayOfType)("TemplateElement"),expressions:{validate:(0,c.chain)((0,c.assertValueType)("array"),(0,c.assertEach)((0,c.assertNodeType)("Expression","TSType")),(function(e,t,r){if(e.quasis.length!==r.length+1)throw new TypeError(`Number of ${e.type} quasis should be exactly one more than the number of expressions.\nExpected ${r.length+1} quasis but got ${e.quasis.length}`)}))}}}),p("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertValueType)("boolean"),Object.assign((function(e,t,r){if(r&&!e.argument)throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument")}),{type:"boolean"})):(0,c.assertValueType)("boolean"),default:!1},argument:{optional:!0,validate:(0,c.assertNodeType)("Expression")}}}),p("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:(0,c.assertNodeType)("Expression")}}}),p("Import",{aliases:["Expression"]}),p("BigIntLiteral",{builder:["value"],fields:{value:{validate:(0,c.assertValueType)("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),p("ExportNamespaceSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:(0,c.assertNodeType)("Identifier")}}}),p("OptionalMemberExpression",{builder:["object","property","computed","optional"],visitor:["object","property"],aliases:["Expression"],fields:{object:{validate:(0,c.assertNodeType)("Expression")},property:{validate:function(){const e=(0,c.assertNodeType)("Identifier"),t=(0,c.assertNodeType)("Expression");return Object.assign((function(r,n,s){(r.computed?t:e)(r,n,s)}),{oneOfNodeTypes:["Expression","Identifier"]})}()},computed:{default:!1},optional:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertValueType)("boolean"),(0,c.assertOptionalChainStart)()):(0,c.assertValueType)("boolean")}}}),p("OptionalCallExpression",{visitor:["callee","arguments","typeParameters","typeArguments"],builder:["callee","arguments","optional"],aliases:["Expression"],fields:Object.assign({callee:{validate:(0,c.assertNodeType)("Expression")},arguments:(0,c.validateArrayOfType)("Expression","SpreadElement","ArgumentPlaceholder"),optional:{validate:n.env.BABEL_TYPES_8_BREAKING?(0,c.chain)((0,c.assertValueType)("boolean"),(0,c.assertOptionalChainStart)()):(0,c.assertValueType)("boolean")},typeArguments:{validate:(0,c.assertNodeType)("TypeParameterInstantiation"),optional:!0}},{typeParameters:{validate:(0,c.assertNodeType)("TSTypeParameterInstantiation"),optional:!0}})}),p("ClassProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property"],fields:Object.assign({},y(),{value:{validate:(0,c.assertNodeType)("Expression"),optional:!0},definite:{validate:(0,c.assertValueType)("boolean"),optional:!0},typeAnnotation:{validate:(0,c.assertNodeType)("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0},readonly:{validate:(0,c.assertValueType)("boolean"),optional:!0},declare:{validate:(0,c.assertValueType)("boolean"),optional:!0},variance:{validate:(0,c.assertNodeType)("Variance"),optional:!0}})}),p("ClassAccessorProperty",{visitor:["decorators","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property","Accessor"],fields:Object.assign({},y(),{key:{validate:(0,c.chain)(function(){const e=(0,c.assertNodeType)("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","PrivateName"),t=(0,c.assertNodeType)("Expression");return function(r,n,s){(r.computed?t:e)(r,n,s)}}(),(0,c.assertNodeType)("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression","PrivateName"))},value:{validate:(0,c.assertNodeType)("Expression"),optional:!0},definite:{validate:(0,c.assertValueType)("boolean"),optional:!0},typeAnnotation:{validate:(0,c.assertNodeType)("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0},readonly:{validate:(0,c.assertValueType)("boolean"),optional:!0},declare:{validate:(0,c.assertValueType)("boolean"),optional:!0},variance:{validate:(0,c.assertNodeType)("Variance"),optional:!0}})}),p("ClassPrivateProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","decorators","static"],aliases:["Property","Private"],fields:{key:{validate:(0,c.assertNodeType)("PrivateName")},value:{validate:(0,c.assertNodeType)("Expression"),optional:!0},typeAnnotation:{validate:(0,c.assertNodeType)("TypeAnnotation","TSTypeAnnotation","Noop"),optional:!0},decorators:{validate:(0,c.arrayOfType)("Decorator"),optional:!0},static:{validate:(0,c.assertValueType)("boolean"),default:!1},readonly:{validate:(0,c.assertValueType)("boolean"),optional:!0},optional:{validate:(0,c.assertValueType)("boolean"),optional:!0},definite:{validate:(0,c.assertValueType)("boolean"),optional:!0},variance:{validate:(0,c.assertNodeType)("Variance"),optional:!0}}}),p("ClassPrivateMethod",{builder:["kind","key","params","body","static"],visitor:["decorators","key","typeParameters","params","returnType","body"],aliases:["Function","Scopable","BlockParent","FunctionParent","Method","Private"],fields:Object.assign({},g(),d(),{kind:{validate:(0,c.assertOneOf)("get","set","method"),default:"method"},key:{validate:(0,c.assertNodeType)("PrivateName")},body:{validate:(0,c.assertNodeType)("BlockStatement")}})}),p("PrivateName",{visitor:["id"],aliases:["Private"],fields:{id:{validate:(0,c.assertNodeType)("Identifier")}}}),p("StaticBlock",{visitor:["body"],fields:{body:(0,c.validateArrayOfType)("Statement")},aliases:["Scopable","BlockParent","FunctionParent"]})},5196:(e,t,r)=>{e.exports=r(439)},5237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(t){const r=Array.from(t),i=new Map,a=new Map,o=new Set,l=[];for(let t=0;t<r.length;t++){const c=r[t];if(c&&!l.includes(c)){if((0,n.isAnyTypeAnnotation)(c))return[c];if((0,n.isFlowBaseAnnotation)(c))a.set(c.type,c);else if((0,n.isUnionTypeAnnotation)(c))o.has(c.types)||(r.push(...c.types),o.add(c.types));else if((0,n.isGenericTypeAnnotation)(c)){const t=s(c.id);if(i.has(t)){let r=i.get(t);r.typeParameters?c.typeParameters&&(r.typeParameters.params.push(...c.typeParameters.params),r.typeParameters.params=e(r.typeParameters.params)):r=c.typeParameters}else i.set(t,c)}else l.push(c)}}for(const[,e]of a)l.push(e);for(const[,e]of i)l.push(e);return l};var n=r(8960);function s(e){return(0,n.isIdentifier)(e)?e.name:`${e.id.name}.${s(e.qualification)}`}},5252:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){let a;return t=e.code(t),o=>{const l=(0,n.normalizeReplacements)(o);return a||(a=(0,s.default)(e,t,r)),e.unwrap((0,i.default)(a,l))}};var n=r(9815),s=r(4858),i=r(7427)},5279:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t=!0,r=!1){return l(e,t,r,new Map)};var n=r(9793),s=r(8960);const{hasOwn:i}={hasOwn:Function.call.bind(Object.prototype.hasOwnProperty)};function a(e,t,r,n){return e&&"string"==typeof e.type?l(e,t,r,n):e}function o(e,t,r,n){return Array.isArray(e)?e.map((e=>a(e,t,r,n))):a(e,t,r,n)}function l(e,t=!0,r=!1,a){if(!e)return e;const{type:l}=e,p={type:e.type};if((0,s.isIdentifier)(e))p.name=e.name,i(e,"optional")&&"boolean"==typeof e.optional&&(p.optional=e.optional),i(e,"typeAnnotation")&&(p.typeAnnotation=t?o(e.typeAnnotation,!0,r,a):e.typeAnnotation),i(e,"decorators")&&(p.decorators=t?o(e.decorators,!0,r,a):e.decorators);else{if(!i(n.NODE_FIELDS,l))throw new Error(`Unknown node type: "${l}"`);for(const u of Object.keys(n.NODE_FIELDS[l]))i(e,u)&&(p[u]=t?(0,s.isFile)(e)&&"comments"===u?c(e.comments,t,r,a):o(e[u],!0,r,a):e[u])}return i(e,"loc")&&(p.loc=r?null:e.loc),i(e,"leadingComments")&&(p.leadingComments=c(e.leadingComments,t,r,a)),i(e,"innerComments")&&(p.innerComments=c(e.innerComments,t,r,a)),i(e,"trailingComments")&&(p.trailingComments=c(e.trailingComments,t,r,a)),i(e,"extra")&&(p.extra=Object.assign({},e.extra)),p}function c(e,t,r,n){return e&&t?e.map((e=>{const t=n.get(e);if(t)return t;const{type:s,value:i,loc:a}=e,o={type:s,value:i,loc:a};return r&&(o.loc=null),n.set(e,o),o})):e}},5283:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.parse=void 0,t.parseAsync=function(...e){return(0,o.beginHiddenCallStack)(l.async)(...e)},t.parseSync=function(...e){return(0,o.beginHiddenCallStack)(l.sync)(...e)};var s=r(6955),i=r(7262),a=r(9618),o=r(1339);const l=n()((function*(e,t){const r=yield*(0,s.default)(t);return null===r?null:yield*(0,i.default)(r.passes,(0,a.default)(r),e)}));t.parse=function(e,t,r){if("function"==typeof t&&(r=t,t=void 0),void 0===r)return(0,o.beginHiddenCallStack)(l.sync)(e,t);(0,o.beginHiddenCallStack)(l.errback)(e,t,r)}},5299:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.default)(e,!0,!0)};var n=r(5279)},5333:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t={}){const r=t.preserveComments?s:i;for(const t of r)null!=e[t]&&(e[t]=void 0);for(const t of Object.keys(e))"_"===t[0]&&null!=e[t]&&(e[t]=void 0);const n=Object.getOwnPropertySymbols(e);for(const t of n)e[t]=null};var n=r(3422);const s=["tokens","start","end","loc","raw","rawValue"],i=[...n.COMMENT_KEYS,"comments",...s]},5345:(e,t,r)=>{var n,s=r(5606);t=e.exports=v,n="object"==typeof s&&s.env&&s.env.NODE_DEBUG&&/\bsemver\b/i.test(s.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var i=256,a=Number.MAX_SAFE_INTEGER||9007199254740991,o=i-6,l=t.re=[],c=t.safeRe=[],p=t.src=[],u=t.tokens={},d=0;function f(e){u[e]=d++}var h="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",i],[h,o]];function y(e){for(var t=0;t<m.length;t++){var r=m[t][0],n=m[t][1];e=e.split(r+"*").join(r+"{0,"+n+"}").split(r+"+").join(r+"{1,"+n+"}")}return e}f("NUMERICIDENTIFIER"),p[u.NUMERICIDENTIFIER]="0|[1-9]\\d*",f("NUMERICIDENTIFIERLOOSE"),p[u.NUMERICIDENTIFIERLOOSE]="\\d+",f("NONNUMERICIDENTIFIER"),p[u.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-]"+h+"*",f("MAINVERSION"),p[u.MAINVERSION]="("+p[u.NUMERICIDENTIFIER]+")\\.("+p[u.NUMERICIDENTIFIER]+")\\.("+p[u.NUMERICIDENTIFIER]+")",f("MAINVERSIONLOOSE"),p[u.MAINVERSIONLOOSE]="("+p[u.NUMERICIDENTIFIERLOOSE]+")\\.("+p[u.NUMERICIDENTIFIERLOOSE]+")\\.("+p[u.NUMERICIDENTIFIERLOOSE]+")",f("PRERELEASEIDENTIFIER"),p[u.PRERELEASEIDENTIFIER]="(?:"+p[u.NUMERICIDENTIFIER]+"|"+p[u.NONNUMERICIDENTIFIER]+")",f("PRERELEASEIDENTIFIERLOOSE"),p[u.PRERELEASEIDENTIFIERLOOSE]="(?:"+p[u.NUMERICIDENTIFIERLOOSE]+"|"+p[u.NONNUMERICIDENTIFIER]+")",f("PRERELEASE"),p[u.PRERELEASE]="(?:-("+p[u.PRERELEASEIDENTIFIER]+"(?:\\."+p[u.PRERELEASEIDENTIFIER]+")*))",f("PRERELEASELOOSE"),p[u.PRERELEASELOOSE]="(?:-?("+p[u.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+p[u.PRERELEASEIDENTIFIERLOOSE]+")*))",f("BUILDIDENTIFIER"),p[u.BUILDIDENTIFIER]=h+"+",f("BUILD"),p[u.BUILD]="(?:\\+("+p[u.BUILDIDENTIFIER]+"(?:\\."+p[u.BUILDIDENTIFIER]+")*))",f("FULL"),f("FULLPLAIN"),p[u.FULLPLAIN]="v?"+p[u.MAINVERSION]+p[u.PRERELEASE]+"?"+p[u.BUILD]+"?",p[u.FULL]="^"+p[u.FULLPLAIN]+"$",f("LOOSEPLAIN"),p[u.LOOSEPLAIN]="[v=\\s]*"+p[u.MAINVERSIONLOOSE]+p[u.PRERELEASELOOSE]+"?"+p[u.BUILD]+"?",f("LOOSE"),p[u.LOOSE]="^"+p[u.LOOSEPLAIN]+"$",f("GTLT"),p[u.GTLT]="((?:<|>)?=?)",f("XRANGEIDENTIFIERLOOSE"),p[u.XRANGEIDENTIFIERLOOSE]=p[u.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*",f("XRANGEIDENTIFIER"),p[u.XRANGEIDENTIFIER]=p[u.NUMERICIDENTIFIER]+"|x|X|\\*",f("XRANGEPLAIN"),p[u.XRANGEPLAIN]="[v=\\s]*("+p[u.XRANGEIDENTIFIER]+")(?:\\.("+p[u.XRANGEIDENTIFIER]+")(?:\\.("+p[u.XRANGEIDENTIFIER]+")(?:"+p[u.PRERELEASE]+")?"+p[u.BUILD]+"?)?)?",f("XRANGEPLAINLOOSE"),p[u.XRANGEPLAINLOOSE]="[v=\\s]*("+p[u.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[u.XRANGEIDENTIFIERLOOSE]+")(?:\\.("+p[u.XRANGEIDENTIFIERLOOSE]+")(?:"+p[u.PRERELEASELOOSE]+")?"+p[u.BUILD]+"?)?)?",f("XRANGE"),p[u.XRANGE]="^"+p[u.GTLT]+"\\s*"+p[u.XRANGEPLAIN]+"$",f("XRANGELOOSE"),p[u.XRANGELOOSE]="^"+p[u.GTLT]+"\\s*"+p[u.XRANGEPLAINLOOSE]+"$",f("COERCE"),p[u.COERCE]="(^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])",f("COERCERTL"),l[u.COERCERTL]=new RegExp(p[u.COERCE],"g"),c[u.COERCERTL]=new RegExp(y(p[u.COERCE]),"g"),f("LONETILDE"),p[u.LONETILDE]="(?:~>?)",f("TILDETRIM"),p[u.TILDETRIM]="(\\s*)"+p[u.LONETILDE]+"\\s+",l[u.TILDETRIM]=new RegExp(p[u.TILDETRIM],"g"),c[u.TILDETRIM]=new RegExp(y(p[u.TILDETRIM]),"g"),f("TILDE"),p[u.TILDE]="^"+p[u.LONETILDE]+p[u.XRANGEPLAIN]+"$",f("TILDELOOSE"),p[u.TILDELOOSE]="^"+p[u.LONETILDE]+p[u.XRANGEPLAINLOOSE]+"$",f("LONECARET"),p[u.LONECARET]="(?:\\^)",f("CARETTRIM"),p[u.CARETTRIM]="(\\s*)"+p[u.LONECARET]+"\\s+",l[u.CARETTRIM]=new RegExp(p[u.CARETTRIM],"g"),c[u.CARETTRIM]=new RegExp(y(p[u.CARETTRIM]),"g"),f("CARET"),p[u.CARET]="^"+p[u.LONECARET]+p[u.XRANGEPLAIN]+"$",f("CARETLOOSE"),p[u.CARETLOOSE]="^"+p[u.LONECARET]+p[u.XRANGEPLAINLOOSE]+"$",f("COMPARATORLOOSE"),p[u.COMPARATORLOOSE]="^"+p[u.GTLT]+"\\s*("+p[u.LOOSEPLAIN]+")$|^$",f("COMPARATOR"),p[u.COMPARATOR]="^"+p[u.GTLT]+"\\s*("+p[u.FULLPLAIN]+")$|^$",f("COMPARATORTRIM"),p[u.COMPARATORTRIM]="(\\s*)"+p[u.GTLT]+"\\s*("+p[u.LOOSEPLAIN]+"|"+p[u.XRANGEPLAIN]+")",l[u.COMPARATORTRIM]=new RegExp(p[u.COMPARATORTRIM],"g"),c[u.COMPARATORTRIM]=new RegExp(y(p[u.COMPARATORTRIM]),"g"),f("HYPHENRANGE"),p[u.HYPHENRANGE]="^\\s*("+p[u.XRANGEPLAIN]+")\\s+-\\s+("+p[u.XRANGEPLAIN]+")\\s*$",f("HYPHENRANGELOOSE"),p[u.HYPHENRANGELOOSE]="^\\s*("+p[u.XRANGEPLAINLOOSE]+")\\s+-\\s+("+p[u.XRANGEPLAINLOOSE]+")\\s*$",f("STAR"),p[u.STAR]="(<|>)?=?\\s*\\*";for(var g=0;g<d;g++)n(g,p[g]),l[g]||(l[g]=new RegExp(p[g]),c[g]=new RegExp(y(p[g])));function b(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof v)return e;if("string"!=typeof e)return null;if(e.length>i)return null;if(!(t.loose?c[u.LOOSE]:c[u.FULL]).test(e))return null;try{return new v(e,t)}catch(e){return null}}function v(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof v){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>i)throw new TypeError("version is longer than "+i+" characters");if(!(this instanceof v))return new v(e,t);n("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?c[u.LOOSE]:c[u.FULL]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>a||this.major<0)throw new TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t<a)return t}return e})):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}t.parse=b,t.valid=function(e,t){var r=b(e,t);return r?r.version:null},t.clean=function(e,t){var r=b(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null},t.SemVer=v,v.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version},v.prototype.toString=function(){return this.version},v.prototype.compare=function(e){return n("SemVer.compare",this.version,this.options,e),e instanceof v||(e=new v(e,this.options)),this.compareMain(e)||this.comparePre(e)},v.prototype.compareMain=function(e){return e instanceof v||(e=new v(e,this.options)),x(this.major,e.major)||x(this.minor,e.minor)||x(this.patch,e.patch)},v.prototype.comparePre=function(e){if(e instanceof v||(e=new v(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;var t=0;do{var r=this.prerelease[t],s=e.prerelease[t];if(n("prerelease compare",t,r,s),void 0===r&&void 0===s)return 0;if(void 0===s)return 1;if(void 0===r)return-1;if(r!==s)return x(r,s)}while(++t)},v.prototype.compareBuild=function(e){e instanceof v||(e=new v(e,this.options));var t=0;do{var r=this.build[t],s=e.build[t];if(n("prerelease compare",t,r,s),void 0===r&&void 0===s)return 0;if(void 0===s)return 1;if(void 0===r)return-1;if(r!==s)return x(r,s)}while(++t)},v.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t),this.inc("pre",t);break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":if(0===this.prerelease.length)this.prerelease=[0];else{for(var r=this.prerelease.length;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,r,n){"string"==typeof r&&(n=r,r=void 0);try{return new v(e,r).inc(t,n).version}catch(e){return null}},t.diff=function(e,t){if(A(e,t))return null;var r=b(e),n=b(t),s="";if(r.prerelease.length||n.prerelease.length){s="pre";var i="prerelease"}for(var a in r)if(("major"===a||"minor"===a||"patch"===a)&&r[a]!==n[a])return s+a;return i},t.compareIdentifiers=x;var T=/^[0-9]+$/;function x(e,t){var r=T.test(e),n=T.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1}function S(e,t,r){return new v(e,r).compare(new v(t,r))}function E(e,t,r){return S(e,t,r)>0}function P(e,t,r){return S(e,t,r)<0}function A(e,t,r){return 0===S(e,t,r)}function w(e,t,r){return 0!==S(e,t,r)}function C(e,t,r){return S(e,t,r)>=0}function O(e,t,r){return S(e,t,r)<=0}function I(e,t,r,n){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return A(e,r,n);case"!=":return w(e,r,n);case">":return E(e,r,n);case">=":return C(e,r,n);case"<":return P(e,r,n);case"<=":return O(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}function N(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof N){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof N))return new N(e,t);e=e.trim().split(/\s+/).join(" "),n("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===k?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}t.rcompareIdentifiers=function(e,t){return x(t,e)},t.major=function(e,t){return new v(e,t).major},t.minor=function(e,t){return new v(e,t).minor},t.patch=function(e,t){return new v(e,t).patch},t.compare=S,t.compareLoose=function(e,t){return S(e,t,!0)},t.compareBuild=function(e,t,r){var n=new v(e,r),s=new v(t,r);return n.compare(s)||n.compareBuild(s)},t.rcompare=function(e,t,r){return S(t,e,r)},t.sort=function(e,r){return e.sort((function(e,n){return t.compareBuild(e,n,r)}))},t.rsort=function(e,r){return e.sort((function(e,n){return t.compareBuild(n,e,r)}))},t.gt=E,t.lt=P,t.eq=A,t.neq=w,t.gte=C,t.lte=O,t.cmp=I,t.Comparator=N;var k={};function _(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof _)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new _(e.raw,t);if(e instanceof N)return new _(e.value,t);if(!(this instanceof _))return new _(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+this.raw);this.format()}function D(e,t){for(var r=!0,n=e.slice(),s=n.pop();r&&n.length;)r=n.every((function(e){return s.intersects(e,t)})),s=n.pop();return r}function j(e){return!e||"x"===e.toLowerCase()||"*"===e}function B(e,t,r,n,s,i,a,o,l,c,p,u,d){return((t=j(r)?"":j(n)?">="+r+".0.0":j(s)?">="+r+"."+n+".0":">="+t)+" "+(o=j(l)?"":j(c)?"<"+(+l+1)+".0.0":j(p)?"<"+l+"."+(+c+1)+".0":u?"<="+l+"."+c+"."+p+"-"+u:"<="+o)).trim()}function M(e,t,r){for(var s=0;s<e.length;s++)if(!e[s].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(s=0;s<e.length;s++)if(n(e[s].semver),e[s].semver!==k&&e[s].semver.prerelease.length>0){var i=e[s].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}function L(e,t,r){try{t=new _(t,r)}catch(e){return!1}return t.test(e)}function F(e,t,r,n){var s,i,a,o,l;switch(e=new v(e,n),t=new _(t,n),r){case">":s=E,i=O,a=P,o=">",l=">=";break;case"<":s=P,i=C,a=E,o="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(L(e,t,n))return!1;for(var c=0;c<t.set.length;++c){var p=t.set[c],u=null,d=null;if(p.forEach((function(e){e.semver===k&&(e=new N(">=0.0.0")),u=u||e,d=d||e,s(e.semver,u.semver,n)?u=e:a(e.semver,d.semver,n)&&(d=e)})),u.operator===o||u.operator===l)return!1;if((!d.operator||d.operator===o)&&i(e,d.semver))return!1;if(d.operator===l&&a(e,d.semver))return!1}return!0}N.prototype.parse=function(e){var t=this.options.loose?c[u.COMPARATORLOOSE]:c[u.COMPARATOR],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new v(r[2],this.options.loose):this.semver=k},N.prototype.toString=function(){return this.value},N.prototype.test=function(e){if(n("Comparator.test",e,this.options.loose),this.semver===k||e===k)return!0;if("string"==typeof e)try{e=new v(e,this.options)}catch(e){return!1}return I(e,this.operator,this.semver,this.options)},N.prototype.intersects=function(e,t){if(!(e instanceof N))throw new TypeError("a Comparator is required");var r;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return""===this.value||(r=new _(e.value,t),L(this.value,r,t));if(""===e.operator)return""===e.value||(r=new _(this.value,t),L(e.semver,r,t));var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),s=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),i=this.semver.version===e.semver.version,a=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),o=I(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),l=I(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||s||i&&a||o||l},t.Range=_,_.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},_.prototype.toString=function(){return this.range},_.prototype.parseRange=function(e){var t=this.options.loose,r=t?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];e=e.replace(r,B),n("hyphen replace",e),e=e.replace(c[u.COMPARATORTRIM],"$1$2$3"),n("comparator trim",e,c[u.COMPARATORTRIM]),e=(e=(e=e.replace(c[u.TILDETRIM],"$1~")).replace(c[u.CARETTRIM],"$1^")).split(/\s+/).join(" ");var s=t?c[u.COMPARATORLOOSE]:c[u.COMPARATOR],i=e.split(" ").map((function(e){return function(e,t){return n("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){n("caret",e,t);var r=t.loose?c[u.CARETLOOSE]:c[u.CARET];return e.replace(r,(function(t,r,s,i,a){var o;return n("caret",e,t,r,s,i,a),j(r)?o="":j(s)?o=">="+r+".0.0 <"+(+r+1)+".0.0":j(i)?o="0"===r?">="+r+"."+s+".0 <"+r+"."+(+s+1)+".0":">="+r+"."+s+".0 <"+(+r+1)+".0.0":a?(n("replaceCaret pr",a),o="0"===r?"0"===s?">="+r+"."+s+"."+i+"-"+a+" <"+r+"."+s+"."+(+i+1):">="+r+"."+s+"."+i+"-"+a+" <"+r+"."+(+s+1)+".0":">="+r+"."+s+"."+i+"-"+a+" <"+(+r+1)+".0.0"):(n("no pr"),o="0"===r?"0"===s?">="+r+"."+s+"."+i+" <"+r+"."+s+"."+(+i+1):">="+r+"."+s+"."+i+" <"+r+"."+(+s+1)+".0":">="+r+"."+s+"."+i+" <"+(+r+1)+".0.0"),n("caret return",o),o}))}(e,t)})).join(" ")}(e,t),n("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var r=t.loose?c[u.TILDELOOSE]:c[u.TILDE];return e.replace(r,(function(t,r,s,i,a){var o;return n("tilde",e,t,r,s,i,a),j(r)?o="":j(s)?o=">="+r+".0.0 <"+(+r+1)+".0.0":j(i)?o=">="+r+"."+s+".0 <"+r+"."+(+s+1)+".0":a?(n("replaceTilde pr",a),o=">="+r+"."+s+"."+i+"-"+a+" <"+r+"."+(+s+1)+".0"):o=">="+r+"."+s+"."+i+" <"+r+"."+(+s+1)+".0",n("tilde return",o),o}))}(e,t)})).join(" ")}(e,t),n("tildes",e),e=function(e,t){return n("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var r=t.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return e.replace(r,(function(r,s,i,a,o,l){n("xRange",e,r,s,i,a,o,l);var c=j(i),p=c||j(a),u=p||j(o),d=u;return"="===s&&d&&(s=""),l=t.includePrerelease?"-0":"",c?r=">"===s||"<"===s?"<0.0.0-0":"*":s&&d?(p&&(a=0),o=0,">"===s?(s=">=",p?(i=+i+1,a=0,o=0):(a=+a+1,o=0)):"<="===s&&(s="<",p?i=+i+1:a=+a+1),r=s+i+"."+a+"."+o+l):p?r=">="+i+".0.0"+l+" <"+(+i+1)+".0.0"+l:u&&(r=">="+i+"."+a+".0"+l+" <"+i+"."+(+a+1)+".0"+l),n("xRange return",r),r}))}(e,t)})).join(" ")}(e,t),n("xrange",e),e=function(e,t){return n("replaceStars",e,t),e.trim().replace(c[u.STAR],"")}(e,t),n("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter((function(e){return!!e.match(s)}))),i.map((function(e){return new N(e,this.options)}),this)},_.prototype.intersects=function(e,t){if(!(e instanceof _))throw new TypeError("a Range is required");return this.set.some((function(r){return D(r,t)&&e.set.some((function(e){return D(e,t)&&r.every((function(r){return e.every((function(e){return r.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new _(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},_.prototype.test=function(e){if(!e)return!1;if("string"==typeof e)try{e=new v(e,this.options)}catch(e){return!1}for(var t=0;t<this.set.length;t++)if(M(this.set[t],e,this.options))return!0;return!1},t.satisfies=L,t.maxSatisfying=function(e,t,r){var n=null,s=null;try{var i=new _(t,r)}catch(e){return null}return e.forEach((function(e){i.test(e)&&(n&&-1!==s.compare(e)||(s=new v(n=e,r)))})),n},t.minSatisfying=function(e,t,r){var n=null,s=null;try{var i=new _(t,r)}catch(e){return null}return e.forEach((function(e){i.test(e)&&(n&&1!==s.compare(e)||(s=new v(n=e,r)))})),n},t.minVersion=function(e,t){e=new _(e,t);var r=new v("0.0.0");if(e.test(r))return r;if(r=new v("0.0.0-0"),e.test(r))return r;r=null;for(var n=0;n<e.set.length;++n)e.set[n].forEach((function(e){var t=new v(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":r&&!E(r,t)||(r=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}));return r&&e.test(r)?r:null},t.validRange=function(e,t){try{return new _(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,r){return F(e,t,"<",r)},t.gtr=function(e,t,r){return F(e,t,">",r)},t.outside=F,t.prerelease=function(e,t){var r=b(e,t);return r&&r.prerelease.length?r.prerelease:null},t.intersects=function(e,t,r){return e=new _(e,r),t=new _(t,r),e.intersects(t)},t.coerce=function(e,t){if(e instanceof v)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;var r=null;if((t=t||{}).rtl){for(var n;(n=c[u.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)r&&n.index+n[0].length===r.index+r[0].length||(r=n),c[u.COERCERTL].lastIndex=n.index+n[1].length+n[2].length;c[u.COERCERTL].lastIndex=-1}else r=e.match(c[u.COERCE]);return null===r?null:b(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}},5562:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Var=t.User=t.Statement=t.SpreadProperty=t.Scope=t.RestProperty=t.ReferencedMemberExpression=t.ReferencedIdentifier=t.Referenced=t.Pure=t.NumericLiteralTypeAnnotation=t.Generated=t.ForAwaitStatement=t.Flow=t.Expression=t.ExistentialTypeParam=t.BlockScoped=t.BindingIdentifier=void 0,t.ReferencedIdentifier=["Identifier","JSXIdentifier"],t.ReferencedMemberExpression=["MemberExpression"],t.BindingIdentifier=["Identifier"],t.Statement=["Statement"],t.Expression=["Expression"],t.Scope=["Scopable","Pattern"],t.Referenced=null,t.BlockScoped=null,t.Var=["VariableDeclaration"],t.User=null,t.Generated=null,t.Pure=null,t.Flow=["Flow","ImportDeclaration","ExportDeclaration","ImportSpecifier"],t.RestProperty=["RestElement"],t.SpreadProperty=["RestElement"],t.ExistentialTypeParam=["ExistsTypeAnnotation"],t.NumericLiteralTypeAnnotation=["NumberLiteralTypeAnnotation"],t.ForAwaitStatement=["ForOfStatement"]},5586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){(0,n.default)("trailingComments",e,t)};var n=r(3205)},5589:(e,t,r)=>{"use strict";var n=r(7596),s=r(9187),i=r(5158);const a=(0,n.defineAliasedType)("Miscellaneous");a("Noop",{visitor:[]}),a("Placeholder",{visitor:[],builder:["expectedNode","name"],fields:Object.assign({name:{validate:(0,n.assertNodeType)("Identifier")},expectedNode:{validate:(0,n.assertOneOf)(...s.PLACEHOLDERS)}},(0,i.patternLikeCommon)())}),a("V8IntrinsicIdentifier",{builder:["name"],fields:{name:{validate:(0,n.assertValueType)("string")}}})},5606:e=>{var t,r,n=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===s||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:s}catch(e){t=s}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=i}}();var o,l=[],c=!1,p=-1;function u(){c&&o&&(c=!1,o.length?l=o.concat(l):p=-1,l.length&&d())}function d(){if(!c){var e=a(u);c=!0;for(var t=l.length;t;){for(o=l,l=[];++p<t;)o&&o[p].run();p=-1,t=l.length}o=null,c=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function f(e,t){this.fun=e,this.array=t}function h(){}n.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];l.push(new f(e,t)),1!==l.length||c||a(d)},f.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=h,n.addListener=h,n.once=h,n.off=h,n.removeListener=h,n.removeAllListeners=h,n.emit=h,n.prependListener=h,n.prependOnceListener=h,n.listeners=function(e){return[]},n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},5680:(e,t,r)=>{"use strict";var n=r(5767);e.exports=function(e){return!!n(e)}},5682:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;const n=(0,r(3937).default)("React.Component");t.default=n},5689:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEPRECATED_ALIASES=void 0,t.DEPRECATED_ALIASES={ModuleDeclaration:"ImportOrExportDeclaration"}},5766:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){(0,n.default)("leadingComments",e,t)};var n=r(3205)},5767:(e,t,r)=>{"use strict";var n=r(2682),s=r(9209),i=r(487),a=r(6556),o=r(5795),l=r(3628),c=a("Object.prototype.toString"),p=r(9092)(),u="undefined"==typeof globalThis?r.g:globalThis,d=s(),f=a("String.prototype.slice"),h=a("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r<e.length;r+=1)if(e[r]===t)return r;return-1},m={__proto__:null};n(d,p&&o&&l?function(e){var t=new u[e];if(Symbol.toStringTag in t&&l){var r=l(t),n=o(r,Symbol.toStringTag);if(!n&&r){var s=l(r);n=o(s,Symbol.toStringTag)}m["$"+e]=i(n.get)}}:function(e){var t=new u[e],r=t.slice||t.set;r&&(m["$"+e]=i(r))}),e.exports=function(e){if(!e||"object"!=typeof e)return!1;if(!p){var t=f(c(e),8,-1);return h(d,t)>-1?t:"Object"===t&&function(e){var t=!1;return n(m,(function(r,n){if(!t)try{r(e),t=f(n,1)}catch(e){}})),t}(e)}return o?function(e){var t=!1;return n(m,(function(r,n){if(!t)try{"$"+r(e)===n&&(t=f(n,1))}catch(e){}})),t}(e):null}},5781:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Hub",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(t,"NodePath",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return l.default}}),t.visitors=t.default=void 0,r(9578);var n=r(4950);t.visitors=n;var s=r(2352),i=r(7411),a=r(2264),o=r(9709),l=r(6814),c=r(7878);const{VISITOR_KEYS:p,removeProperties:u,traverseFast:d}=s;function f(e,t={},r,s,i,o){if(e){if(!t.noScope&&!r&&"Program"!==e.type&&"File"!==e.type)throw new Error(`You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a ${e.type} node without passing scope and parentPath.`);if(!i&&o)throw new Error("visitSelf can only be used when providing a NodePath.");p[e.type]&&(n.explode(t),(0,a.traverseNode)(e,t,r,s,i,null,o))}}function h(e,t){e.node.type===t.type&&(t.has=!0,e.stop())}t.default=f,f.visitors=n,f.verify=n.verify,f.explode=n.explode,f.cheap=function(e,t){d(e,t)},f.node=function(e,t,r,n,s,i){(0,a.traverseNode)(e,t,r,n,s,i)},f.clearNode=function(e,t){u(e,t)},f.removeProperties=function(e,t){return d(e,f.clearNode,t),e},f.hasType=function(e,t,r){if(null!=r&&r.includes(e.type))return!1;if(e.type===t)return!0;const n={has:!1,type:t};return f(e,{noScope:!0,denylist:r,enter:h},null,n),n.has},f.cache=i},5795:(e,t,r)=>{"use strict";var n=r(6549);if(n)try{n([],"length")}catch(e){n=null}e.exports=n},5856:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(947);t.default=class{constructor(e,t,r,s=(0,n.finalize)([])){this.key=void 0,this.manipulateOptions=void 0,this.post=void 0,this.pre=void 0,this.visitor=void 0,this.parserOverride=void 0,this.generatorOverride=void 0,this.options=void 0,this.externalDependencies=void 0,this.key=e.name||r,this.manipulateOptions=e.manipulateOptions,this.post=e.post,this.pre=e.pre,this.visitor=e.visitor||{},this.parserOverride=e.parserOverride,this.generatorOverride=e.generatorOverride,this.options=t,this.externalDependencies=s}}},5879:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=/((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g,t.matchToToken=function(e){var t={type:"invalid",value:e[0],closed:void 0};return e[1]?(t.type="string",t.closed=!(!e[3]&&!e[4])):e[5]?t.type="comment":e[6]?(t.type="comment",t.closed=!!e[7]):e[8]?t.type="regex":e[9]?t.type="number":e[10]?t.type="name":e[11]?t.type="punctuator":e[12]&&(t.type="whitespace"),t}},5880:e=>{"use strict";e.exports=Math.pow},5913:(e,t)=>{"use strict";var r;function n(e,t){(t=t||{}).hasComment&&(e=function(e){return e.split(",").pop()}(e)),"base64"===t.encoding?e=r(e):"uri"===t.encoding&&(e=decodeURIComponent(e)),(t.isJSON||t.encoding)&&(e=JSON.parse(e)),this.sourcemap=e}function s(e){return new n(e,{isJSON:!0})}Object.defineProperty(t,"commentRegex",{get:function(){return/^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/gm}}),Object.defineProperty(t,"mapFileCommentRegex",{get:function(){return/(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/gm}}),r="undefined"!=typeof Buffer?"function"==typeof Buffer.from?function(e){return Buffer.from(e,"base64").toString()}:function(e){if("number"==typeof value)throw new TypeError("The value to decode must not be of type number.");return new Buffer(e,"base64").toString()}:function(e){return decodeURIComponent(escape(atob(e)))},n.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)},"undefined"!=typeof Buffer?"function"==typeof Buffer.from?n.prototype.toBase64=function(){var e=this.toJSON();return Buffer.from(e,"utf8").toString("base64")}:n.prototype.toBase64=function(){var e=this.toJSON();if("number"==typeof e)throw new TypeError("The json to encode must not be of type number.");return new Buffer(e,"utf8").toString("base64")}:n.prototype.toBase64=function(){var e=this.toJSON();return btoa(unescape(encodeURIComponent(e)))},n.prototype.toURI=function(){var e=this.toJSON();return encodeURIComponent(e)},n.prototype.toComment=function(e){var t,r,n;return null!=e&&"uri"===e.encoding?(t="",r=this.toURI()):(t=";base64",r=this.toBase64()),n="sourceMappingURL=data:application/json;charset=utf-8"+t+","+r,null!=e&&e.multiline?"/*# "+n+" */":"//# "+n},n.prototype.toObject=function(){return JSON.parse(this.toJSON())},n.prototype.addProperty=function(e,t){if(this.sourcemap.hasOwnProperty(e))throw new Error('property "'+e+'" already exists on the sourcemap, use set property instead');return this.setProperty(e,t)},n.prototype.setProperty=function(e,t){return this.sourcemap[e]=t,this},n.prototype.getProperty=function(e){return this.sourcemap[e]},t.fromObject=function(e){return new n(e)},t.fromJSON=function(e){return new n(e,{isJSON:!0})},t.fromURI=function(e){return new n(e,{encoding:"uri"})},t.fromBase64=function(e){return new n(e,{encoding:"base64"})},t.fromComment=function(e){var r;return new n(e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,""),{encoding:(r=t.commentRegex.exec(e))&&r[4]||"uri",hasComment:!0})},t.fromMapFileComment=function(e,r){if("string"==typeof r)throw new Error("String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading");var n=function(e,r){var n=t.mapFileCommentRegex.exec(e),s=n[1]||n[2];try{return null!=(e=r(s))&&"function"==typeof e.catch?e.catch(i):e}catch(e){i(e)}function i(e){throw new Error("An error occurred while trying to read the map file at "+s+"\n"+e.stack)}}(e,r);return null!=n&&"function"==typeof n.then?n.then(s):s(n)},t.fromSource=function(e){var r=e.match(t.commentRegex);return r?t.fromComment(r.pop()):null},t.fromMapFileSource=function(e,r){if("string"==typeof r)throw new Error("String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading");var n=e.match(t.mapFileCommentRegex);return n?t.fromMapFileComment(n.pop(),r):null},t.removeComments=function(e){return e.replace(t.commentRegex,"")},t.removeMapFileComments=function(e){return e.replace(t.mapFileCommentRegex,"")},t.generateMapFileComment=function(e,t){var r="sourceMappingURL="+e;return t&&t.multiline?"/*# "+r+" */":"//# "+r}},5958:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(8079);t.default=function(e){switch(e){case"string":return(0,n.stringTypeAnnotation)();case"number":return(0,n.numberTypeAnnotation)();case"undefined":return(0,n.voidTypeAnnotation)();case"boolean":return(0,n.booleanTypeAnnotation)();case"function":return(0,n.genericTypeAnnotation)((0,n.identifier)("Function"));case"object":return(0,n.genericTypeAnnotation)((0,n.identifier)("Object"));case"symbol":return(0,n.genericTypeAnnotation)((0,n.identifier)("Symbol"));case"bigint":return(0,n.anyTypeAnnotation)()}throw new Error("Invalid typeof value: "+e)}},6019:(e,t,r)=>{"use strict";const n=r(2660).browsers,s=r(5040).browserVersions,i=r(6481);function a(e){return Object.keys(e).reduce(((t,r)=>(t[s[r]]=e[r],t)),{})}e.exports.X=Object.keys(i).reduce(((e,t)=>{let r=i[t];return e[n[t]]=Object.keys(r).reduce(((e,t)=>("A"===t?e.usage_global=a(r[t]):"C"===t?e.versions=r[t].reduce(((e,t)=>(""===t?e.push(null):e.push(s[t]),e)),[]):"D"===t?e.prefix_exceptions=a(r[t]):"E"===t?e.browser=r[t]:"F"===t?e.release_date=Object.keys(r[t]).reduce(((e,n)=>(e[s[n]]=r[t][n],e)),{}):e.prefix=r[t],e)),{}),e}),{})},6049:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){const t=e.map((e=>(0,i.isTSTypeAnnotation)(e)?e.typeAnnotation:e)),r=(0,s.default)(t);return 1===r.length?r[0]:(0,n.tsUnionType)(r)};var n=r(8079),s=r(8812),i=r(8960)},6106:(e,t,r)=>{"use strict";var n=r(7596),s=r(5158),i=r(3828);const a=(0,n.defineAliasedType)("TypeScript"),o=(0,n.assertValueType)("boolean"),l=()=>({returnType:{validate:(0,n.assertNodeType)("TSTypeAnnotation","Noop"),optional:!0},typeParameters:{validate:(0,n.assertNodeType)("TSTypeParameterDeclaration","Noop"),optional:!0}});a("TSParameterProperty",{aliases:["LVal"],visitor:["parameter"],fields:{accessibility:{validate:(0,n.assertOneOf)("public","private","protected"),optional:!0},readonly:{validate:(0,n.assertValueType)("boolean"),optional:!0},parameter:{validate:(0,n.assertNodeType)("Identifier","AssignmentPattern")},override:{validate:(0,n.assertValueType)("boolean"),optional:!0},decorators:{validate:(0,n.arrayOfType)("Decorator"),optional:!0}}}),a("TSDeclareFunction",{aliases:["Statement","Declaration"],visitor:["id","typeParameters","params","returnType"],fields:Object.assign({},(0,s.functionDeclarationCommon)(),l())}),a("TSDeclareMethod",{visitor:["decorators","key","typeParameters","params","returnType"],fields:Object.assign({},(0,s.classMethodOrDeclareMethodCommon)(),l())}),a("TSQualifiedName",{aliases:["TSEntityName"],visitor:["left","right"],fields:{left:(0,n.validateType)("TSEntityName"),right:(0,n.validateType)("Identifier")}});const c=()=>({typeParameters:(0,n.validateOptionalType)("TSTypeParameterDeclaration"),parameters:(0,n.validateArrayOfType)("ArrayPattern","Identifier","ObjectPattern","RestElement"),typeAnnotation:(0,n.validateOptionalType)("TSTypeAnnotation")}),p={aliases:["TSTypeElement"],visitor:["typeParameters","parameters","typeAnnotation"],fields:c()};a("TSCallSignatureDeclaration",p),a("TSConstructSignatureDeclaration",p);const u=()=>({key:(0,n.validateType)("Expression"),computed:{default:!1},optional:(0,n.validateOptional)(o)});a("TSPropertySignature",{aliases:["TSTypeElement"],visitor:["key","typeAnnotation"],fields:Object.assign({},u(),{readonly:(0,n.validateOptional)(o),typeAnnotation:(0,n.validateOptionalType)("TSTypeAnnotation"),kind:{optional:!0,validate:(0,n.assertOneOf)("get","set")}})}),a("TSMethodSignature",{aliases:["TSTypeElement"],visitor:["key","typeParameters","parameters","typeAnnotation"],fields:Object.assign({},c(),u(),{kind:{validate:(0,n.assertOneOf)("method","get","set")}})}),a("TSIndexSignature",{aliases:["TSTypeElement"],visitor:["parameters","typeAnnotation"],fields:{readonly:(0,n.validateOptional)(o),static:(0,n.validateOptional)(o),parameters:(0,n.validateArrayOfType)("Identifier"),typeAnnotation:(0,n.validateOptionalType)("TSTypeAnnotation")}});const d=["TSAnyKeyword","TSBooleanKeyword","TSBigIntKeyword","TSIntrinsicKeyword","TSNeverKeyword","TSNullKeyword","TSNumberKeyword","TSObjectKeyword","TSStringKeyword","TSSymbolKeyword","TSUndefinedKeyword","TSUnknownKeyword","TSVoidKeyword"];for(const e of d)a(e,{aliases:["TSType","TSBaseType"],visitor:[],fields:{}});a("TSThisType",{aliases:["TSType","TSBaseType"],visitor:[],fields:{}});const f={aliases:["TSType"],visitor:["typeParameters","parameters","typeAnnotation"]};a("TSFunctionType",Object.assign({},f,{fields:c()})),a("TSConstructorType",Object.assign({},f,{fields:Object.assign({},c(),{abstract:(0,n.validateOptional)(o)})})),a("TSTypeReference",{aliases:["TSType"],visitor:["typeName","typeParameters"],fields:{typeName:(0,n.validateType)("TSEntityName"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterInstantiation")}}),a("TSTypePredicate",{aliases:["TSType"],visitor:["parameterName","typeAnnotation"],builder:["parameterName","typeAnnotation","asserts"],fields:{parameterName:(0,n.validateType)("Identifier","TSThisType"),typeAnnotation:(0,n.validateOptionalType)("TSTypeAnnotation"),asserts:(0,n.validateOptional)(o)}}),a("TSTypeQuery",{aliases:["TSType"],visitor:["exprName","typeParameters"],fields:{exprName:(0,n.validateType)("TSEntityName","TSImportType"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterInstantiation")}}),a("TSTypeLiteral",{aliases:["TSType"],visitor:["members"],fields:{members:(0,n.validateArrayOfType)("TSTypeElement")}}),a("TSArrayType",{aliases:["TSType"],visitor:["elementType"],fields:{elementType:(0,n.validateType)("TSType")}}),a("TSTupleType",{aliases:["TSType"],visitor:["elementTypes"],fields:{elementTypes:(0,n.validateArrayOfType)("TSType","TSNamedTupleMember")}}),a("TSOptionalType",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{typeAnnotation:(0,n.validateType)("TSType")}}),a("TSRestType",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{typeAnnotation:(0,n.validateType)("TSType")}}),a("TSNamedTupleMember",{visitor:["label","elementType"],builder:["label","elementType","optional"],fields:{label:(0,n.validateType)("Identifier"),optional:{validate:o,default:!1},elementType:(0,n.validateType)("TSType")}});const h={aliases:["TSType"],visitor:["types"],fields:{types:(0,n.validateArrayOfType)("TSType")}};a("TSUnionType",h),a("TSIntersectionType",h),a("TSConditionalType",{aliases:["TSType"],visitor:["checkType","extendsType","trueType","falseType"],fields:{checkType:(0,n.validateType)("TSType"),extendsType:(0,n.validateType)("TSType"),trueType:(0,n.validateType)("TSType"),falseType:(0,n.validateType)("TSType")}}),a("TSInferType",{aliases:["TSType"],visitor:["typeParameter"],fields:{typeParameter:(0,n.validateType)("TSTypeParameter")}}),a("TSParenthesizedType",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{typeAnnotation:(0,n.validateType)("TSType")}}),a("TSTypeOperator",{aliases:["TSType"],visitor:["typeAnnotation"],fields:{operator:(0,n.validate)((0,n.assertValueType)("string")),typeAnnotation:(0,n.validateType)("TSType")}}),a("TSIndexedAccessType",{aliases:["TSType"],visitor:["objectType","indexType"],fields:{objectType:(0,n.validateType)("TSType"),indexType:(0,n.validateType)("TSType")}}),a("TSMappedType",{aliases:["TSType"],visitor:["typeParameter","nameType","typeAnnotation"],builder:["typeParameter","typeAnnotation","nameType"],fields:Object.assign({},{typeParameter:(0,n.validateType)("TSTypeParameter")},{readonly:(0,n.validateOptional)((0,n.assertOneOf)(!0,!1,"+","-")),optional:(0,n.validateOptional)((0,n.assertOneOf)(!0,!1,"+","-")),typeAnnotation:(0,n.validateOptionalType)("TSType"),nameType:(0,n.validateOptionalType)("TSType")})}),a("TSTemplateLiteralType",{aliases:["TSType","TSBaseType"],visitor:["quasis","types"],fields:{quasis:(0,n.validateArrayOfType)("TemplateElement"),types:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("TSType")),(function(e,t,r){if(e.quasis.length!==r.length+1)throw new TypeError(`Number of ${e.type} quasis should be exactly one more than the number of types.\nExpected ${r.length+1} quasis but got ${e.quasis.length}`)}))}}}),a("TSLiteralType",{aliases:["TSType","TSBaseType"],visitor:["literal"],fields:{literal:{validate:function(){const e=(0,n.assertNodeType)("NumericLiteral","BigIntLiteral"),t=(0,n.assertOneOf)("-"),r=(0,n.assertNodeType)("NumericLiteral","StringLiteral","BooleanLiteral","BigIntLiteral","TemplateLiteral");function s(n,s,a){(0,i.default)("UnaryExpression",a)?(t(a,"operator",a.operator),e(a,"argument",a.argument)):r(n,s,a)}return s.oneOfNodeTypes=["NumericLiteral","StringLiteral","BooleanLiteral","BigIntLiteral","TemplateLiteral","UnaryExpression"],s}()}}}),a("TSExpressionWithTypeArguments",{aliases:["TSType"],visitor:["expression","typeParameters"],fields:{expression:(0,n.validateType)("TSEntityName"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterInstantiation")}}),a("TSInterfaceDeclaration",{aliases:["Statement","Declaration"],visitor:["id","typeParameters","extends","body"],fields:{declare:(0,n.validateOptional)(o),id:(0,n.validateType)("Identifier"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterDeclaration"),extends:(0,n.validateOptional)((0,n.arrayOfType)("TSExpressionWithTypeArguments")),body:(0,n.validateType)("TSInterfaceBody")}}),a("TSInterfaceBody",{visitor:["body"],fields:{body:(0,n.validateArrayOfType)("TSTypeElement")}}),a("TSTypeAliasDeclaration",{aliases:["Statement","Declaration"],visitor:["id","typeParameters","typeAnnotation"],fields:{declare:(0,n.validateOptional)(o),id:(0,n.validateType)("Identifier"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterDeclaration"),typeAnnotation:(0,n.validateType)("TSType")}}),a("TSInstantiationExpression",{aliases:["Expression"],visitor:["expression","typeParameters"],fields:{expression:(0,n.validateType)("Expression"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterInstantiation")}});const m={aliases:["Expression","LVal","PatternLike"],visitor:["expression","typeAnnotation"],fields:{expression:(0,n.validateType)("Expression"),typeAnnotation:(0,n.validateType)("TSType")}};a("TSAsExpression",m),a("TSSatisfiesExpression",m),a("TSTypeAssertion",{aliases:["Expression","LVal","PatternLike"],visitor:["typeAnnotation","expression"],fields:{typeAnnotation:(0,n.validateType)("TSType"),expression:(0,n.validateType)("Expression")}}),a("TSEnumBody",{visitor:["members"],fields:{members:(0,n.validateArrayOfType)("TSEnumMember")}}),a("TSEnumDeclaration",{aliases:["Statement","Declaration"],visitor:["id","members"],fields:{declare:(0,n.validateOptional)(o),const:(0,n.validateOptional)(o),id:(0,n.validateType)("Identifier"),members:(0,n.validateArrayOfType)("TSEnumMember"),initializer:(0,n.validateOptionalType)("Expression"),body:(0,n.validateOptionalType)("TSEnumBody")}}),a("TSEnumMember",{visitor:["id","initializer"],fields:{id:(0,n.validateType)("Identifier","StringLiteral"),initializer:(0,n.validateOptionalType)("Expression")}}),a("TSModuleDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:Object.assign({kind:{validate:(0,n.assertOneOf)("global","module","namespace")},declare:(0,n.validateOptional)(o)},{global:(0,n.validateOptional)(o)},{id:(0,n.validateType)("Identifier","StringLiteral"),body:(0,n.validateType)("TSModuleBlock","TSModuleDeclaration")})}),a("TSModuleBlock",{aliases:["Scopable","Block","BlockParent","FunctionParent"],visitor:["body"],fields:{body:(0,n.validateArrayOfType)("Statement")}}),a("TSImportType",{aliases:["TSType"],builder:["argument","qualifier","typeParameters"],visitor:["argument","options","qualifier","typeParameters"],fields:{argument:(0,n.validateType)("StringLiteral"),qualifier:(0,n.validateOptionalType)("TSEntityName"),typeParameters:(0,n.validateOptionalType)("TSTypeParameterInstantiation"),options:{validate:(0,n.assertNodeType)("Expression"),optional:!0}}}),a("TSImportEqualsDeclaration",{aliases:["Statement","Declaration"],visitor:["id","moduleReference"],fields:Object.assign({},{isExport:(0,n.validate)(o)},{id:(0,n.validateType)("Identifier"),moduleReference:(0,n.validateType)("TSEntityName","TSExternalModuleReference"),importKind:{validate:(0,n.assertOneOf)("type","value"),optional:!0}})}),a("TSExternalModuleReference",{visitor:["expression"],fields:{expression:(0,n.validateType)("StringLiteral")}}),a("TSNonNullExpression",{aliases:["Expression","LVal","PatternLike"],visitor:["expression"],fields:{expression:(0,n.validateType)("Expression")}}),a("TSExportAssignment",{aliases:["Statement"],visitor:["expression"],fields:{expression:(0,n.validateType)("Expression")}}),a("TSNamespaceExportDeclaration",{aliases:["Statement"],visitor:["id"],fields:{id:(0,n.validateType)("Identifier")}}),a("TSTypeAnnotation",{visitor:["typeAnnotation"],fields:{typeAnnotation:{validate:(0,n.assertNodeType)("TSType")}}}),a("TSTypeParameterInstantiation",{visitor:["params"],fields:{params:(0,n.validateArrayOfType)("TSType")}}),a("TSTypeParameterDeclaration",{visitor:["params"],fields:{params:(0,n.validateArrayOfType)("TSTypeParameter")}}),a("TSTypeParameter",{builder:["constraint","default","name"],visitor:["constraint","default"],fields:{name:{validate:(0,n.assertValueType)("string")},in:{validate:(0,n.assertValueType)("boolean"),optional:!0},out:{validate:(0,n.assertValueType)("boolean"),optional:!0},const:{validate:(0,n.assertValueType)("boolean"),optional:!0},constraint:{validate:(0,n.assertNodeType)("TSType"),optional:!0},default:{validate:(0,n.assertNodeType)("TSType"),optional:!0}}})},6109:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._getKey=g,t._getPattern=b,t.get=function(e,t=!0){!0===t&&(t=this.context);const r=e.split(".");return 1===r.length?g.call(this,e,t):b.call(this,r,t)},t.getAllNextSiblings=function(){let e=this.key,t=this.getSibling(++e);const r=[];for(;t.node;)r.push(t),t=this.getSibling(++e);return r},t.getAllPrevSiblings=function(){let e=this.key,t=this.getSibling(--e);const r=[];for(;t.node;)r.push(t),t=this.getSibling(--e);return r},t.getAssignmentIdentifiers=function(){return i(this.node)},t.getBindingIdentifierPaths=function(e=!1,t=!1){const r=[this],n=Object.create(null);for(;r.length;){const s=r.shift();if(!s)continue;if(!s.node)continue;const i=a.keys[s.node.type];if(s.isIdentifier())e?(n[s.node.name]=n[s.node.name]||[]).push(s):n[s.node.name]=s;else if(s.isExportDeclaration()){const e=s.get("declaration");e.isDeclaration()&&r.push(e)}else{if(t){if(s.isFunctionDeclaration()){r.push(s.get("id"));continue}if(s.isFunctionExpression())continue}if(i)for(let e=0;e<i.length;e++){const t=i[e],n=s.get(t);Array.isArray(n)?r.push(...n):n.node&&r.push(n)}}}return n},t.getBindingIdentifiers=function(e){return a(this.node,e)},t.getCompletionRecords=function(){return y(this,{canHaveBreak:!1,shouldPopulateBreak:!1,inCaseClause:!1}).map((e=>e.path))},t.getNextSibling=function(){return this.getSibling(this.key+1)},t.getOpposite=function(){return"left"===this.key?this.getSibling("right"):"right"===this.key?this.getSibling("left"):null},t.getOuterBindingIdentifierPaths=function(e=!1){return this.getBindingIdentifierPaths(e,!0)},t.getOuterBindingIdentifiers=function(e){return o(this.node,e)},t.getPrevSibling=function(){return this.getSibling(this.key-1)},t.getSibling=function(e){return n.default.get({parentPath:this.parentPath,parent:this.parent,container:this.container,listKey:this.listKey,key:e}).setContext(this.context)};var n=r(9709),s=r(2352);const{getAssignmentIdentifiers:i,getBindingIdentifiers:a,getOuterBindingIdentifiers:o,numericLiteral:l,unaryExpression:c}=s,p=0,u=1;function d(e,t,r){return e&&t.push(...y(e,r)),t}function f(e){e.forEach((e=>{e.type=u}))}function h(e,t){e.forEach((e=>{e.path.isBreakStatement({label:null})&&(t?e.path.replaceWith(c("void",l(0))):e.path.remove())}))}function m(e,t){const r=[];if(t.canHaveBreak){let n=[];for(let s=0;s<e.length;s++){const i=e[s],a=Object.assign({},t,{inCaseClause:!1});i.isBlockStatement()&&(t.inCaseClause||t.shouldPopulateBreak)?a.shouldPopulateBreak=!0:a.shouldPopulateBreak=!1;const o=y(i,a);if(o.length>0&&o.every((e=>e.type===u))){n.length>0&&o.every((e=>e.path.isBreakStatement({label:null})))?(f(n),r.push(...n),n.some((e=>e.path.isDeclaration()))&&(r.push(...o),h(o,!0)),h(o,!1)):(r.push(...o),t.shouldPopulateBreak||h(o,!0));break}if(s===e.length-1)r.push(...o);else{n=[];for(let e=0;e<o.length;e++){const t=o[e];t.type===u&&r.push(t),t.type===p&&n.push(t)}}}}else if(e.length)for(let n=e.length-1;n>=0;n--){const s=y(e[n],t);if(s.length>1||1===s.length&&!s[0].path.isVariableDeclaration()){r.push(...s);break}}return r}function y(e,t){let r=[];if(e.isIfStatement())r=d(e.get("consequent"),r,t),r=d(e.get("alternate"),r,t);else{if(e.isDoExpression()||e.isFor()||e.isWhile()||e.isLabeledStatement())return d(e.get("body"),r,t);if(e.isProgram()||e.isBlockStatement())return m(e.get("body"),t);if(e.isFunction())return y(e.get("body"),t);if(e.isTryStatement())r=d(e.get("block"),r,t),r=d(e.get("handler"),r,t);else{if(e.isCatchClause())return d(e.get("body"),r,t);if(e.isSwitchStatement())return function(e,t,r){let n=[];for(let s=0;s<e.length;s++){const i=y(e[s],r),a=[],o=[];for(const e of i)e.type===p&&a.push(e),e.type===u&&o.push(e);a.length&&(n=a),t.push(...o)}return t.push(...n),t}(e.get("cases"),r,t);if(e.isSwitchCase())return m(e.get("consequent"),{canHaveBreak:!0,shouldPopulateBreak:!1,inCaseClause:!0});e.isBreakStatement()?r.push(function(e){return{type:u,path:e}}(e)):r.push(function(e){return{type:p,path:e}}(e))}}return r}function g(e,t){const r=this.node,s=r[e];return Array.isArray(s)?s.map(((i,a)=>n.default.get({listKey:e,parentPath:this,parent:r,container:s,key:a}).setContext(t))):n.default.get({parentPath:this,parent:r,container:r,key:e}).setContext(t)}function b(e,t){let r=this;for(const n of e)r="."===n?r.parentPath:Array.isArray(r)?r[n]:r.get(n,t);return r}},6133:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(8960);t.default=function(e){if((0,n.isExpressionStatement)(e)&&(e=e.expression),(0,n.isExpression)(e))return e;if((0,n.isClass)(e)?e.type="ClassExpression":(0,n.isFunction)(e)&&(e.type="FunctionExpression"),!(0,n.isExpression)(e))throw new Error(`cannot turn ${e.type} to an expression`);return e}},6140:(e,t,r)=>{"use strict";function n(){const e=r(7975);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.createConfigItem=function*(e,{dirname:t=".",type:r}={}){return i(yield*(0,s.createDescriptor)(e,n().resolve(t),{type:r,alias:"programmatic item"}))},t.createItemFromDescriptor=i,t.getItemDescriptor=function(e){if(null!=e&&e[a])return e._descriptor};var s=r(9990);function i(e){return new o(e)}const a=Symbol.for("@babel/core@7 - ConfigItem");class o{constructor(e){this._descriptor=void 0,this[a]=!0,this.value=void 0,this.options=void 0,this.dirname=void 0,this.name=void 0,this.file=void 0,this._descriptor=e,Object.defineProperty(this,"_descriptor",{enumerable:!1}),Object.defineProperty(this,a,{enumerable:!1}),this.value=this._descriptor.value,this.options=this._descriptor.options,this.dirname=this._descriptor.dirname,this.name=this._descriptor.name,this.file=this._descriptor.file?{request:this._descriptor.file.request,resolved:this._descriptor.file.resolved}:void 0,Object.freeze(this)}}Object.freeze(o.prototype)},6184:(e,t,r)=>{"use strict";var n=r(7596);const s=(0,n.defineAliasedType)("JSX");s("JSXAttribute",{visitor:["name","value"],aliases:["Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXNamespacedName")},value:{optional:!0,validate:(0,n.assertNodeType)("JSXElement","JSXFragment","StringLiteral","JSXExpressionContainer")}}}),s("JSXClosingElement",{visitor:["name"],aliases:["Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")}}}),s("JSXElement",{builder:["openingElement","closingElement","children","selfClosing"],visitor:["openingElement","children","closingElement"],aliases:["Immutable","Expression"],fields:Object.assign({openingElement:{validate:(0,n.assertNodeType)("JSXOpeningElement")},closingElement:{optional:!0,validate:(0,n.assertNodeType)("JSXClosingElement")},children:(0,n.validateArrayOfType)("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")},{selfClosing:{validate:(0,n.assertValueType)("boolean"),optional:!0}})}),s("JSXEmptyExpression",{}),s("JSXExpressionContainer",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:(0,n.assertNodeType)("Expression","JSXEmptyExpression")}}}),s("JSXSpreadChild",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),s("JSXIdentifier",{builder:["name"],fields:{name:{validate:(0,n.assertValueType)("string")}}}),s("JSXMemberExpression",{visitor:["object","property"],fields:{object:{validate:(0,n.assertNodeType)("JSXMemberExpression","JSXIdentifier")},property:{validate:(0,n.assertNodeType)("JSXIdentifier")}}}),s("JSXNamespacedName",{visitor:["namespace","name"],fields:{namespace:{validate:(0,n.assertNodeType)("JSXIdentifier")},name:{validate:(0,n.assertNodeType)("JSXIdentifier")}}}),s("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","typeParameters","typeArguments","attributes"],aliases:["Immutable"],fields:Object.assign({name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")},selfClosing:{default:!1},attributes:(0,n.validateArrayOfType)("JSXAttribute","JSXSpreadAttribute"),typeArguments:{validate:(0,n.assertNodeType)("TypeParameterInstantiation"),optional:!0}},{typeParameters:{validate:(0,n.assertNodeType)("TSTypeParameterInstantiation"),optional:!0}})}),s("JSXSpreadAttribute",{visitor:["argument"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),s("JSXText",{aliases:["Immutable"],builder:["value"],fields:{value:{validate:(0,n.assertValueType)("string")}}}),s("JSXFragment",{builder:["openingFragment","closingFragment","children"],visitor:["openingFragment","children","closingFragment"],aliases:["Immutable","Expression"],fields:{openingFragment:{validate:(0,n.assertNodeType)("JSXOpeningFragment")},closingFragment:{validate:(0,n.assertNodeType)("JSXClosingFragment")},children:(0,n.validateArrayOfType)("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")}}),s("JSXOpeningFragment",{aliases:["Immutable"]}),s("JSXClosingFragment",{aliases:["Immutable"]})},6188:e=>{"use strict";e.exports=Math.max},6211:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,s){return(0,n.default)(e,t,[{type:s?"CommentLine":"CommentBlock",value:r}])};var n=r(2598)},6219:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if((0,s.isSuper)(e.object))throw new Error("Cannot prepend node to super property access (`super.foo`).");return e.object=(0,n.memberExpression)(t,e.object),e};var n=r(8079),s=r(2352)},6271:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClassAccessorProperty=function(e){var t;this.printJoin(e.decorators);const r=null==(t=e.key.loc)||null==(t=t.end)?void 0:t.line;r&&this.catchUp(r),this.tsPrintClassMemberModifiers(e),this.word("accessor",!0),this.space(),e.computed?(this.tokenChar(91),this.print(e.key),this.tokenChar(93)):(this._variance(e),this.print(e.key)),e.optional&&this.tokenChar(63),e.definite&&this.tokenChar(33),this.print(e.typeAnnotation),e.value&&(this.space(),this.tokenChar(61),this.space(),this.print(e.value)),this.semicolon()},t.ClassBody=function(e){if(this.tokenChar(123),0===e.body.length)this.tokenChar(125);else{this.newline();const t=function(e,t){if(!e.tokenMap||null==t.start||null==t.end)return null;const r=e.tokenMap.getIndexes(t);if(!r)return null;let n=1,s=0,i=0;const a=()=>{for(;i<t.body.length&&null==t.body[i].start;)i++};return a(),o=>{i<=o&&(i=o+1,a());const l=i===t.body.length?t.end:t.body[i].start;let c;for(;n<r.length&&e.tokenMap.matchesOriginal(c=e._tokens[r[n]],";")&&c.start<l;)e.token(";",void 0,s++),n++}}(this,e);null==t||t(-1);const r=this.enterDelimited();this.printJoin(e.body,!0,!0,t,!0),r(),this.endsWith(10)||this.newline(),this.rightBrace(e)}},t.ClassExpression=t.ClassDeclaration=function(e,t){(s(t)||i(t))&&this._shouldPrintDecoratorsBeforeExport(t)||this.printJoin(e.decorators),e.declare&&(this.word("declare"),this.space()),e.abstract&&(this.word("abstract"),this.space()),this.word("class"),e.id&&(this.space(),this.print(e.id)),this.print(e.typeParameters),e.superClass&&(this.space(),this.word("extends"),this.space(),this.print(e.superClass),this.print(e.superTypeParameters)),e.implements&&(this.space(),this.word("implements"),this.space(),this.printList(e.implements)),this.space(),this.print(e.body)},t.ClassMethod=function(e){this._classMethodHead(e),this.space(),this.print(e.body)},t.ClassPrivateMethod=function(e){this._classMethodHead(e),this.space(),this.print(e.body)},t.ClassPrivateProperty=function(e){this.printJoin(e.decorators),this.tsPrintClassMemberModifiers(e),this.print(e.key),e.optional&&this.tokenChar(63),e.definite&&this.tokenChar(33),this.print(e.typeAnnotation),e.value&&(this.space(),this.tokenChar(61),this.space(),this.print(e.value)),this.semicolon()},t.ClassProperty=function(e){if(this.printJoin(e.decorators),!e.static&&!this.format.preserveFormat){var t;const r=null==(t=e.key.loc)||null==(t=t.end)?void 0:t.line;r&&this.catchUp(r)}this.tsPrintClassMemberModifiers(e),e.computed?(this.tokenChar(91),this.print(e.key),this.tokenChar(93)):(this._variance(e),this.print(e.key)),e.optional&&this.tokenChar(63),e.definite&&this.tokenChar(33),this.print(e.typeAnnotation),e.value&&(this.space(),this.tokenChar(61),this.space(),this.print(e.value)),this.semicolon()},t.StaticBlock=function(e){this.word("static"),this.space(),this.tokenChar(123),0===e.body.length?this.tokenChar(125):(this.newline(),this.printSequence(e.body,!0),this.rightBrace(e))},t._classMethodHead=function(e){if(this.printJoin(e.decorators),!this.format.preserveFormat){var t;const r=null==(t=e.key.loc)||null==(t=t.end)?void 0:t.line;r&&this.catchUp(r)}this.tsPrintClassMemberModifiers(e),this._methodHead(e)};var n=r(2352);const{isExportDefaultDeclaration:s,isExportNamedDeclaration:i}=n},6299:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getHighestUnreleased=function(e,t,r){return c(e,t,r)===e?t:e},t.getLowestImplementedVersion=function(e,t){const r=e[t];return r||"android"!==t?r:e.chrome},t.getLowestUnreleased=c,t.isUnreleasedVersion=function(e,t){const r=i.unreleasedLabels[t];return!!r&&r===e.toString().toLowerCase()},t.semverMin=l,t.semverify=function(e){if("string"==typeof e&&n.valid(e))return e;o.invariant("number"==typeof e||"string"==typeof e&&a.test(e),`'${e}' is not a valid version`),e=e.toString();let t=0,r=0;for(;(t=e.indexOf(".",t+1))>0;)r++;return e+".0".repeat(2-r)};var n=r(5345),s=r(130),i=r(1884);const a=/^(?:\d+|\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?))$/,o=new s.OptionValidator("@babel/helper-compilation-targets");function l(e,t){return e&&n.lt(e,t)?e:t}function c(e,t,r){const n=i.unreleasedLabels[r];return e===n?t:t===n?e:l(e,t)}},6319:e=>{var t=/^\s+and\s+(.*)/i,r=/^(?:,\s*|\s+or\s+)(.*)/i;function n(e){return Array.isArray(e)?e.reduce((function(e,t){return e.concat(n(t))}),[]):[e]}function s(e,t){var r={query:t};for(var n in 0===t.indexOf("not ")&&(r.not=!0,t=t.slice(4)),e){var s=e[n],i=t.match(s.regexp);if(i){r.type=n;for(var a=0;a<s.matches.length;a++)r[s.matches[a]]=i[a+1];return r}}return r.type="unknown",r}function i(e,n,i){var a;return function(e,t){for(var r=e.length,n=1;n<=r;n++)if(t(e.substr(-n,n),n,r))return e.slice(0,-n);return""}(n,(function(n,o,l){return t.test(n)?((a=s(e,n.match(t)[1])).compose="and",i.unshift(a),!0):r.test(n)?((a=s(e,n.match(r)[1])).compose="or",i.unshift(a),!0):o===l&&((a=s(e,n.trim())).compose="or",i.unshift(a),!0)}))}e.exports=function(e,t){return Array.isArray(t)||(t=[t]),n(t.map((function(t){var r=[];do{t=i(e,t,r)}while(t);return r})))}},6416:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_EXTENSIONS=void 0,Object.defineProperty(t,"File",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"buildExternalHelpers",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(t,"createConfigItem",{enumerable:!0,get:function(){return u.createConfigItem}}),Object.defineProperty(t,"createConfigItemAsync",{enumerable:!0,get:function(){return u.createConfigItemAsync}}),Object.defineProperty(t,"createConfigItemSync",{enumerable:!0,get:function(){return u.createConfigItemSync}}),Object.defineProperty(t,"getEnv",{enumerable:!0,get:function(){return a.getEnv}}),Object.defineProperty(t,"loadOptions",{enumerable:!0,get:function(){return u.loadOptions}}),Object.defineProperty(t,"loadOptionsAsync",{enumerable:!0,get:function(){return u.loadOptionsAsync}}),Object.defineProperty(t,"loadOptionsSync",{enumerable:!0,get:function(){return u.loadOptionsSync}}),Object.defineProperty(t,"loadPartialConfig",{enumerable:!0,get:function(){return u.loadPartialConfig}}),Object.defineProperty(t,"loadPartialConfigAsync",{enumerable:!0,get:function(){return u.loadPartialConfigAsync}}),Object.defineProperty(t,"loadPartialConfigSync",{enumerable:!0,get:function(){return u.loadPartialConfigSync}}),Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return m.parse}}),Object.defineProperty(t,"parseAsync",{enumerable:!0,get:function(){return m.parseAsync}}),Object.defineProperty(t,"parseSync",{enumerable:!0,get:function(){return m.parseSync}}),t.resolvePreset=t.resolvePlugin=void 0,Object.defineProperty(t,"template",{enumerable:!0,get:function(){return p().default}}),Object.defineProperty(t,"tokTypes",{enumerable:!0,get:function(){return l().tokTypes}}),Object.defineProperty(t,"transform",{enumerable:!0,get:function(){return d.transform}}),Object.defineProperty(t,"transformAsync",{enumerable:!0,get:function(){return d.transformAsync}}),Object.defineProperty(t,"transformFile",{enumerable:!0,get:function(){return f.transformFile}}),Object.defineProperty(t,"transformFileAsync",{enumerable:!0,get:function(){return f.transformFileAsync}}),Object.defineProperty(t,"transformFileSync",{enumerable:!0,get:function(){return f.transformFileSync}}),Object.defineProperty(t,"transformFromAst",{enumerable:!0,get:function(){return h.transformFromAst}}),Object.defineProperty(t,"transformFromAstAsync",{enumerable:!0,get:function(){return h.transformFromAstAsync}}),Object.defineProperty(t,"transformFromAstSync",{enumerable:!0,get:function(){return h.transformFromAstSync}}),Object.defineProperty(t,"transformSync",{enumerable:!0,get:function(){return d.transformSync}}),Object.defineProperty(t,"traverse",{enumerable:!0,get:function(){return c().default}}),t.version=t.types=void 0;var n=r(4797),s=r(322),i=r(682),a=r(324);function o(){const e=r(2352);return o=function(){return e},e}function l(){const e=r(2172);return l=function(){return e},e}function c(){const e=r(5781);return c=function(){return e},e}function p(){const e=r(2485);return p=function(){return e},e}Object.defineProperty(t,"types",{enumerable:!0,get:function(){return o()}});var u=r(6955),d=r(5104),f=r(786),h=r(8441),m=r(5283);t.version="7.26.9",t.resolvePlugin=(e,t)=>i.resolvePlugin(e,t,!1).filepath,t.resolvePreset=(e,t)=>i.resolvePreset(e,t,!1).filepath,t.DEFAULT_EXTENSIONS=Object.freeze([".js",".jsx",".es6",".es",".mjs",".cjs"]),t.OptionManager=class{init(e){return(0,u.loadOptionsSync)(e)}},t.Plugin=function(e){throw new Error(`The (${e}) Babel 5 plugin is being run with an unsupported Babel version.`)}},6438:e=>{e.exports={0:"22",1:"23",2:"24",3:"25",4:"26",5:"27",6:"115",7:"116",8:"117",9:"118",A:"10",B:"11",C:"12",D:"132",E:"7",F:"8",G:"9",H:"15",I:"80",J:"4",K:"6",L:"13",M:"14",N:"16",O:"17",P:"18",Q:"79",R:"81",S:"83",T:"84",U:"85",V:"86",W:"87",X:"88",Y:"89",Z:"90",a:"91",b:"92",c:"93",d:"94",e:"95",f:"96",g:"97",h:"98",i:"99",j:"100",k:"101",l:"102",m:"103",n:"104",o:"105",p:"106",q:"107",r:"108",s:"109",t:"110",u:"111",v:"112",w:"113",x:"114",y:"20",z:"21",AB:"119",BB:"120",CB:"121",DB:"122",EB:"123",FB:"124",GB:"125",HB:"126",IB:"127",JB:"128",KB:"129",LB:"130",MB:"131",NB:"5",OB:"19",PB:"28",QB:"29",RB:"30",SB:"31",TB:"32",UB:"33",VB:"34",WB:"35",XB:"36",YB:"37",ZB:"38",aB:"39",bB:"40",cB:"41",dB:"42",eB:"43",fB:"44",gB:"45",hB:"46",iB:"47",jB:"48",kB:"49",lB:"50",mB:"51",nB:"52",oB:"53",pB:"54",qB:"55",rB:"56",sB:"57",tB:"58",uB:"60",vB:"62",wB:"63",xB:"64",yB:"65",zB:"66","0B":"67","1B":"68","2B":"69","3B":"70","4B":"71","5B":"72","6B":"73","7B":"74","8B":"75","9B":"76",AC:"77",BC:"78",CC:"11.1",DC:"12.1",EC:"15.5",FC:"16.0",GC:"17.0",HC:"18.0",IC:"3",JC:"59",KC:"61",LC:"82",MC:"133",NC:"134",OC:"135",PC:"136",QC:"3.2",RC:"10.1",SC:"15.2-15.3",TC:"15.4",UC:"16.1",VC:"16.2",WC:"16.3",XC:"16.4",YC:"16.5",ZC:"17.1",aC:"17.2",bC:"17.3",cC:"17.4",dC:"17.5",eC:"18.1",fC:"18.2",gC:"18.3",hC:"18.4",iC:"11.5",jC:"4.2-4.3",kC:"5.5",lC:"2",mC:"137",nC:"138",oC:"3.5",pC:"3.6",qC:"3.1",rC:"5.1",sC:"6.1",tC:"7.1",uC:"9.1",vC:"13.1",wC:"14.1",xC:"15.1",yC:"15.6",zC:"16.6","0C":"17.6","1C":"TP","2C":"9.5-9.6","3C":"10.0-10.1","4C":"10.5","5C":"10.6","6C":"11.6","7C":"4.0-4.1","8C":"5.0-5.1","9C":"6.0-6.1",AD:"7.0-7.1",BD:"8.1-8.4",CD:"9.0-9.2",DD:"9.3",ED:"10.0-10.2",FD:"10.3",GD:"11.0-11.2",HD:"11.3-11.4",ID:"12.0-12.1",JD:"12.2-12.5",KD:"13.0-13.1",LD:"13.2",MD:"13.3",ND:"13.4-13.7",OD:"14.0-14.4",PD:"14.5-14.8",QD:"15.0-15.1",RD:"15.6-15.8",SD:"16.6-16.7",TD:"17.6-17.7",UD:"all",VD:"2.1",WD:"2.2",XD:"2.3",YD:"4.1",ZD:"4.4",aD:"4.4.3-4.4.4",bD:"5.0-5.4",cD:"6.2-6.4",dD:"7.2-7.4",eD:"8.2",fD:"9.2",gD:"11.1-11.2",hD:"12.0",iD:"13.0",jD:"14.0",kD:"15.0",lD:"19.0",mD:"14.9",nD:"13.52",oD:"2.5",pD:"3.0-3.1"}},6481:e=>{e.exports={A:{A:{K:0,E:0,F:0,G:.033801,A:0,B:.371811,kC:0},B:"ms",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","kC","K","E","F","G","A","B","","",""],E:"IE",F:{kC:962323200,K:998870400,E:1161129600,F:1237420800,G:1300060800,A:1346716800,B:1381968e3}},B:{A:{6:.003558,7:0,8:.003558,9:.003558,C:0,L:0,M:0,H:0,N:0,O:.003558,P:.117414,Q:0,I:0,R:0,S:0,T:0,U:0,V:0,W:0,X:0,Y:0,Z:0,a:0,b:.010674,c:0,d:0,e:0,f:0,g:0,h:0,i:0,j:0,k:0,l:0,m:0,n:0,o:0,p:0,q:0,r:.003558,s:.049812,t:0,u:.003558,v:.007116,w:.007116,x:.010674,AB:.003558,BB:.021348,CB:.010674,DB:.014232,EB:.007116,FB:.010674,GB:.010674,HB:.021348,IB:.021348,JB:.01779,KB:.021348,LB:.067602,MB:2.88198,D:1.62245},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","C","L","M","H","N","O","P","Q","I","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","6","7","8","9","AB","BB","CB","DB","EB","FB","GB","HB","IB","JB","KB","LB","MB","D","","",""],E:"Edge",F:{6:1689897600,7:1692576e3,8:1694649600,9:1697155200,C:1438128e3,L:1447286400,M:1470096e3,H:1491868800,N:1508198400,O:1525046400,P:1542067200,Q:1579046400,I:1581033600,R:1586736e3,S:1590019200,T:1594857600,U:1598486400,V:1602201600,W:1605830400,X:161136e4,Y:1614816e3,Z:1618358400,a:1622073600,b:1626912e3,c:1630627200,d:1632441600,e:1634774400,f:1637539200,g:1641427200,h:1643932800,i:1646265600,j:1649635200,k:1651190400,l:1653955200,m:1655942400,n:1659657600,o:1661990400,p:1664755200,q:1666915200,r:1670198400,s:1673481600,t:1675900800,u:1678665600,v:1680825600,w:1683158400,x:1685664e3,AB:1698969600,BB:1701993600,CB:1706227200,DB:1708732800,EB:1711152e3,FB:1713398400,GB:1715990400,HB:1718841600,IB:1721865600,JB:1724371200,KB:1726704e3,LB:1729123200,MB:1731542400,D:1737417600},D:{C:"ms",L:"ms",M:"ms",H:"ms",N:"ms",O:"ms",P:"ms"}},C:{A:{0:0,1:0,2:0,3:0,4:0,5:0,6:.234828,7:0,8:0,9:.085392,lC:0,IC:0,J:0,NB:0,K:0,E:0,F:0,G:0,A:0,B:.021348,C:0,L:0,M:0,H:0,N:0,O:0,P:0,OB:0,y:0,z:0,PB:0,QB:0,RB:0,SB:0,TB:0,UB:0,VB:0,WB:0,XB:0,YB:0,ZB:0,aB:0,bB:0,cB:0,dB:0,eB:.007116,fB:.003558,gB:0,hB:0,iB:.003558,jB:0,kB:0,lB:0,mB:0,nB:.028464,oB:0,pB:0,qB:.003558,rB:.014232,sB:0,tB:0,JC:.003558,uB:0,KC:0,vB:0,wB:0,xB:0,yB:0,zB:0,"0B":0,"1B":0,"2B":0,"3B":0,"4B":0,"5B":0,"6B":0,"7B":0,"8B":0,"9B":0,AC:0,BC:.010674,Q:0,I:0,R:0,LC:0,S:0,T:0,U:0,V:0,W:0,X:.003558,Y:0,Z:0,a:0,b:0,c:0,d:0,e:0,f:0,g:0,h:0,i:0,j:0,k:0,l:0,m:.007116,n:0,o:0,p:0,q:0,r:0,s:.003558,t:0,u:0,v:0,w:.007116,x:0,AB:0,BB:.003558,CB:.003558,DB:0,EB:0,FB:0,GB:.01779,HB:0,IB:.007116,JB:.078276,KB:.003558,LB:.007116,MB:.010674,D:.021348,MC:.49812,NC:1.02826,OC:.007116,PC:0,mC:0,nC:0,oC:0,pC:0},B:"moz",C:["lC","IC","oC","pC","J","NB","K","E","F","G","A","B","C","L","M","H","N","O","P","OB","y","z","0","1","2","3","4","5","PB","QB","RB","SB","TB","UB","VB","WB","XB","YB","ZB","aB","bB","cB","dB","eB","fB","gB","hB","iB","jB","kB","lB","mB","nB","oB","pB","qB","rB","sB","tB","JC","uB","KC","vB","wB","xB","yB","zB","0B","1B","2B","3B","4B","5B","6B","7B","8B","9B","AC","BC","Q","I","R","LC","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","6","7","8","9","AB","BB","CB","DB","EB","FB","GB","HB","IB","JB","KB","LB","MB","D","MC","NC","OC","PC","mC","nC"],E:"Firefox",F:{0:1368489600,1:1372118400,2:1375747200,3:1379376e3,4:1386633600,5:1391472e3,6:1688428800,7:1690848e3,8:1693267200,9:1695686400,lC:1161648e3,IC:1213660800,oC:124632e4,pC:1264032e3,J:1300752e3,NB:1308614400,K:1313452800,E:1317081600,F:1317081600,G:1320710400,A:1324339200,B:1327968e3,C:1331596800,L:1335225600,M:1338854400,H:1342483200,N:1346112e3,O:1349740800,P:1353628800,OB:1357603200,y:1361232e3,z:1364860800,PB:1395100800,QB:1398729600,RB:1402358400,SB:1405987200,TB:1409616e3,UB:1413244800,VB:1417392e3,WB:1421107200,XB:1424736e3,YB:1428278400,ZB:1431475200,aB:1435881600,bB:1439251200,cB:144288e4,dB:1446508800,eB:1450137600,fB:1453852800,gB:1457395200,hB:1461628800,iB:1465257600,jB:1470096e3,kB:1474329600,lB:1479168e3,mB:1485216e3,nB:1488844800,oB:149256e4,pB:1497312e3,qB:1502150400,rB:1506556800,sB:1510617600,tB:1516665600,JC:1520985600,uB:1525824e3,KC:1529971200,vB:1536105600,wB:1540252800,xB:1544486400,yB:154872e4,zB:1552953600,"0B":1558396800,"1B":1562630400,"2B":1567468800,"3B":1571788800,"4B":1575331200,"5B":1578355200,"6B":1581379200,"7B":1583798400,"8B":1586304e3,"9B":1588636800,AC:1591056e3,BC:1593475200,Q:1595894400,I:1598313600,R:1600732800,LC:1603152e3,S:1605571200,T:1607990400,U:1611619200,V:1614038400,W:1616457600,X:1618790400,Y:1622505600,Z:1626134400,a:1628553600,b:1630972800,c:1633392e3,d:1635811200,e:1638835200,f:1641859200,g:1644364800,h:1646697600,i:1649116800,j:1651536e3,k:1653955200,l:1656374400,m:1658793600,n:1661212800,o:1663632e3,p:1666051200,q:1668470400,r:1670889600,s:1673913600,t:1676332800,u:1678752e3,v:1681171200,w:1683590400,x:1686009600,AB:1698105600,BB:1700524800,CB:1702944e3,DB:1705968e3,EB:1708387200,FB:1710806400,GB:1713225600,HB:1715644800,IB:1718064e3,JB:1720483200,KB:1722902400,LB:1725321600,MB:1727740800,D:173016e4,MC:1732579200,NC:1736208e3,OC:1738627200,PC:null,mC:null,nC:null}},D:{A:{0:0,1:0,2:0,3:0,4:0,5:0,6:.024906,7:.110298,8:.067602,9:.056928,J:0,NB:0,K:0,E:0,F:0,G:0,A:0,B:0,C:0,L:0,M:0,H:0,N:0,O:0,P:0,OB:0,y:0,z:0,PB:0,QB:0,RB:0,SB:0,TB:0,UB:0,VB:0,WB:0,XB:0,YB:0,ZB:.007116,aB:0,bB:0,cB:0,dB:0,eB:0,fB:0,gB:.003558,hB:0,iB:.003558,jB:.014232,kB:.014232,lB:.024906,mB:0,nB:.007116,oB:.007116,pB:0,qB:0,rB:.010674,sB:0,tB:.007116,JC:0,uB:0,KC:.007116,vB:0,wB:0,xB:0,yB:0,zB:.021348,"0B":0,"1B":0,"2B":.007116,"3B":.010674,"4B":0,"5B":0,"6B":.007116,"7B":.007116,"8B":.003558,"9B":.003558,AC:.010674,BC:.010674,Q:.08895,I:.010674,R:.024906,S:.032022,T:0,U:.010674,V:.01779,W:.067602,X:.010674,Y:.007116,Z:.007116,a:.03558,b:.010674,c:.010674,d:.032022,e:.014232,f:.007116,g:.014232,h:.039138,i:.010674,j:.007116,k:.014232,l:.010674,m:.099624,n:.042696,o:.010674,p:.01779,q:.024906,r:.039138,s:1.04605,t:.021348,u:.028464,v:.039138,w:.145878,x:.07116,AB:.039138,BB:.056928,CB:.08895,DB:.074718,EB:.078276,FB:.138762,GB:.814782,HB:.295314,IB:.224154,JB:.156552,KB:.14232,LB:.384264,MB:12.7946,D:3.25201,MC:.014232,NC:.007116,OC:0,PC:0},B:"webkit",C:["","","","","","","","J","NB","K","E","F","G","A","B","C","L","M","H","N","O","P","OB","y","z","0","1","2","3","4","5","PB","QB","RB","SB","TB","UB","VB","WB","XB","YB","ZB","aB","bB","cB","dB","eB","fB","gB","hB","iB","jB","kB","lB","mB","nB","oB","pB","qB","rB","sB","tB","JC","uB","KC","vB","wB","xB","yB","zB","0B","1B","2B","3B","4B","5B","6B","7B","8B","9B","AC","BC","Q","I","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","6","7","8","9","AB","BB","CB","DB","EB","FB","GB","HB","IB","JB","KB","LB","MB","D","MC","NC","OC","PC"],E:"Chrome",F:{0:1343692800,1:1348531200,2:1352246400,3:1357862400,4:1361404800,5:1364428800,6:1689724800,7:1692057600,8:1694476800,9:1696896e3,J:1264377600,NB:1274745600,K:1283385600,E:1287619200,F:1291248e3,G:1296777600,A:1299542400,B:1303862400,C:1307404800,L:1312243200,M:1316131200,H:1316131200,N:1319500800,O:1323734400,P:1328659200,OB:1332892800,y:133704e4,z:1340668800,PB:1369094400,QB:1374105600,RB:1376956800,SB:1384214400,TB:1389657600,UB:1392940800,VB:1397001600,WB:1400544e3,XB:1405468800,YB:1409011200,ZB:141264e4,aB:1416268800,bB:1421798400,cB:1425513600,dB:1429401600,eB:143208e4,fB:1437523200,gB:1441152e3,hB:1444780800,iB:1449014400,jB:1453248e3,kB:1456963200,lB:1460592e3,mB:1464134400,nB:1469059200,oB:1472601600,pB:1476230400,qB:1480550400,rB:1485302400,sB:1489017600,tB:149256e4,JC:1496707200,uB:1500940800,KC:1504569600,vB:1508198400,wB:1512518400,xB:1516752e3,yB:1520294400,zB:1523923200,"0B":1527552e3,"1B":1532390400,"2B":1536019200,"3B":1539648e3,"4B":1543968e3,"5B":154872e4,"6B":1552348800,"7B":1555977600,"8B":1559606400,"9B":1564444800,AC:1568073600,BC:1571702400,Q:1575936e3,I:1580860800,R:1586304e3,S:1589846400,T:1594684800,U:1598313600,V:1601942400,W:1605571200,X:1611014400,Y:1614556800,Z:1618272e3,a:1621987200,b:1626739200,c:1630368e3,d:1632268800,e:1634601600,f:1637020800,g:1641340800,h:1643673600,i:1646092800,j:1648512e3,k:1650931200,l:1653350400,m:1655769600,n:1659398400,o:1661817600,p:1664236800,q:1666656e3,r:166968e4,s:1673308800,t:1675728e3,u:1678147200,v:1680566400,w:1682985600,x:1685404800,AB:1698710400,BB:1701993600,CB:1705968e3,DB:1708387200,EB:1710806400,FB:1713225600,GB:1715644800,HB:1718064e3,IB:1721174400,JB:1724112e3,KB:1726531200,LB:1728950400,MB:1731369600,D:1736812800,MC:1738627200,NC:null,OC:null,PC:null}},E:{A:{J:0,NB:0,K:0,E:0,F:0,G:0,A:0,B:0,C:0,L:.003558,M:.01779,H:.003558,qC:0,QC:0,rC:0,sC:0,tC:0,uC:0,RC:0,CC:.003558,DC:.007116,vC:.039138,wC:.05337,xC:.010674,SC:.007116,TC:.014232,EC:.01779,yC:.167226,FC:.024906,UC:.028464,VC:.021348,WC:.049812,XC:.01779,YC:.028464,zC:.224154,GC:.014232,ZC:.024906,aC:.024906,bC:.028464,cC:.064044,dC:.131646,"0C":.39138,HC:.067602,eC:.939312,fC:.416286,gC:.028464,hC:0,"1C":0},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","qC","QC","J","NB","rC","K","sC","E","tC","F","G","uC","A","RC","B","CC","C","DC","L","vC","M","wC","H","xC","SC","TC","EC","yC","FC","UC","VC","WC","XC","YC","zC","GC","ZC","aC","bC","cC","dC","0C","HC","eC","fC","gC","hC","1C",""],E:"Safari",F:{qC:1205798400,QC:1226534400,J:1244419200,NB:1275868800,rC:131112e4,K:1343174400,sC:13824e5,E:13824e5,tC:1410998400,F:1413417600,G:1443657600,uC:1458518400,A:1474329600,RC:1490572800,B:1505779200,CC:1522281600,C:1537142400,DC:1553472e3,L:1568851200,vC:1585008e3,M:1600214400,wC:1619395200,H:1632096e3,xC:1635292800,SC:1639353600,TC:1647216e3,EC:1652745600,yC:1658275200,FC:1662940800,UC:1666569600,VC:1670889600,WC:1674432e3,XC:1679875200,YC:1684368e3,zC:1690156800,GC:1695686400,ZC:1698192e3,aC:1702252800,bC:1705881600,cC:1709596800,dC:1715558400,"0C":1722211200,HC:1726444800,eC:1730073600,fC:1733875200,gC:1737936e3,hC:null,"1C":null}},F:{A:{0:0,1:0,2:0,3:0,4:0,5:0,G:0,B:0,C:0,H:0,N:0,O:0,P:0,OB:0,y:0,z:0,PB:0,QB:0,RB:0,SB:0,TB:0,UB:0,VB:0,WB:0,XB:0,YB:0,ZB:0,aB:0,bB:.003558,cB:0,dB:0,eB:0,fB:0,gB:0,hB:.014232,iB:0,jB:0,kB:0,lB:0,mB:0,nB:0,oB:0,pB:0,qB:0,rB:0,sB:0,tB:0,uB:0,vB:0,wB:0,xB:0,yB:0,zB:0,"0B":0,"1B":0,"2B":0,"3B":0,"4B":0,"5B":0,"6B":0,"7B":0,"8B":0,"9B":0,AC:0,BC:0,Q:0,I:0,R:0,LC:0,S:0,T:0,U:0,V:.032022,W:.010674,X:0,Y:0,Z:0,a:0,b:0,c:0,d:0,e:.032022,f:0,g:0,h:0,i:0,j:0,k:0,l:.010674,m:0,n:0,o:0,p:0,q:0,r:0,s:0,t:0,u:0,v:0,w:0,x:.313104,"2C":0,"3C":0,"4C":0,"5C":0,CC:0,iC:0,"6C":0,DC:0},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","G","2C","3C","4C","5C","B","CC","iC","6C","C","DC","H","N","O","P","OB","y","z","0","1","2","3","4","5","PB","QB","RB","SB","TB","UB","VB","WB","XB","YB","ZB","aB","bB","cB","dB","eB","fB","gB","hB","iB","jB","kB","lB","mB","nB","oB","pB","qB","rB","sB","tB","uB","vB","wB","xB","yB","zB","0B","1B","2B","3B","4B","5B","6B","7B","8B","9B","AC","BC","Q","I","R","LC","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","","",""],E:"Opera",F:{0:1401753600,1:1405987200,2:1409616e3,3:1413331200,4:1417132800,5:1422316800,G:1150761600,"2C":1223424e3,"3C":1251763200,"4C":1267488e3,"5C":1277942400,B:1292457600,CC:1302566400,iC:1309219200,"6C":1323129600,C:1323129600,DC:1352073600,H:1372723200,N:1377561600,O:1381104e3,P:1386288e3,OB:1390867200,y:1393891200,z:1399334400,PB:1425945600,QB:1430179200,RB:1433808e3,SB:1438646400,TB:1442448e3,UB:1445904e3,VB:1449100800,WB:1454371200,XB:1457308800,YB:146232e4,ZB:1465344e3,aB:1470096e3,bB:1474329600,cB:1477267200,dB:1481587200,eB:1486425600,fB:1490054400,gB:1494374400,hB:1498003200,iB:1502236800,jB:1506470400,kB:1510099200,lB:1515024e3,mB:1517961600,nB:1521676800,oB:1525910400,pB:1530144e3,qB:1534982400,rB:1537833600,sB:1543363200,tB:1548201600,uB:1554768e3,vB:1561593600,wB:1566259200,xB:1570406400,yB:1573689600,zB:1578441600,"0B":1583971200,"1B":1587513600,"2B":1592956800,"3B":1595894400,"4B":1600128e3,"5B":1603238400,"6B":161352e4,"7B":1612224e3,"8B":1616544e3,"9B":1619568e3,AC:1623715200,BC:1627948800,Q:1631577600,I:1633392e3,R:1635984e3,LC:1638403200,S:1642550400,T:1644969600,U:1647993600,V:1650412800,W:1652745600,X:1654646400,Y:1657152e3,Z:1660780800,a:1663113600,b:1668816e3,c:1668643200,d:1671062400,e:1675209600,f:1677024e3,g:1679529600,h:1681948800,i:1684195200,j:1687219200,k:1690329600,l:1692748800,m:1696204800,n:169992e4,o:169992e4,p:1702944e3,q:1707264e3,r:1710115200,s:1711497600,t:1716336e3,u:1719273600,v:1721088e3,w:1724284800,x:1727222400},D:{G:"o",B:"o",C:"o","2C":"o","3C":"o","4C":"o","5C":"o",CC:"o",iC:"o","6C":"o",DC:"o"}},G:{A:{F:0,QC:0,"7C":0,jC:.00293498,"8C":0,"9C":.00733744,AD:.00880493,BD:0,CD:.00293498,DD:.0220123,ED:.00440246,FD:.0322847,GD:.0924517,HD:.0102724,ID:.00586995,JD:.155554,KD:.00293498,LD:.0176099,MD:.00586995,ND:.0220123,OD:.143814,PD:.0689719,QD:.0352197,SC:.0366872,TC:.0425571,EC:.0498946,RD:.585528,FC:.0880493,UC:.192241,VC:.0983217,WC:.171696,XC:.0366872,YC:.0704394,SD:.713199,GC:.0454921,ZC:.0807118,aC:.063102,bC:.0895167,cC:.192241,dC:.463726,TD:1.59369,HC:.490141,eC:6.52592,fC:2.20123,gC:.190773,hC:0},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","QC","7C","jC","8C","9C","AD","F","BD","CD","DD","ED","FD","GD","HD","ID","JD","KD","LD","MD","ND","OD","PD","QD","SC","TC","EC","RD","FC","UC","VC","WC","XC","YC","SD","GC","ZC","aC","bC","cC","dC","TD","HC","eC","fC","gC","hC","",""],E:"Safari on iOS",F:{QC:1270252800,"7C":1283904e3,jC:1299628800,"8C":1331078400,"9C":1359331200,AD:1394409600,F:1410912e3,BD:1413763200,CD:1442361600,DD:1458518400,ED:1473724800,FD:1490572800,GD:1505779200,HD:1522281600,ID:1537142400,JD:1553472e3,KD:1568851200,LD:1572220800,MD:1580169600,ND:1585008e3,OD:1600214400,PD:1619395200,QD:1632096e3,SC:1639353600,TC:1647216e3,EC:1652659200,RD:1658275200,FC:1662940800,UC:1666569600,VC:1670889600,WC:1674432e3,XC:1679875200,YC:1684368e3,SD:1690156800,GC:1694995200,ZC:1698192e3,aC:1702252800,bC:1705881600,cC:1709596800,dC:1715558400,TD:1722211200,HC:1726444800,eC:1730073600,fC:1733875200,gC:1737936e3,hC:null}},H:{A:{UD:.04},B:"o",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","UD","","",""],E:"Opera Mini",F:{UD:1426464e3}},I:{A:{IC:0,J:0,D:.308567,VD:0,WD:0,XD:0,YD:309216e-10,jC:618432e-10,ZD:0,aD:371059e-9},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","VD","WD","XD","IC","J","YD","jC","ZD","aD","D","","",""],E:"Android Browser",F:{VD:1256515200,WD:1274313600,XD:1291593600,IC:1298332800,J:1318896e3,YD:1341792e3,jC:1374624e3,ZD:1386547200,aD:1401667200,D:1737676800}},J:{A:{E:0,A:0},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","E","A","","",""],E:"Blackberry Browser",F:{E:1325376e3,A:1359504e3}},K:{A:{A:0,B:0,C:0,I:1.03581,CC:0,iC:0,DC:0},B:"o",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","A","B","CC","iC","C","DC","I","","",""],E:"Opera Mobile",F:{A:1287100800,B:1300752e3,CC:1314835200,iC:1318291200,C:1330300800,DC:1349740800,I:1709769600},D:{I:"webkit"}},L:{A:{D:46.1904},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","D","","",""],E:"Chrome for Android",F:{D:1737676800}},M:{A:{D:.334984},B:"moz",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","D","","",""],E:"Firefox for Android",F:{D:173016e4}},N:{A:{A:0,B:0},B:"ms",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","A","B","","",""],E:"IE Mobile",F:{A:1340150400,B:1353456e3}},O:{A:{EC:.83746},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","EC","","",""],E:"UC Browser for Android",F:{EC:1710115200},D:{EC:"webkit"}},P:{A:{0:.0330772,1:.0330772,2:.0441029,3:.0441029,4:.110257,5:1.90745,J:.0661544,y:0,z:.0220515,bD:.0110257,cD:0,dD:.0110257,eD:0,fD:0,RC:0,gD:0,hD:0,iD:0,jD:0,kD:0,FC:0,GC:.0110257,HC:0,lD:0},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","J","bD","cD","dD","eD","fD","RC","gD","hD","iD","jD","kD","FC","GC","HC","lD","y","z","0","1","2","3","4","5","","",""],E:"Samsung Internet",F:{0:1689292800,1:1697587200,2:1711497600,3:1715126400,4:1717718400,5:1725667200,J:1461024e3,bD:1481846400,cD:1509408e3,dD:1528329600,eD:1546128e3,fD:1554163200,RC:1567900800,gD:1582588800,hD:1593475200,iD:1605657600,jD:1618531200,kD:1629072e3,FC:1640736e3,GC:1651708800,HC:1659657600,lD:1667260800,y:1677369600,z:1684454400}},Q:{A:{mD:.199702},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","mD","","",""],E:"QQ Browser",F:{mD:1710288e3}},R:{A:{nD:0},B:"webkit",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","nD","","",""],E:"Baidu Browser",F:{nD:1710201600}},S:{A:{oD:.019326,pD:0},B:"moz",C:["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","oD","pD","","",""],E:"KaiOS Browser",F:{oD:1527811200,pD:1631664e3}}}},6549:e=>{"use strict";e.exports=Object.getOwnPropertyDescriptor},6556:(e,t,r)=>{"use strict";var n=r(453),s=r(3126),i=s([n("%String.prototype.indexOf%")]);e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?s([r]):r}},6568:(e,t,r)=>{"use strict";function n(){const e=r(5781);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.run=function*(e,t,r){const u=yield*(0,o.default)(e.passes,(0,a.default)(e),t,r),d=u.opts;try{yield*function*(e,t){const r=yield*(0,p.isAsync)();for(const a of t){const t=[],o=[],l=[];for(const n of a.concat([(0,i.default)()])){const i=new s.default(e,n.key,n.options,r);t.push([n,i]),o.push(i),l.push(n.visitor)}for(const[r,n]of t)if(r.pre){const t=(0,p.maybeAsync)(r.pre,"You appear to be using an async plugin/preset, but Babel has been called synchronously");yield*t.call(n,e)}const c=n().default.visitors.merge(l,o,e.opts.wrapPluginVisitorMethod);(0,n().default)(e.ast,c,e.scope);for(const[r,n]of t)if(r.post){const t=(0,p.maybeAsync)(r.post,"You appear to be using an async plugin/preset, but Babel has been called synchronously");yield*t.call(n,e)}}}(u,e.passes)}catch(e){var f;throw e.message=`${null!=(f=d.filename)?f:"unknown file"}: ${e.message}`,e.code||(e.code="BABEL_TRANSFORM_ERROR"),e}let h,m;try{!1!==d.code&&({outputCode:h,outputMap:m}=(0,l.default)(e.passes,u))}catch(e){var y;throw e.message=`${null!=(y=d.filename)?y:"unknown file"}: ${e.message}`,e.code||(e.code="BABEL_GENERATE_ERROR"),e}return{metadata:u.metadata,options:d,ast:!0===d.ast?u.ast:null,code:void 0===h?null:h,map:void 0===m?null:m,sourceType:u.ast.program.sourceType,externalDependencies:(0,c.flattenToSet)(e.externalDependencies)}};var s=r(3823),i=r(3863),a=r(9618),o=r(3342),l=r(2120),c=r(947),p=r(3310)},6576:(e,t,r)=>{"use strict";var n=r(9394),s=r(8452);e.exports=function(){var e=n();return s(Object,{is:e},{is:function(){return Object.is!==e}}),e}},6578:e=>{"use strict";e.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,i=7*s;function a(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,o){o=o||{};var l,c,p=typeof e;if("string"===p&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(a){var o=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return o*i;case"days":case"day":case"d":return o*s;case"hours":case"hour":case"hrs":case"hr":case"h":return o*n;case"minutes":case"minute":case"mins":case"min":case"m":return o*r;case"seconds":case"second":case"secs":case"sec":case"s":return o*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===p&&isFinite(e))return o.long?(l=e,(c=Math.abs(l))>=s?a(l,c,s,"day"):c>=n?a(l,c,n,"hour"):c>=r?a(l,c,r,"minute"):c>=t?a(l,c,t,"second"):l+" ms"):function(e){var i=Math.abs(e);return i>=s?Math.round(e/s)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},6616:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const r=Object.keys(t);for(const n of r)if(e[n]!==t[n])return!1;return!0}},6636:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(4960),s=r(1373),i=r(2352),a=r(9594),o=r(6735),l=r(4014);const{isExpression:c,isFunction:p,isStatement:u,isClassBody:d,isTSInterfaceBody:f,isTSEnumMember:h}=i,m=/e/i,y=/\.0+$/,g=/[\n\r\u2028\u2029]/,b=/[\n\r\u2028\u2029]|\*\//;function v(e){return"CommentLine"===e.type||g.test(e.value)}const{needsParens:T}=s;class x{constructor(e,t,r,s){this.inForStatementInit=!1,this.tokenContext=0,this._tokens=null,this._originalCode=null,this._currentNode=null,this._indent=0,this._indentRepeat=0,this._insideAux=!1,this._noLineTerminator=!1,this._noLineTerminatorAfterNode=null,this._printAuxAfterOnNextUserNode=!1,this._printedComments=new Set,this._endsWithInteger=!1,this._endsWithWord=!1,this._endsWithDiv=!1,this._lastCommentLine=0,this._endsWithInnerRaw=!1,this._indentInnerComments=!0,this.tokenMap=null,this._boundGetRawIdentifier=this._getRawIdentifier.bind(this),this._printSemicolonBeforeNextNode=-1,this._printSemicolonBeforeNextToken=-1,this.format=e,this._tokens=r,this._originalCode=s,this._indentRepeat=e.indent.style.length,this._inputMap=null==t?void 0:t._inputMap,this._buf=new n.default(t,e.indent.style[0])}enterForStatementInit(){return this.inForStatementInit?()=>{}:(this.inForStatementInit=!0,()=>{this.inForStatementInit=!1})}enterDelimited(){const e=this.inForStatementInit,t=this._noLineTerminatorAfterNode;return!1===e&&null===t?()=>{}:(this.inForStatementInit=!1,this._noLineTerminatorAfterNode=null,()=>{this.inForStatementInit=e,this._noLineTerminatorAfterNode=t})}generate(e){return this.format.preserveFormat&&(this.tokenMap=new a.TokenMap(e,this._tokens,this._originalCode)),this.print(e),this._maybeAddAuxComment(),this._buf.get()}indent(){const{format:e}=this;e.preserveFormat||e.compact||e.concise||this._indent++}dedent(){const{format:e}=this;e.preserveFormat||e.compact||e.concise||this._indent--}semicolon(e=!1){if(this._maybeAddAuxComment(),e)return this._appendChar(59),void(this._noLineTerminator=!1);if(this.tokenMap){const e=this._currentNode;if(null!=e.start&&null!=e.end){if(!this.tokenMap.endMatches(e,";"))return void(this._printSemicolonBeforeNextNode=this._buf.getCurrentLine());const t=this.tokenMap.getIndexes(this._currentNode);this._catchUpTo(this._tokens[t[t.length-1]].loc.start)}}this._queue(59),this._noLineTerminator=!1}rightBrace(e){this.format.minified&&this._buf.removeLastSemicolon(),this.sourceWithOffset("end",e.loc,-1),this.tokenChar(125)}rightParens(e){this.sourceWithOffset("end",e.loc,-1),this.tokenChar(41)}space(e=!1){const{format:t}=this;if(!t.compact&&!t.preserveFormat)if(e)this._space();else if(this._buf.hasContent()){const e=this.getLastChar();32!==e&&10!==e&&this._space()}}word(e,t=!1){this.tokenContext=0,this._maybePrintInnerComments(e),this._maybeAddAuxComment(),this.tokenMap&&this._catchUpToCurrentToken(e),(this._endsWithWord||this._endsWithDiv&&47===e.charCodeAt(0))&&this._space(),this._append(e,!1),this._endsWithWord=!0,this._noLineTerminator=t}number(e,t){this.word(e),this._endsWithInteger=Number.isInteger(t)&&!function(e){if(e.length>2&&48===e.charCodeAt(0)){const t=e.charCodeAt(1);return 98===t||111===t||120===t}return!1}(e)&&!m.test(e)&&!y.test(e)&&46!==e.charCodeAt(e.length-1)}token(e,t=!1,r=0){this.tokenContext=0,this._maybePrintInnerComments(e,r),this._maybeAddAuxComment(),this.tokenMap&&this._catchUpToCurrentToken(e,r);const n=this.getLastChar(),s=e.charCodeAt(0);(33===n&&("--"===e||61===s)||43===s&&43===n||45===s&&45===n||46===s&&this._endsWithInteger)&&this._space(),this._append(e,t),this._noLineTerminator=!1}tokenChar(e){this.tokenContext=0;const t=String.fromCharCode(e);this._maybePrintInnerComments(t),this._maybeAddAuxComment(),this.tokenMap&&this._catchUpToCurrentToken(t);const r=this.getLastChar();(43===e&&43===r||45===e&&45===r||46===e&&this._endsWithInteger)&&this._space(),this._appendChar(e),this._noLineTerminator=!1}newline(e=1,t){if(!(e<=0)){if(!t){if(this.format.retainLines||this.format.compact)return;if(this.format.concise)return void this.space()}e>2&&(e=2),e-=this._buf.getNewlineCount();for(let t=0;t<e;t++)this._newline()}}endsWith(e){return this.getLastChar()===e}getLastChar(){return this._buf.getLastChar()}endsWithCharAndNewline(){return this._buf.endsWithCharAndNewline()}removeTrailingNewline(){this._buf.removeTrailingNewline()}exactSource(e,t){e?(this._catchUp("start",e),this._buf.exactSource(e,t)):t()}source(e,t){t&&(this._catchUp(e,t),this._buf.source(e,t))}sourceWithOffset(e,t,r){t&&!this.format.preserveFormat&&(this._catchUp(e,t),this._buf.sourceWithOffset(e,t,r))}sourceIdentifierName(e,t){if(!this._buf._canMarkIdName)return;const r=this._buf._sourcePosition;r.identifierNamePos=t,r.identifierName=e}_space(){this._queue(32)}_newline(){this._queue(10)}_catchUpToCurrentToken(e,t=0){const r=this.tokenMap.findMatching(this._currentNode,e,t);r&&this._catchUpTo(r.loc.start),-1!==this._printSemicolonBeforeNextToken&&this._printSemicolonBeforeNextToken===this._buf.getCurrentLine()&&(this._buf.appendChar(59),this._endsWithWord=!1,this._endsWithInteger=!1,this._endsWithDiv=!1),this._printSemicolonBeforeNextToken=-1,this._printSemicolonBeforeNextNode=-1}_append(e,t){this._maybeIndent(e.charCodeAt(0)),this._buf.append(e,t),this._endsWithWord=!1,this._endsWithInteger=!1,this._endsWithDiv=!1}_appendChar(e){this._maybeIndent(e),this._buf.appendChar(e),this._endsWithWord=!1,this._endsWithInteger=!1,this._endsWithDiv=!1}_queue(e){this._maybeIndent(e),this._buf.queue(e),this._endsWithWord=!1,this._endsWithInteger=!1}_maybeIndent(e){this._indent&&10!==e&&this.endsWith(10)&&this._buf.queueIndentation(this._getIndent())}_shouldIndent(e){if(this._indent&&10!==e&&this.endsWith(10))return!0}catchUp(e){if(!this.format.retainLines)return;const t=e-this._buf.getCurrentLine();for(let e=0;e<t;e++)this._newline()}_catchUp(e,t){const{format:r}=this;if(!r.preserveFormat)return void(r.retainLines&&null!=t&&t[e]&&this.catchUp(t[e].line));const n=null==t?void 0:t[e];null!=n&&this._catchUpTo(n)}_catchUpTo({line:e,column:t,index:r}){const n=e-this._buf.getCurrentLine();if(n>0&&this._noLineTerminator)return;for(let e=0;e<n;e++)this._newline();const s=n>0?t:t-this._buf.getCurrentColumn();if(s>0){const e=this._originalCode?this._originalCode.slice(r-s,r).replace(/[^\t\x0B\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]/gu," "):" ".repeat(s);this._append(e,!1)}}_getIndent(){return this._indentRepeat*this._indent}printTerminatorless(e){this._noLineTerminator=!0,this.print(e)}print(e,t,r){var n,i,a;if(!e)return;this._endsWithInnerRaw=!1;const o=e.type,l=this.format,p=l.concise;e._compact&&(l.concise=!0);const u=this[o];if(void 0===u)throw new ReferenceError(`unknown node of type ${JSON.stringify(o)} with constructor ${JSON.stringify(e.constructor.name)}`);const d=this._currentNode;this._currentNode=e,this.tokenMap&&(this._printSemicolonBeforeNextToken=this._printSemicolonBeforeNextNode);const f=this._insideAux;this._insideAux=null==e.loc,this._maybeAddAuxComment(this._insideAux&&!f);const h=null==(n=e.extra)?void 0:n.parenthesized;let m=h&&l.preserveFormat||h&&l.retainFunctionParens&&"FunctionExpression"===o||T(e,d,this.tokenContext,this.inForStatementInit,l.preserveFormat?this._boundGetRawIdentifier:void 0);if(!m&&h&&null!=(i=e.leadingComments)&&i.length&&"CommentBlock"===e.leadingComments[0].type)switch(null==d?void 0:d.type){case"ExpressionStatement":case"VariableDeclarator":case"AssignmentExpression":case"ReturnStatement":break;case"CallExpression":case"OptionalCallExpression":case"NewExpression":if(d.callee!==e)break;default:m=!0}let y,g,b=!1;var x;!m&&this._noLineTerminator&&(null!=(a=e.leadingComments)&&a.some(v)||this.format.retainLines&&e.loc&&e.loc.start.line>this._buf.getCurrentLine())&&(m=!0,b=!0),m||(t||(t=d&&this._noLineTerminatorAfterNode===d&&s.isLastChild(d,e)),t&&(null!=(x=e.trailingComments)&&x.some(v)?c(e)&&(m=!0):(y=this._noLineTerminatorAfterNode,this._noLineTerminatorAfterNode=e))),m&&(this.tokenChar(40),b&&this.indent(),this._endsWithInnerRaw=!1,this.inForStatementInit&&(g=!0,this.inForStatementInit=!1),y=this._noLineTerminatorAfterNode,this._noLineTerminatorAfterNode=null),this._lastCommentLine=0,this._printLeadingComments(e,d);const S="Program"===o||"File"===o?null:e.loc;this.exactSource(S,u.bind(this,e,d)),m?(this._printTrailingComments(e,d),b&&(this.dedent(),this.newline()),this.tokenChar(41),this._noLineTerminator=t,g&&(this.inForStatementInit=!0)):t&&!this._noLineTerminator?(this._noLineTerminator=!0,this._printTrailingComments(e,d)):this._printTrailingComments(e,d,r),this._currentNode=d,l.concise=p,this._insideAux=f,void 0!==y&&(this._noLineTerminatorAfterNode=y),this._endsWithInnerRaw=!1}_maybeAddAuxComment(e){e&&this._printAuxBeforeComment(),this._insideAux||this._printAuxAfterComment()}_printAuxBeforeComment(){if(this._printAuxAfterOnNextUserNode)return;this._printAuxAfterOnNextUserNode=!0;const e=this.format.auxiliaryCommentBefore;e&&this._printComment({type:"CommentBlock",value:e},0)}_printAuxAfterComment(){if(!this._printAuxAfterOnNextUserNode)return;this._printAuxAfterOnNextUserNode=!1;const e=this.format.auxiliaryCommentAfter;e&&this._printComment({type:"CommentBlock",value:e},0)}getPossibleRaw(e){const t=e.extra;if(null!=(null==t?void 0:t.raw)&&null!=t.rawValue&&e.value===t.rawValue)return t.raw}printJoin(e,t,r,n,s,i,a,o){if(null==e||!e.length)return;if(null==r&&this.format.retainLines){var l;const t=null==(l=e[0].loc)?void 0:l.start.line;null!=t&&t!==this._buf.getCurrentLine()&&(r=!0)}r&&this.indent();const c={addNewlines:i,nextNodeStartLine:0},p=null==n?void 0:n.bind(this),u=e.length;for(let r=0;r<u;r++){const n=e[r];var d;if(n&&(t&&this._printNewline(0===r,c),this.print(n,void 0,o||0),null==a||a(n,r),null!=p&&(r<u-1?p(r,!1):s&&p(r,!0)),t))if(null!=(d=n.trailingComments)&&d.length||(this._lastCommentLine=0),r+1===u)this.newline(1);else{var f;const t=e[r+1];c.nextNodeStartLine=(null==(f=t.loc)?void 0:f.start.line)||0,this._printNewline(!0,c)}}r&&this.dedent()}printAndIndentOnComments(e){const t=e.leadingComments&&e.leadingComments.length>0;t&&this.indent(),this.print(e),t&&this.dedent()}printBlock(e){const t=e.body;"EmptyStatement"!==t.type&&this.space(),this.print(t)}_printTrailingComments(e,t,r){const{innerComments:n,trailingComments:s}=e;null!=n&&n.length&&this._printComments(2,n,e,t,r),null!=s&&s.length&&this._printComments(2,s,e,t,r)}_printLeadingComments(e,t){const r=e.leadingComments;null!=r&&r.length&&this._printComments(0,r,e,t)}_maybePrintInnerComments(e,t){var r;this._endsWithInnerRaw&&this.printInnerComments(null==(r=this.tokenMap)?void 0:r.findMatching(this._currentNode,e,t)),this._endsWithInnerRaw=!0,this._indentInnerComments=!0}printInnerComments(e){const t=this._currentNode,r=t.innerComments;if(null==r||!r.length)return;const n=this.endsWith(32),s=this._indentInnerComments,i=this._printedComments.size;s&&this.indent(),this._printComments(1,r,t,void 0,void 0,e),n&&i!==this._printedComments.size&&this.space(),s&&this.dedent()}noIndentInnerCommentsHere(){this._indentInnerComments=!1}printSequence(e,t,r,n){this.printJoin(e,!0,null!=t&&t,void 0,void 0,n,void 0,r)}printList(e,t,r,n,s,i){this.printJoin(e,r,n,null!=s?s:S,t,void 0,i)}shouldPrintTrailingComma(e){if(!this.tokenMap)return null;const t=this.tokenMap.findLastIndex(this._currentNode,(t=>this.tokenMap.matchesOriginal(t,e)));return t<=0?null:this.tokenMap.matchesOriginal(this._tokens[t-1],",")}_printNewline(e,t){const r=this.format;if(r.retainLines||r.compact)return;if(r.concise)return void this.space();if(!e)return;const n=t.nextNodeStartLine,s=this._lastCommentLine;if(n>0&&s>0){const e=n-s;if(e>=0)return void this.newline(e||1)}this._buf.hasContent()&&this.newline(1)}_shouldPrintComment(e,t){if(e.ignore)return 0;if(this._printedComments.has(e))return 0;if(this._noLineTerminator&&b.test(e.value))return 2;if(t&&this.tokenMap){const r=this.tokenMap.find(this._currentNode,(t=>t.value===e.value));if(r&&r.start>t.start)return 2}return this._printedComments.add(e),this.format.shouldPrintComment(e.value)?1:0}_printComment(e,t){const r=this._noLineTerminator,n="CommentBlock"===e.type,s=n&&1!==t&&!this._noLineTerminator;s&&this._buf.hasContent()&&2!==t&&this.newline(1);const i=this.getLastChar();let a;if(91!==i&&123!==i&&40!==i&&this.space(),n){if(a=`/*${e.value}*/`,this.format.indent.adjustMultilineComment){var o;const t=null==(o=e.loc)?void 0:o.start.column;if(t){const e=new RegExp("\\n\\s{1,"+t+"}","g");a=a.replace(e,"\n")}if(this.format.concise)a=a.replace(/\n(?!$)/g,"\n");else{let e=this.format.retainLines?0:this._buf.getCurrentColumn();(this._shouldIndent(47)||this.format.retainLines)&&(e+=this._getIndent()),a=a.replace(/\n(?!$)/g,`\n${" ".repeat(e)}`)}}}else a=r?`/*${e.value}*/`:`//${e.value}`;if(this._endsWithDiv&&this._space(),this.tokenMap){const{_printSemicolonBeforeNextToken:t,_printSemicolonBeforeNextNode:r}=this;this._printSemicolonBeforeNextToken=-1,this._printSemicolonBeforeNextNode=-1,this.source("start",e.loc),this._append(a,n),this._printSemicolonBeforeNextNode=r,this._printSemicolonBeforeNextToken=t}else this.source("start",e.loc),this._append(a,n);n||r||this.newline(1,!0),s&&3!==t&&this.newline(1)}_printComments(e,t,r,n,s=0,i){const a=r.loc,o=t.length;let l=!!a;const c=l?a.start.line:0,m=l?a.end.line:0;let y=0,b=0;const v=this._noLineTerminator?function(){}:this.newline.bind(this);for(let a=0;a<o;a++){const T=t[a],x=this._shouldPrintComment(T,i);if(2===x){l=!1;break}if(l&&T.loc&&1===x){const t=T.loc.start.line,r=T.loc.end.line;if(0===e){let e=0;0===a?!this._buf.hasContent()||"CommentLine"!==T.type&&t===r||(e=b=1):e=t-y,y=r,v(e),this._printComment(T,1),a+1===o&&(v(Math.max(c-y,b)),y=c)}else if(1===e){const e=t-(0===a?c:y);y=r,v(e),this._printComment(T,1),a+1===o&&(v(Math.min(1,m-y)),y=m)}else{const e=t-(0===a?m-s:y);y=r,v(e),this._printComment(T,1)}}else{if(l=!1,1!==x)continue;if(1===o){const t=T.loc?T.loc.start.line===T.loc.end.line:!g.test(T.value),s=t&&!u(r)&&!d(n)&&!f(n)&&!h(r);0===e?this._printComment(T,s&&"ObjectExpression"!==r.type||t&&p(n,{body:r})?1:0):s&&2===e?this._printComment(T,1):this._printComment(T,0)}else 1!==e||"ObjectExpression"===r.type&&r.properties.length>1||"ClassBody"===r.type||"TSInterfaceBody"===r.type?this._printComment(T,0):this._printComment(T,0===a?2:a===o-1?3:0)}}2===e&&l&&y&&(this._lastCommentLine=y)}}function S(e,t){this.token(",",!1,e),t||this.space()}Object.assign(x.prototype,o),(0,l.addDeprecatedGenerators)(x),t.default=x},6642:(e,t,r)=>{"use strict";var n=r(3003);e.exports=function(){return Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a")?Number.isNaN:n}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},6735:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2226);Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===n[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return n[e]}}))}));var s=r(4436);Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===s[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}}))}));var i=r(521);Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===i[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}}))}));var a=r(6271);Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===a[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}}))}));var o=r(2861);Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===o[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}}))}));var l=r(9638);Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===l[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return l[e]}}))}));var c=r(7942);Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===c[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}}))}));var p=r(2259);Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===p[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return p[e]}}))}));var u=r(546);Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===u[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return u[e]}}))}));var d=r(3962);Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===d[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return d[e]}}))}));var f=r(9276);Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===f[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return f[e]}}))}))},6743:(e,t,r)=>{"use strict";var n=r(9353);e.exports=Function.prototype.bind||n},6744:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){e+="";let t="";for(const r of e)t+=(0,s.isIdentifierChar)(r.codePointAt(0))?r:"-";return t=t.replace(/^[-0-9]+/,""),t=t.replace(/[-\s]+(.)?/g,(function(e,t){return t?t.toUpperCase():""})),(0,n.default)(t)||(t=`_${t}`),t||"_"};var n=r(983),s=r(1e3)},6779:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AnyTypeAnnotation",{enumerable:!0,get:function(){return n.anyTypeAnnotation}}),Object.defineProperty(t,"ArgumentPlaceholder",{enumerable:!0,get:function(){return n.argumentPlaceholder}}),Object.defineProperty(t,"ArrayExpression",{enumerable:!0,get:function(){return n.arrayExpression}}),Object.defineProperty(t,"ArrayPattern",{enumerable:!0,get:function(){return n.arrayPattern}}),Object.defineProperty(t,"ArrayTypeAnnotation",{enumerable:!0,get:function(){return n.arrayTypeAnnotation}}),Object.defineProperty(t,"ArrowFunctionExpression",{enumerable:!0,get:function(){return n.arrowFunctionExpression}}),Object.defineProperty(t,"AssignmentExpression",{enumerable:!0,get:function(){return n.assignmentExpression}}),Object.defineProperty(t,"AssignmentPattern",{enumerable:!0,get:function(){return n.assignmentPattern}}),Object.defineProperty(t,"AwaitExpression",{enumerable:!0,get:function(){return n.awaitExpression}}),Object.defineProperty(t,"BigIntLiteral",{enumerable:!0,get:function(){return n.bigIntLiteral}}),Object.defineProperty(t,"BinaryExpression",{enumerable:!0,get:function(){return n.binaryExpression}}),Object.defineProperty(t,"BindExpression",{enumerable:!0,get:function(){return n.bindExpression}}),Object.defineProperty(t,"BlockStatement",{enumerable:!0,get:function(){return n.blockStatement}}),Object.defineProperty(t,"BooleanLiteral",{enumerable:!0,get:function(){return n.booleanLiteral}}),Object.defineProperty(t,"BooleanLiteralTypeAnnotation",{enumerable:!0,get:function(){return n.booleanLiteralTypeAnnotation}}),Object.defineProperty(t,"BooleanTypeAnnotation",{enumerable:!0,get:function(){return n.booleanTypeAnnotation}}),Object.defineProperty(t,"BreakStatement",{enumerable:!0,get:function(){return n.breakStatement}}),Object.defineProperty(t,"CallExpression",{enumerable:!0,get:function(){return n.callExpression}}),Object.defineProperty(t,"CatchClause",{enumerable:!0,get:function(){return n.catchClause}}),Object.defineProperty(t,"ClassAccessorProperty",{enumerable:!0,get:function(){return n.classAccessorProperty}}),Object.defineProperty(t,"ClassBody",{enumerable:!0,get:function(){return n.classBody}}),Object.defineProperty(t,"ClassDeclaration",{enumerable:!0,get:function(){return n.classDeclaration}}),Object.defineProperty(t,"ClassExpression",{enumerable:!0,get:function(){return n.classExpression}}),Object.defineProperty(t,"ClassImplements",{enumerable:!0,get:function(){return n.classImplements}}),Object.defineProperty(t,"ClassMethod",{enumerable:!0,get:function(){return n.classMethod}}),Object.defineProperty(t,"ClassPrivateMethod",{enumerable:!0,get:function(){return n.classPrivateMethod}}),Object.defineProperty(t,"ClassPrivateProperty",{enumerable:!0,get:function(){return n.classPrivateProperty}}),Object.defineProperty(t,"ClassProperty",{enumerable:!0,get:function(){return n.classProperty}}),Object.defineProperty(t,"ConditionalExpression",{enumerable:!0,get:function(){return n.conditionalExpression}}),Object.defineProperty(t,"ContinueStatement",{enumerable:!0,get:function(){return n.continueStatement}}),Object.defineProperty(t,"DebuggerStatement",{enumerable:!0,get:function(){return n.debuggerStatement}}),Object.defineProperty(t,"DecimalLiteral",{enumerable:!0,get:function(){return n.decimalLiteral}}),Object.defineProperty(t,"DeclareClass",{enumerable:!0,get:function(){return n.declareClass}}),Object.defineProperty(t,"DeclareExportAllDeclaration",{enumerable:!0,get:function(){return n.declareExportAllDeclaration}}),Object.defineProperty(t,"DeclareExportDeclaration",{enumerable:!0,get:function(){return n.declareExportDeclaration}}),Object.defineProperty(t,"DeclareFunction",{enumerable:!0,get:function(){return n.declareFunction}}),Object.defineProperty(t,"DeclareInterface",{enumerable:!0,get:function(){return n.declareInterface}}),Object.defineProperty(t,"DeclareModule",{enumerable:!0,get:function(){return n.declareModule}}),Object.defineProperty(t,"DeclareModuleExports",{enumerable:!0,get:function(){return n.declareModuleExports}}),Object.defineProperty(t,"DeclareOpaqueType",{enumerable:!0,get:function(){return n.declareOpaqueType}}),Object.defineProperty(t,"DeclareTypeAlias",{enumerable:!0,get:function(){return n.declareTypeAlias}}),Object.defineProperty(t,"DeclareVariable",{enumerable:!0,get:function(){return n.declareVariable}}),Object.defineProperty(t,"DeclaredPredicate",{enumerable:!0,get:function(){return n.declaredPredicate}}),Object.defineProperty(t,"Decorator",{enumerable:!0,get:function(){return n.decorator}}),Object.defineProperty(t,"Directive",{enumerable:!0,get:function(){return n.directive}}),Object.defineProperty(t,"DirectiveLiteral",{enumerable:!0,get:function(){return n.directiveLiteral}}),Object.defineProperty(t,"DoExpression",{enumerable:!0,get:function(){return n.doExpression}}),Object.defineProperty(t,"DoWhileStatement",{enumerable:!0,get:function(){return n.doWhileStatement}}),Object.defineProperty(t,"EmptyStatement",{enumerable:!0,get:function(){return n.emptyStatement}}),Object.defineProperty(t,"EmptyTypeAnnotation",{enumerable:!0,get:function(){return n.emptyTypeAnnotation}}),Object.defineProperty(t,"EnumBooleanBody",{enumerable:!0,get:function(){return n.enumBooleanBody}}),Object.defineProperty(t,"EnumBooleanMember",{enumerable:!0,get:function(){return n.enumBooleanMember}}),Object.defineProperty(t,"EnumDeclaration",{enumerable:!0,get:function(){return n.enumDeclaration}}),Object.defineProperty(t,"EnumDefaultedMember",{enumerable:!0,get:function(){return n.enumDefaultedMember}}),Object.defineProperty(t,"EnumNumberBody",{enumerable:!0,get:function(){return n.enumNumberBody}}),Object.defineProperty(t,"EnumNumberMember",{enumerable:!0,get:function(){return n.enumNumberMember}}),Object.defineProperty(t,"EnumStringBody",{enumerable:!0,get:function(){return n.enumStringBody}}),Object.defineProperty(t,"EnumStringMember",{enumerable:!0,get:function(){return n.enumStringMember}}),Object.defineProperty(t,"EnumSymbolBody",{enumerable:!0,get:function(){return n.enumSymbolBody}}),Object.defineProperty(t,"ExistsTypeAnnotation",{enumerable:!0,get:function(){return n.existsTypeAnnotation}}),Object.defineProperty(t,"ExportAllDeclaration",{enumerable:!0,get:function(){return n.exportAllDeclaration}}),Object.defineProperty(t,"ExportDefaultDeclaration",{enumerable:!0,get:function(){return n.exportDefaultDeclaration}}),Object.defineProperty(t,"ExportDefaultSpecifier",{enumerable:!0,get:function(){return n.exportDefaultSpecifier}}),Object.defineProperty(t,"ExportNamedDeclaration",{enumerable:!0,get:function(){return n.exportNamedDeclaration}}),Object.defineProperty(t,"ExportNamespaceSpecifier",{enumerable:!0,get:function(){return n.exportNamespaceSpecifier}}),Object.defineProperty(t,"ExportSpecifier",{enumerable:!0,get:function(){return n.exportSpecifier}}),Object.defineProperty(t,"ExpressionStatement",{enumerable:!0,get:function(){return n.expressionStatement}}),Object.defineProperty(t,"File",{enumerable:!0,get:function(){return n.file}}),Object.defineProperty(t,"ForInStatement",{enumerable:!0,get:function(){return n.forInStatement}}),Object.defineProperty(t,"ForOfStatement",{enumerable:!0,get:function(){return n.forOfStatement}}),Object.defineProperty(t,"ForStatement",{enumerable:!0,get:function(){return n.forStatement}}),Object.defineProperty(t,"FunctionDeclaration",{enumerable:!0,get:function(){return n.functionDeclaration}}),Object.defineProperty(t,"FunctionExpression",{enumerable:!0,get:function(){return n.functionExpression}}),Object.defineProperty(t,"FunctionTypeAnnotation",{enumerable:!0,get:function(){return n.functionTypeAnnotation}}),Object.defineProperty(t,"FunctionTypeParam",{enumerable:!0,get:function(){return n.functionTypeParam}}),Object.defineProperty(t,"GenericTypeAnnotation",{enumerable:!0,get:function(){return n.genericTypeAnnotation}}),Object.defineProperty(t,"Identifier",{enumerable:!0,get:function(){return n.identifier}}),Object.defineProperty(t,"IfStatement",{enumerable:!0,get:function(){return n.ifStatement}}),Object.defineProperty(t,"Import",{enumerable:!0,get:function(){return n.import}}),Object.defineProperty(t,"ImportAttribute",{enumerable:!0,get:function(){return n.importAttribute}}),Object.defineProperty(t,"ImportDeclaration",{enumerable:!0,get:function(){return n.importDeclaration}}),Object.defineProperty(t,"ImportDefaultSpecifier",{enumerable:!0,get:function(){return n.importDefaultSpecifier}}),Object.defineProperty(t,"ImportExpression",{enumerable:!0,get:function(){return n.importExpression}}),Object.defineProperty(t,"ImportNamespaceSpecifier",{enumerable:!0,get:function(){return n.importNamespaceSpecifier}}),Object.defineProperty(t,"ImportSpecifier",{enumerable:!0,get:function(){return n.importSpecifier}}),Object.defineProperty(t,"IndexedAccessType",{enumerable:!0,get:function(){return n.indexedAccessType}}),Object.defineProperty(t,"InferredPredicate",{enumerable:!0,get:function(){return n.inferredPredicate}}),Object.defineProperty(t,"InterfaceDeclaration",{enumerable:!0,get:function(){return n.interfaceDeclaration}}),Object.defineProperty(t,"InterfaceExtends",{enumerable:!0,get:function(){return n.interfaceExtends}}),Object.defineProperty(t,"InterfaceTypeAnnotation",{enumerable:!0,get:function(){return n.interfaceTypeAnnotation}}),Object.defineProperty(t,"InterpreterDirective",{enumerable:!0,get:function(){return n.interpreterDirective}}),Object.defineProperty(t,"IntersectionTypeAnnotation",{enumerable:!0,get:function(){return n.intersectionTypeAnnotation}}),Object.defineProperty(t,"JSXAttribute",{enumerable:!0,get:function(){return n.jsxAttribute}}),Object.defineProperty(t,"JSXClosingElement",{enumerable:!0,get:function(){return n.jsxClosingElement}}),Object.defineProperty(t,"JSXClosingFragment",{enumerable:!0,get:function(){return n.jsxClosingFragment}}),Object.defineProperty(t,"JSXElement",{enumerable:!0,get:function(){return n.jsxElement}}),Object.defineProperty(t,"JSXEmptyExpression",{enumerable:!0,get:function(){return n.jsxEmptyExpression}}),Object.defineProperty(t,"JSXExpressionContainer",{enumerable:!0,get:function(){return n.jsxExpressionContainer}}),Object.defineProperty(t,"JSXFragment",{enumerable:!0,get:function(){return n.jsxFragment}}),Object.defineProperty(t,"JSXIdentifier",{enumerable:!0,get:function(){return n.jsxIdentifier}}),Object.defineProperty(t,"JSXMemberExpression",{enumerable:!0,get:function(){return n.jsxMemberExpression}}),Object.defineProperty(t,"JSXNamespacedName",{enumerable:!0,get:function(){return n.jsxNamespacedName}}),Object.defineProperty(t,"JSXOpeningElement",{enumerable:!0,get:function(){return n.jsxOpeningElement}}),Object.defineProperty(t,"JSXOpeningFragment",{enumerable:!0,get:function(){return n.jsxOpeningFragment}}),Object.defineProperty(t,"JSXSpreadAttribute",{enumerable:!0,get:function(){return n.jsxSpreadAttribute}}),Object.defineProperty(t,"JSXSpreadChild",{enumerable:!0,get:function(){return n.jsxSpreadChild}}),Object.defineProperty(t,"JSXText",{enumerable:!0,get:function(){return n.jsxText}}),Object.defineProperty(t,"LabeledStatement",{enumerable:!0,get:function(){return n.labeledStatement}}),Object.defineProperty(t,"LogicalExpression",{enumerable:!0,get:function(){return n.logicalExpression}}),Object.defineProperty(t,"MemberExpression",{enumerable:!0,get:function(){return n.memberExpression}}),Object.defineProperty(t,"MetaProperty",{enumerable:!0,get:function(){return n.metaProperty}}),Object.defineProperty(t,"MixedTypeAnnotation",{enumerable:!0,get:function(){return n.mixedTypeAnnotation}}),Object.defineProperty(t,"ModuleExpression",{enumerable:!0,get:function(){return n.moduleExpression}}),Object.defineProperty(t,"NewExpression",{enumerable:!0,get:function(){return n.newExpression}}),Object.defineProperty(t,"Noop",{enumerable:!0,get:function(){return n.noop}}),Object.defineProperty(t,"NullLiteral",{enumerable:!0,get:function(){return n.nullLiteral}}),Object.defineProperty(t,"NullLiteralTypeAnnotation",{enumerable:!0,get:function(){return n.nullLiteralTypeAnnotation}}),Object.defineProperty(t,"NullableTypeAnnotation",{enumerable:!0,get:function(){return n.nullableTypeAnnotation}}),Object.defineProperty(t,"NumberLiteral",{enumerable:!0,get:function(){return n.numberLiteral}}),Object.defineProperty(t,"NumberLiteralTypeAnnotation",{enumerable:!0,get:function(){return n.numberLiteralTypeAnnotation}}),Object.defineProperty(t,"NumberTypeAnnotation",{enumerable:!0,get:function(){return n.numberTypeAnnotation}}),Object.defineProperty(t,"NumericLiteral",{enumerable:!0,get:function(){return n.numericLiteral}}),Object.defineProperty(t,"ObjectExpression",{enumerable:!0,get:function(){return n.objectExpression}}),Object.defineProperty(t,"ObjectMethod",{enumerable:!0,get:function(){return n.objectMethod}}),Object.defineProperty(t,"ObjectPattern",{enumerable:!0,get:function(){return n.objectPattern}}),Object.defineProperty(t,"ObjectProperty",{enumerable:!0,get:function(){return n.objectProperty}}),Object.defineProperty(t,"ObjectTypeAnnotation",{enumerable:!0,get:function(){return n.objectTypeAnnotation}}),Object.defineProperty(t,"ObjectTypeCallProperty",{enumerable:!0,get:function(){return n.objectTypeCallProperty}}),Object.defineProperty(t,"ObjectTypeIndexer",{enumerable:!0,get:function(){return n.objectTypeIndexer}}),Object.defineProperty(t,"ObjectTypeInternalSlot",{enumerable:!0,get:function(){return n.objectTypeInternalSlot}}),Object.defineProperty(t,"ObjectTypeProperty",{enumerable:!0,get:function(){return n.objectTypeProperty}}),Object.defineProperty(t,"ObjectTypeSpreadProperty",{enumerable:!0,get:function(){return n.objectTypeSpreadProperty}}),Object.defineProperty(t,"OpaqueType",{enumerable:!0,get:function(){return n.opaqueType}}),Object.defineProperty(t,"OptionalCallExpression",{enumerable:!0,get:function(){return n.optionalCallExpression}}),Object.defineProperty(t,"OptionalIndexedAccessType",{enumerable:!0,get:function(){return n.optionalIndexedAccessType}}),Object.defineProperty(t,"OptionalMemberExpression",{enumerable:!0,get:function(){return n.optionalMemberExpression}}),Object.defineProperty(t,"ParenthesizedExpression",{enumerable:!0,get:function(){return n.parenthesizedExpression}}),Object.defineProperty(t,"PipelineBareFunction",{enumerable:!0,get:function(){return n.pipelineBareFunction}}),Object.defineProperty(t,"PipelinePrimaryTopicReference",{enumerable:!0,get:function(){return n.pipelinePrimaryTopicReference}}),Object.defineProperty(t,"PipelineTopicExpression",{enumerable:!0,get:function(){return n.pipelineTopicExpression}}),Object.defineProperty(t,"Placeholder",{enumerable:!0,get:function(){return n.placeholder}}),Object.defineProperty(t,"PrivateName",{enumerable:!0,get:function(){return n.privateName}}),Object.defineProperty(t,"Program",{enumerable:!0,get:function(){return n.program}}),Object.defineProperty(t,"QualifiedTypeIdentifier",{enumerable:!0,get:function(){return n.qualifiedTypeIdentifier}}),Object.defineProperty(t,"RecordExpression",{enumerable:!0,get:function(){return n.recordExpression}}),Object.defineProperty(t,"RegExpLiteral",{enumerable:!0,get:function(){return n.regExpLiteral}}),Object.defineProperty(t,"RegexLiteral",{enumerable:!0,get:function(){return n.regexLiteral}}),Object.defineProperty(t,"RestElement",{enumerable:!0,get:function(){return n.restElement}}),Object.defineProperty(t,"RestProperty",{enumerable:!0,get:function(){return n.restProperty}}),Object.defineProperty(t,"ReturnStatement",{enumerable:!0,get:function(){return n.returnStatement}}),Object.defineProperty(t,"SequenceExpression",{enumerable:!0,get:function(){return n.sequenceExpression}}),Object.defineProperty(t,"SpreadElement",{enumerable:!0,get:function(){return n.spreadElement}}),Object.defineProperty(t,"SpreadProperty",{enumerable:!0,get:function(){return n.spreadProperty}}),Object.defineProperty(t,"StaticBlock",{enumerable:!0,get:function(){return n.staticBlock}}),Object.defineProperty(t,"StringLiteral",{enumerable:!0,get:function(){return n.stringLiteral}}),Object.defineProperty(t,"StringLiteralTypeAnnotation",{enumerable:!0,get:function(){return n.stringLiteralTypeAnnotation}}),Object.defineProperty(t,"StringTypeAnnotation",{enumerable:!0,get:function(){return n.stringTypeAnnotation}}),Object.defineProperty(t,"Super",{enumerable:!0,get:function(){return n.super}}),Object.defineProperty(t,"SwitchCase",{enumerable:!0,get:function(){return n.switchCase}}),Object.defineProperty(t,"SwitchStatement",{enumerable:!0,get:function(){return n.switchStatement}}),Object.defineProperty(t,"SymbolTypeAnnotation",{enumerable:!0,get:function(){return n.symbolTypeAnnotation}}),Object.defineProperty(t,"TSAnyKeyword",{enumerable:!0,get:function(){return n.tsAnyKeyword}}),Object.defineProperty(t,"TSArrayType",{enumerable:!0,get:function(){return n.tsArrayType}}),Object.defineProperty(t,"TSAsExpression",{enumerable:!0,get:function(){return n.tsAsExpression}}),Object.defineProperty(t,"TSBigIntKeyword",{enumerable:!0,get:function(){return n.tsBigIntKeyword}}),Object.defineProperty(t,"TSBooleanKeyword",{enumerable:!0,get:function(){return n.tsBooleanKeyword}}),Object.defineProperty(t,"TSCallSignatureDeclaration",{enumerable:!0,get:function(){return n.tsCallSignatureDeclaration}}),Object.defineProperty(t,"TSConditionalType",{enumerable:!0,get:function(){return n.tsConditionalType}}),Object.defineProperty(t,"TSConstructSignatureDeclaration",{enumerable:!0,get:function(){return n.tsConstructSignatureDeclaration}}),Object.defineProperty(t,"TSConstructorType",{enumerable:!0,get:function(){return n.tsConstructorType}}),Object.defineProperty(t,"TSDeclareFunction",{enumerable:!0,get:function(){return n.tsDeclareFunction}}),Object.defineProperty(t,"TSDeclareMethod",{enumerable:!0,get:function(){return n.tsDeclareMethod}}),Object.defineProperty(t,"TSEnumBody",{enumerable:!0,get:function(){return n.tsEnumBody}}),Object.defineProperty(t,"TSEnumDeclaration",{enumerable:!0,get:function(){return n.tsEnumDeclaration}}),Object.defineProperty(t,"TSEnumMember",{enumerable:!0,get:function(){return n.tsEnumMember}}),Object.defineProperty(t,"TSExportAssignment",{enumerable:!0,get:function(){return n.tsExportAssignment}}),Object.defineProperty(t,"TSExpressionWithTypeArguments",{enumerable:!0,get:function(){return n.tsExpressionWithTypeArguments}}),Object.defineProperty(t,"TSExternalModuleReference",{enumerable:!0,get:function(){return n.tsExternalModuleReference}}),Object.defineProperty(t,"TSFunctionType",{enumerable:!0,get:function(){return n.tsFunctionType}}),Object.defineProperty(t,"TSImportEqualsDeclaration",{enumerable:!0,get:function(){return n.tsImportEqualsDeclaration}}),Object.defineProperty(t,"TSImportType",{enumerable:!0,get:function(){return n.tsImportType}}),Object.defineProperty(t,"TSIndexSignature",{enumerable:!0,get:function(){return n.tsIndexSignature}}),Object.defineProperty(t,"TSIndexedAccessType",{enumerable:!0,get:function(){return n.tsIndexedAccessType}}),Object.defineProperty(t,"TSInferType",{enumerable:!0,get:function(){return n.tsInferType}}),Object.defineProperty(t,"TSInstantiationExpression",{enumerable:!0,get:function(){return n.tsInstantiationExpression}}),Object.defineProperty(t,"TSInterfaceBody",{enumerable:!0,get:function(){return n.tsInterfaceBody}}),Object.defineProperty(t,"TSInterfaceDeclaration",{enumerable:!0,get:function(){return n.tsInterfaceDeclaration}}),Object.defineProperty(t,"TSIntersectionType",{enumerable:!0,get:function(){return n.tsIntersectionType}}),Object.defineProperty(t,"TSIntrinsicKeyword",{enumerable:!0,get:function(){return n.tsIntrinsicKeyword}}),Object.defineProperty(t,"TSLiteralType",{enumerable:!0,get:function(){return n.tsLiteralType}}),Object.defineProperty(t,"TSMappedType",{enumerable:!0,get:function(){return n.tsMappedType}}),Object.defineProperty(t,"TSMethodSignature",{enumerable:!0,get:function(){return n.tsMethodSignature}}),Object.defineProperty(t,"TSModuleBlock",{enumerable:!0,get:function(){return n.tsModuleBlock}}),Object.defineProperty(t,"TSModuleDeclaration",{enumerable:!0,get:function(){return n.tsModuleDeclaration}}),Object.defineProperty(t,"TSNamedTupleMember",{enumerable:!0,get:function(){return n.tsNamedTupleMember}}),Object.defineProperty(t,"TSNamespaceExportDeclaration",{enumerable:!0,get:function(){return n.tsNamespaceExportDeclaration}}),Object.defineProperty(t,"TSNeverKeyword",{enumerable:!0,get:function(){return n.tsNeverKeyword}}),Object.defineProperty(t,"TSNonNullExpression",{enumerable:!0,get:function(){return n.tsNonNullExpression}}),Object.defineProperty(t,"TSNullKeyword",{enumerable:!0,get:function(){return n.tsNullKeyword}}),Object.defineProperty(t,"TSNumberKeyword",{enumerable:!0,get:function(){return n.tsNumberKeyword}}),Object.defineProperty(t,"TSObjectKeyword",{enumerable:!0,get:function(){return n.tsObjectKeyword}}),Object.defineProperty(t,"TSOptionalType",{enumerable:!0,get:function(){return n.tsOptionalType}}),Object.defineProperty(t,"TSParameterProperty",{enumerable:!0,get:function(){return n.tsParameterProperty}}),Object.defineProperty(t,"TSParenthesizedType",{enumerable:!0,get:function(){return n.tsParenthesizedType}}),Object.defineProperty(t,"TSPropertySignature",{enumerable:!0,get:function(){return n.tsPropertySignature}}),Object.defineProperty(t,"TSQualifiedName",{enumerable:!0,get:function(){return n.tsQualifiedName}}),Object.defineProperty(t,"TSRestType",{enumerable:!0,get:function(){return n.tsRestType}}),Object.defineProperty(t,"TSSatisfiesExpression",{enumerable:!0,get:function(){return n.tsSatisfiesExpression}}),Object.defineProperty(t,"TSStringKeyword",{enumerable:!0,get:function(){return n.tsStringKeyword}}),Object.defineProperty(t,"TSSymbolKeyword",{enumerable:!0,get:function(){return n.tsSymbolKeyword}}),Object.defineProperty(t,"TSTemplateLiteralType",{enumerable:!0,get:function(){return n.tsTemplateLiteralType}}),Object.defineProperty(t,"TSThisType",{enumerable:!0,get:function(){return n.tsThisType}}),Object.defineProperty(t,"TSTupleType",{enumerable:!0,get:function(){return n.tsTupleType}}),Object.defineProperty(t,"TSTypeAliasDeclaration",{enumerable:!0,get:function(){return n.tsTypeAliasDeclaration}}),Object.defineProperty(t,"TSTypeAnnotation",{enumerable:!0,get:function(){return n.tsTypeAnnotation}}),Object.defineProperty(t,"TSTypeAssertion",{enumerable:!0,get:function(){return n.tsTypeAssertion}}),Object.defineProperty(t,"TSTypeLiteral",{enumerable:!0,get:function(){return n.tsTypeLiteral}}),Object.defineProperty(t,"TSTypeOperator",{enumerable:!0,get:function(){return n.tsTypeOperator}}),Object.defineProperty(t,"TSTypeParameter",{enumerable:!0,get:function(){return n.tsTypeParameter}}),Object.defineProperty(t,"TSTypeParameterDeclaration",{enumerable:!0,get:function(){return n.tsTypeParameterDeclaration}}),Object.defineProperty(t,"TSTypeParameterInstantiation",{enumerable:!0,get:function(){return n.tsTypeParameterInstantiation}}),Object.defineProperty(t,"TSTypePredicate",{enumerable:!0,get:function(){return n.tsTypePredicate}}),Object.defineProperty(t,"TSTypeQuery",{enumerable:!0,get:function(){return n.tsTypeQuery}}),Object.defineProperty(t,"TSTypeReference",{enumerable:!0,get:function(){return n.tsTypeReference}}),Object.defineProperty(t,"TSUndefinedKeyword",{enumerable:!0,get:function(){return n.tsUndefinedKeyword}}),Object.defineProperty(t,"TSUnionType",{enumerable:!0,get:function(){return n.tsUnionType}}),Object.defineProperty(t,"TSUnknownKeyword",{enumerable:!0,get:function(){return n.tsUnknownKeyword}}),Object.defineProperty(t,"TSVoidKeyword",{enumerable:!0,get:function(){return n.tsVoidKeyword}}),Object.defineProperty(t,"TaggedTemplateExpression",{enumerable:!0,get:function(){return n.taggedTemplateExpression}}),Object.defineProperty(t,"TemplateElement",{enumerable:!0,get:function(){return n.templateElement}}),Object.defineProperty(t,"TemplateLiteral",{enumerable:!0,get:function(){return n.templateLiteral}}),Object.defineProperty(t,"ThisExpression",{enumerable:!0,get:function(){return n.thisExpression}}),Object.defineProperty(t,"ThisTypeAnnotation",{enumerable:!0,get:function(){return n.thisTypeAnnotation}}),Object.defineProperty(t,"ThrowStatement",{enumerable:!0,get:function(){return n.throwStatement}}),Object.defineProperty(t,"TopicReference",{enumerable:!0,get:function(){return n.topicReference}}),Object.defineProperty(t,"TryStatement",{enumerable:!0,get:function(){return n.tryStatement}}),Object.defineProperty(t,"TupleExpression",{enumerable:!0,get:function(){return n.tupleExpression}}),Object.defineProperty(t,"TupleTypeAnnotation",{enumerable:!0,get:function(){return n.tupleTypeAnnotation}}),Object.defineProperty(t,"TypeAlias",{enumerable:!0,get:function(){return n.typeAlias}}),Object.defineProperty(t,"TypeAnnotation",{enumerable:!0,get:function(){return n.typeAnnotation}}),Object.defineProperty(t,"TypeCastExpression",{enumerable:!0,get:function(){return n.typeCastExpression}}),Object.defineProperty(t,"TypeParameter",{enumerable:!0,get:function(){return n.typeParameter}}),Object.defineProperty(t,"TypeParameterDeclaration",{enumerable:!0,get:function(){return n.typeParameterDeclaration}}),Object.defineProperty(t,"TypeParameterInstantiation",{enumerable:!0,get:function(){return n.typeParameterInstantiation}}),Object.defineProperty(t,"TypeofTypeAnnotation",{enumerable:!0,get:function(){return n.typeofTypeAnnotation}}),Object.defineProperty(t,"UnaryExpression",{enumerable:!0,get:function(){return n.unaryExpression}}),Object.defineProperty(t,"UnionTypeAnnotation",{enumerable:!0,get:function(){return n.unionTypeAnnotation}}),Object.defineProperty(t,"UpdateExpression",{enumerable:!0,get:function(){return n.updateExpression}}),Object.defineProperty(t,"V8IntrinsicIdentifier",{enumerable:!0,get:function(){return n.v8IntrinsicIdentifier}}),Object.defineProperty(t,"VariableDeclaration",{enumerable:!0,get:function(){return n.variableDeclaration}}),Object.defineProperty(t,"VariableDeclarator",{enumerable:!0,get:function(){return n.variableDeclarator}}),Object.defineProperty(t,"Variance",{enumerable:!0,get:function(){return n.variance}}),Object.defineProperty(t,"VoidTypeAnnotation",{enumerable:!0,get:function(){return n.voidTypeAnnotation}}),Object.defineProperty(t,"WhileStatement",{enumerable:!0,get:function(){return n.whileStatement}}),Object.defineProperty(t,"WithStatement",{enumerable:!0,get:function(){return n.withStatement}}),Object.defineProperty(t,"YieldExpression",{enumerable:!0,get:function(){return n.yieldExpression}});var n=r(3286)},6814:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(3874),s=r(5781),i=r(3599),a=r(7627),o=r(2352),l=o,c=r(7411),p=r(4950);const{NOT_LOCAL_BINDING:u,assignmentExpression:d,callExpression:f,cloneNode:h,getBindingIdentifiers:m,identifier:y,isArrayExpression:g,isBinary:b,isCallExpression:v,isClass:T,isClassBody:x,isClassDeclaration:S,isExportAllDeclaration:E,isExportDefaultDeclaration:P,isExportNamedDeclaration:A,isFunctionDeclaration:w,isIdentifier:C,isImportDeclaration:O,isLiteral:I,isMemberExpression:N,isMethod:k,isModuleSpecifier:_,isNullLiteral:D,isObjectExpression:j,isProperty:B,isPureish:M,isRegExpLiteral:L,isSuper:F,isTaggedTemplateExpression:R,isTemplateLiteral:U,isThisExpression:V,isUnaryExpression:q,isVariableDeclaration:W,expressionStatement:K,matchesPattern:$,memberExpression:G,numericLiteral:H,toIdentifier:Y,variableDeclaration:J,variableDeclarator:z,isRecordExpression:X,isTupleExpression:Q,isObjectProperty:Z,isTopicReference:ee,isMetaProperty:te,isPrivateName:re,isExportDeclaration:ne,buildUndefinedNode:se,sequenceExpression:ie}=o;function ae(e,t){switch(null==e?void 0:e.type){default:var r;if(O(e)||ne(e))if((E(e)||A(e)||O(e))&&e.source)ae(e.source,t);else if((A(e)||O(e))&&null!=(r=e.specifiers)&&r.length)for(const r of e.specifiers)ae(r,t);else(P(e)||A(e))&&e.declaration&&ae(e.declaration,t);else _(e)?ae(e.local,t):!I(e)||D(e)||L(e)||U(e)||t.push(e.value);break;case"MemberExpression":case"OptionalMemberExpression":case"JSXMemberExpression":ae(e.object,t),ae(e.property,t);break;case"Identifier":case"JSXIdentifier":t.push(e.name);break;case"CallExpression":case"OptionalCallExpression":case"NewExpression":ae(e.callee,t);break;case"ObjectExpression":case"ObjectPattern":for(const r of e.properties)ae(r,t);break;case"SpreadElement":case"RestElement":case"UnaryExpression":case"UpdateExpression":ae(e.argument,t);break;case"ObjectProperty":case"ObjectMethod":case"ClassProperty":case"ClassMethod":case"ClassPrivateProperty":case"ClassPrivateMethod":ae(e.key,t);break;case"ThisExpression":t.push("this");break;case"Super":t.push("super");break;case"Import":t.push("import");break;case"DoExpression":t.push("do");break;case"YieldExpression":t.push("yield"),ae(e.argument,t);break;case"AwaitExpression":t.push("await"),ae(e.argument,t);break;case"AssignmentExpression":ae(e.left,t);break;case"VariableDeclarator":case"FunctionExpression":case"FunctionDeclaration":case"ClassExpression":case"ClassDeclaration":case"PrivateName":ae(e.id,t);break;case"ParenthesizedExpression":ae(e.expression,t);break;case"MetaProperty":ae(e.meta,t),ae(e.property,t);break;case"JSXElement":ae(e.openingElement,t);break;case"JSXOpeningElement":ae(e.name,t);break;case"JSXFragment":ae(e.openingFragment,t);break;case"JSXOpeningFragment":t.push("Fragment");break;case"JSXNamespacedName":ae(e.namespace,t),ae(e.name,t)}}const oe={ForStatement(e){const t=e.get("init");if(t.isVar()){const{scope:r}=e;(r.getFunctionParent()||r.getProgramParent()).registerBinding("var",t)}},Declaration(e){e.isBlockScoped()||e.isImportDeclaration()||e.isExportDeclaration()||(e.scope.getFunctionParent()||e.scope.getProgramParent()).registerDeclaration(e)},ImportDeclaration(e){e.scope.getBlockParent().registerDeclaration(e)},TSImportEqualsDeclaration(e){e.scope.getBlockParent().registerDeclaration(e)},ReferencedIdentifier(e,t){l.isTSQualifiedName(e.parent)&&e.parent.right===e.node||e.parentPath.isTSImportEqualsDeclaration()||t.references.push(e)},ForXStatement(e,t){const r=e.get("left");if(r.isPattern()||r.isIdentifier())t.constantViolations.push(e);else if(r.isVar()){const{scope:t}=e;(t.getFunctionParent()||t.getProgramParent()).registerBinding("var",r)}},ExportDeclaration:{exit(e){const{node:t,scope:r}=e;if(E(t))return;const n=t.declaration;if(S(n)||w(n)){const t=n.id;if(!t)return;const s=r.getBinding(t.name);null==s||s.reference(e)}else if(W(n))for(const t of n.declarations)for(const n of Object.keys(m(t))){const t=r.getBinding(n);null==t||t.reference(e)}}},LabeledStatement(e){e.scope.getBlockParent().registerDeclaration(e)},AssignmentExpression(e,t){t.assignments.push(e)},UpdateExpression(e,t){t.constantViolations.push(e)},UnaryExpression(e,t){"delete"===e.node.operator&&t.constantViolations.push(e)},BlockScoped(e){let t=e.scope;if(t.path===e&&(t=t.parent),t.getBlockParent().registerDeclaration(e),e.isClassDeclaration()&&e.node.id){const t=e.node.id.name;e.scope.bindings[t]=e.scope.parent.getBinding(t)}},CatchClause(e){e.scope.registerBinding("let",e)},Function(e){const t=e.get("params");for(const r of t)e.scope.registerBinding("param",r);e.isFunctionExpression()&&e.node.id&&!e.node.id[u]&&e.scope.registerBinding("local",e.get("id"),e)},ClassExpression(e){e.node.id&&!e.node.id[u]&&e.scope.registerBinding("local",e.get("id"),e)},TSTypeAnnotation(e){e.skip()}};let le=0;class ce{constructor(e){this.uid=void 0,this.path=void 0,this.block=void 0,this.inited=void 0,this.labels=void 0,this.bindings=void 0,this.references=void 0,this.globals=void 0,this.uids=void 0,this.data=void 0,this.crawling=void 0;const{node:t}=e,r=c.scope.get(t);if((null==r?void 0:r.path)===e)return r;c.scope.set(t,this),this.uid=le++,this.block=t,this.path=e,this.labels=new Map,this.inited=!1}get parent(){var e;let t,r=this.path;do{var n;const e="key"===r.key||"decorators"===r.listKey;r=r.parentPath,e&&r.isMethod()&&(r=r.parentPath),null!=(n=r)&&n.isScope()&&(t=r)}while(r&&!t);return null==(e=t)?void 0:e.scope}generateDeclaredUidIdentifier(e){const t=this.generateUidIdentifier(e);return this.push({id:t}),h(t)}generateUidIdentifier(e){return y(this.generateUid(e))}generateUid(e="temp"){let t;e=Y(e).replace(/^_+/,"").replace(/\d+$/g,"");let r=1;do{t=`_${e}`,r>1&&(t+=r),r++}while(this.hasLabel(t)||this.hasBinding(t)||this.hasGlobal(t)||this.hasReference(t));const n=this.getProgramParent();return n.references[t]=!0,n.uids[t]=!0,t}generateUidBasedOnNode(e,t){const r=[];ae(e,r);let n=r.join("$");return n=n.replace(/^_/,"")||t||"ref",this.generateUid(n.slice(0,20))}generateUidIdentifierBasedOnNode(e,t){return y(this.generateUidBasedOnNode(e,t))}isStatic(e){if(V(e)||F(e)||ee(e))return!0;if(C(e)){const t=this.getBinding(e.name);return t?t.constant:this.hasBinding(e.name)}return!1}maybeGenerateMemoised(e,t){if(this.isStatic(e))return null;{const r=this.generateUidIdentifierBasedOnNode(e);return t?r:(this.push({id:r}),h(r))}}checkBlockScopedCollisions(e,t,r,n){if("param"!==t&&"local"!==e.kind&&("let"===t||"let"===e.kind||"const"===e.kind||"module"===e.kind||"param"===e.kind&&"const"===t))throw this.path.hub.buildError(n,`Duplicate declaration "${r}"`,TypeError)}rename(e,t){const r=this.getBinding(e);r&&(t||(t=this.generateUidIdentifier(e).name),new n.default(r,e,t).rename(arguments[2]))}dump(){const e="-".repeat(60);console.log(e);let t=this;do{console.log("#",t.block.type);for(const e of Object.keys(t.bindings)){const r=t.bindings[e];console.log(" -",e,{constant:r.constant,references:r.references,violations:r.constantViolations.length,kind:r.kind})}}while(t=t.parent);console.log(e)}hasLabel(e){return!!this.getLabel(e)}getLabel(e){return this.labels.get(e)}registerLabel(e){this.labels.set(e.node.label.name,e)}registerDeclaration(e){if(e.isLabeledStatement())this.registerLabel(e);else if(e.isFunctionDeclaration())this.registerBinding("hoisted",e.get("id"),e);else if(e.isVariableDeclaration()){const t=e.get("declarations"),{kind:r}=e.node;for(const e of t)this.registerBinding("using"===r||"await using"===r?"const":r,e)}else if(e.isClassDeclaration()){if(e.node.declare)return;this.registerBinding("let",e)}else if(e.isImportDeclaration()){const t="type"===e.node.importKind||"typeof"===e.node.importKind,r=e.get("specifiers");for(const e of r){const r=t||e.isImportSpecifier()&&("type"===e.node.importKind||"typeof"===e.node.importKind);this.registerBinding(r?"unknown":"module",e)}}else if(e.isExportDeclaration()){const t=e.get("declaration");(t.isClassDeclaration()||t.isFunctionDeclaration()||t.isVariableDeclaration())&&this.registerDeclaration(t)}else this.registerBinding("unknown",e)}buildUndefinedNode(){return se()}registerConstantViolation(e){const t=e.getAssignmentIdentifiers();for(const n of Object.keys(t)){var r;null==(r=this.getBinding(n))||r.reassign(e)}}registerBinding(e,t,r=t){if(!e)throw new ReferenceError("no `kind`");if(t.isVariableDeclaration()){const r=t.get("declarations");for(const t of r)this.registerBinding(e,t);return}const n=this.getProgramParent(),s=t.getOuterBindingIdentifiers(!0);for(const t of Object.keys(s)){n.references[t]=!0;for(const n of s[t]){const s=this.getOwnBinding(t);if(s){if(s.identifier===n)continue;this.checkBlockScopedCollisions(s,e,t,n)}s?s.reassign(r):this.bindings[t]=new i.default({identifier:n,scope:this,path:r,kind:e})}}}addGlobal(e){this.globals[e.name]=e}hasUid(e){let t=this;do{if(t.uids[e])return!0}while(t=t.parent);return!1}hasGlobal(e){let t=this;do{if(t.globals[e])return!0}while(t=t.parent);return!1}hasReference(e){return!!this.getProgramParent().references[e]}isPure(e,t){if(C(e)){const r=this.getBinding(e.name);return!!r&&(!t||r.constant)}if(V(e)||te(e)||ee(e)||re(e))return!0;var r,n,s;if(T(e))return!(e.superClass&&!this.isPure(e.superClass,t))&&!((null==(r=e.decorators)?void 0:r.length)>0)&&this.isPure(e.body,t);if(x(e)){for(const r of e.body)if(!this.isPure(r,t))return!1;return!0}if(b(e))return this.isPure(e.left,t)&&this.isPure(e.right,t);if(g(e)||Q(e)){for(const r of e.elements)if(null!==r&&!this.isPure(r,t))return!1;return!0}if(j(e)||X(e)){for(const r of e.properties)if(!this.isPure(r,t))return!1;return!0}if(k(e))return!(e.computed&&!this.isPure(e.key,t)||(null==(n=e.decorators)?void 0:n.length)>0);if(B(e))return!(e.computed&&!this.isPure(e.key,t)||(null==(s=e.decorators)?void 0:s.length)>0||(Z(e)||e.static)&&null!==e.value&&!this.isPure(e.value,t));if(q(e))return this.isPure(e.argument,t);if(U(e)){for(const r of e.expressions)if(!this.isPure(r,t))return!1;return!0}return R(e)?$(e.tag,"String.raw")&&!this.hasBinding("String",{noGlobals:!0})&&this.isPure(e.quasi,t):N(e)?!e.computed&&C(e.object)&&"Symbol"===e.object.name&&C(e.property)&&"for"!==e.property.name&&!this.hasBinding("Symbol",{noGlobals:!0}):v(e)?$(e.callee,"Symbol.for")&&!this.hasBinding("Symbol",{noGlobals:!0})&&1===e.arguments.length&&l.isStringLiteral(e.arguments[0]):M(e)}setData(e,t){return this.data[e]=t}getData(e){let t=this;do{const r=t.data[e];if(null!=r)return r}while(t=t.parent)}removeData(e){let t=this;do{null!=t.data[e]&&(t.data[e]=null)}while(t=t.parent)}init(){this.inited||(this.inited=!0,this.crawl())}crawl(){const e=this.path;this.references=Object.create(null),this.bindings=Object.create(null),this.globals=Object.create(null),this.uids=Object.create(null),this.data=Object.create(null);let t=this;do{if(t.crawling)return;if(t.path.isProgram())break}while(t=t.parent);const r=t,n={references:[],constantViolations:[],assignments:[]};if(this.crawling=!0,"Program"!==e.type&&(0,p.isExplodedVisitor)(oe)){for(const t of oe.enter)t.call(n,e,n);const t=oe[e.type];if(t)for(const r of t.enter)r.call(n,e,n)}e.traverse(oe,n),this.crawling=!1;for(const e of n.assignments){const t=e.getAssignmentIdentifiers();for(const n of Object.keys(t))e.scope.getBinding(n)||r.addGlobal(t[n]);e.scope.registerConstantViolation(e)}for(const e of n.references){const t=e.scope.getBinding(e.node.name);t?t.reference(e):r.addGlobal(e.node)}for(const e of n.constantViolations)e.scope.registerConstantViolation(e)}push(e){let t=this.path;t.isPattern()?t=this.getPatternParent().path:t.isBlockStatement()||t.isProgram()||(t=this.getBlockParent().path),t.isSwitchStatement()&&(t=(this.getFunctionParent()||this.getProgramParent()).path);const{init:r,unique:n,kind:s="var",id:i}=e;if(!r&&!n&&("var"===s||"let"===s)&&t.isFunction()&&!t.node.name&&v(t.parent,{callee:t.node})&&t.parent.arguments.length<=t.node.params.length&&C(i))return t.pushContainer("params",i),void t.scope.registerBinding("param",t.get("params")[t.node.params.length-1]);(t.isLoop()||t.isCatchClause()||t.isFunction())&&(t.ensureBlock(),t=t.get("body"));const a=null==e._blockHoist?2:e._blockHoist,o=`declaration:${s}:${a}`;let l=!n&&t.getData(o);if(!l){const e=J(s,[]);e._blockHoist=a,[l]=t.unshiftContainer("body",[e]),n||t.setData(o,l)}const c=z(i,r),p=l.node.declarations.push(c);t.scope.registerBinding(s,l.get("declarations")[p-1])}getProgramParent(){let e=this;do{if(e.path.isProgram())return e}while(e=e.parent);throw new Error("Couldn't find a Program")}getFunctionParent(){let e=this;do{if(e.path.isFunctionParent())return e}while(e=e.parent);return null}getBlockParent(){let e=this;do{if(e.path.isBlockParent())return e}while(e=e.parent);throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...")}getPatternParent(){let e=this;do{if(!e.path.isPattern())return e.getBlockParent()}while(e=e.parent.parent);throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...")}getAllBindings(){const e=Object.create(null);let t=this;do{for(const r of Object.keys(t.bindings))r in e==0&&(e[r]=t.bindings[r]);t=t.parent}while(t);return e}bindingIdentifierEquals(e,t){return this.getBindingIdentifier(e)===t}getBinding(e){let t,r=this;do{const s=r.getOwnBinding(e);var n;if(s){if(null==(n=t)||!n.isPattern()||"param"===s.kind||"local"===s.kind)return s}else if(!s&&"arguments"===e&&r.path.isFunction()&&!r.path.isArrowFunctionExpression())break;t=r.path}while(r=r.parent)}getOwnBinding(e){return this.bindings[e]}getBindingIdentifier(e){var t;return null==(t=this.getBinding(e))?void 0:t.identifier}getOwnBindingIdentifier(e){const t=this.bindings[e];return null==t?void 0:t.identifier}hasOwnBinding(e){return!!this.getOwnBinding(e)}hasBinding(e,t){if(!e)return!1;let r,n,s=this;do{if(s.hasOwnBinding(e))return!0}while(s=s.parent);return"object"==typeof t?(r=t.noGlobals,n=t.noUids):"boolean"==typeof t&&(r=t),!(n||!this.hasUid(e))||!(r||!ce.globals.includes(e))||!(r||!ce.contextVariables.includes(e))}parentHasBinding(e,t){var r;return null==(r=this.parent)?void 0:r.hasBinding(e,t)}moveBindingTo(e,t){const r=this.getBinding(e);r&&(r.scope.removeOwnBinding(e),r.scope=t,t.bindings[e]=r)}removeOwnBinding(e){delete this.bindings[e]}removeBinding(e){var t;null==(t=this.getBinding(e))||t.scope.removeOwnBinding(e);let r=this;do{r.uids[e]&&(r.uids[e]=!1)}while(r=r.parent)}hoistVariables(e=e=>this.push({id:e})){this.crawl();const t=new Set;for(const r of Object.keys(this.bindings)){const n=this.bindings[r];if(!n)continue;const{path:s}=n;if(!s.isVariableDeclarator())continue;const{parent:i,parentPath:a}=s;if("var"!==i.kind||t.has(i))continue;let o;t.add(s.parent);const l=[];for(const t of i.declarations){null!=o||(o=t.id),t.init&&l.push(d("=",t.id,t.init));const r=Object.keys(m(t,!1,!0,!0));for(const n of r)e(y(n),null!=t.init)}if(a.parentPath.isFor({left:i}))a.replaceWith(o);else if(0===l.length)a.remove();else{const e=1===l.length?l[0]:ie(l);a.parentPath.isForStatement({init:i})?a.replaceWith(e):a.replaceWith(K(e))}}}}t.default=ce,ce.globals=Object.keys(a.builtin),ce.contextVariables=["arguments","undefined","Infinity","NaN"],ce.prototype._renameFromMap=function(e,t,r,n){e[t]&&(e[r]=n,e[t]=null)},ce.prototype.traverse=function(e,t,r){(0,s.default)(e,t,this,r,this.path)},ce.prototype._generateUid=function(e,t){let r=e;return t>1&&(r+=t),`_${r}`},ce.prototype.toArray=function(e,t,r){if(C(e)){const t=this.getBinding(e.name);if(null!=t&&t.constant&&t.path.isGenericType("Array"))return e}if(g(e))return e;if(C(e,{name:"arguments"}))return f(G(G(G(y("Array"),y("prototype")),y("slice")),y("call")),[e]);let n;const s=[e];return!0===t?n="toConsumableArray":"number"==typeof t?(s.push(H(t)),n="slicedToArray"):n="toArray",r&&(s.unshift(this.path.hub.addHelper(n)),n="maybeArrayLike"),f(this.path.hub.addHelper(n),s)},ce.prototype.getAllBindingsOfKind=function(...e){const t=Object.create(null);for(const r of e){let e=this;do{for(const n of Object.keys(e.bindings)){const s=e.bindings[n];s.kind===r&&(t[n]=s)}e=e.parent}while(e)}return t},Object.defineProperties(ce.prototype,{parentBlock:{configurable:!0,enumerable:!0,get(){return this.path.parent}},hub:{configurable:!0,enumerable:!0,get(){return this.path.hub}}})},6818:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return"module"===e.node.sourceType}},6871:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildDynamicImport=function(e,t,r,s){const i=n.types.isCallExpression(e)?e.arguments[0]:e.source;if(n.types.isStringLiteral(i)||n.types.isTemplateLiteral(i)&&0===i.quasis.length)return t?n.template.expression.ast` - Promise.resolve().then(() => ${s(i)}) - `:s(i);const a=n.types.isTemplateLiteral(i)?n.types.identifier("specifier"):n.types.templateLiteral([n.types.templateElement({raw:""}),n.types.templateElement({raw:""})],[n.types.identifier("specifier")]);return t?n.template.expression.ast` - (specifier => - new Promise(r => r(${a})) - .then(s => ${s(n.types.identifier("s"))}) - )(${i}) - `:r?n.template.expression.ast` - (specifier => - new Promise(r => r(${s(a)})) - )(${i}) - `:n.template.expression.ast` - (specifier => ${s(a)})(${i}) - `};var n=r(6416);t.getDynamicImportSource=function(e){const[t]=e.arguments;return n.types.isStringLiteral(t)||n.types.isTemplateLiteral(t)?t:n.template.expression.ast`\`\${${t}}\``}},6884:(e,t,r)=>{"use strict";function n(){const e=r(7298);return n=function(){return e},e}function s(e){return Object.assign({},e,{sourceRoot:null})}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){const i=r.replace(/\\/g,"/");let a=!1;const o=n()(s(t),((t,r)=>t!==i||a?null:(a=!0,r.source="",s(e))));return"string"==typeof e.sourceRoot&&(o.sourceRoot=e.sourceRoot),Object.assign({},o)}},6890:(e,t,r)=>{"use strict";function n(){const e=r(5345);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.makeConfigAPI=a,t.makePluginAPI=function(e,t){return Object.assign({},o(e,t),{assumption:t=>e.using((e=>e.assumptions[t]))})},t.makePresetAPI=o;var s=r(6416),i=r(1310);function a(e){return{version:s.version,cache:e.simple(),env:t=>e.using((e=>void 0===t?e.envName:"function"==typeof t?(0,i.assertSimpleType)(t(e.envName)):(Array.isArray(t)?t:[t]).some((t=>{if("string"!=typeof t)throw new Error("Unexpected non-string value");return t===e.envName})))),async:()=>!1,caller:t=>e.using((e=>(0,i.assertSimpleType)(t(e.caller)))),assertVersion:l}}function o(e,t){return Object.assign({},a(e),{targets:()=>JSON.parse(e.using((e=>JSON.stringify(e.targets)))),addExternalDependency:e=>{t.push(e)}})}function l(e){if("number"==typeof e){if(!Number.isInteger(e))throw new Error("Expected string or integer value.");e=`^${e}.0.0-0`}if("string"!=typeof e)throw new Error("Expected string or integer value.");if("*"===e||n().satisfies(s.version,e))return;const t=Error.stackTraceLimit;"number"==typeof t&&t<25&&(Error.stackTraceLimit=25);const r=new Error(`Requires Babel "${e}", but was loaded with "${s.version}". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel.`);throw"number"==typeof t&&(Error.stackTraceLimit=t),Object.assign(r,{code:"BABEL_VERSION_UNSUPPORTED",version:s.version,range:e})}},6897:(e,t,r)=>{"use strict";var n=r(453),s=r(41),i=r(592)(),a=r(5795),o=r(9675),l=n("%Math.floor%");e.exports=function(e,t){if("function"!=typeof e)throw new o("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||l(t)!==t)throw new o("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],n=!0,c=!0;if("length"in e&&a){var p=a(e,"length");p&&!p.configurable&&(n=!1),p&&!p.writable&&(c=!1)}return(n||c||!r)&&(i?s(e,"length",t,!0,!0):s(e,"length",t)),e}},6955:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.createConfigItem=function(e,t,r){if(void 0!==r)(0,o.beginHiddenCallStack)(d.errback)(e,t,r);else{if("function"!=typeof t)return f(e,t);(0,o.beginHiddenCallStack)(d.errback)(e,void 0,r)}},t.createConfigItemAsync=function(...e){return(0,o.beginHiddenCallStack)(d.async)(...e)},t.createConfigItemSync=f,Object.defineProperty(t,"default",{enumerable:!0,get:function(){return s.default}}),t.loadOptions=function(e,t){if(void 0!==t)(0,o.beginHiddenCallStack)(p.errback)(e,t);else{if("function"!=typeof e)return u(e);(0,o.beginHiddenCallStack)(p.errback)(void 0,e)}},t.loadOptionsAsync=function(...e){return(0,o.beginHiddenCallStack)(p.async)(...e)},t.loadOptionsSync=u,t.loadPartialConfig=function(e,t){if(void 0!==t)(0,o.beginHiddenCallStack)(l.errback)(e,t);else{if("function"!=typeof e)return c(e);(0,o.beginHiddenCallStack)(l.errback)(void 0,e)}},t.loadPartialConfigAsync=function(...e){return(0,o.beginHiddenCallStack)(l.async)(...e)},t.loadPartialConfigSync=c;var s=r(2110),i=r(2610),a=r(6140),o=r(1339);const l=n()(i.loadPartialConfig);function c(...e){return(0,o.beginHiddenCallStack)(l.sync)(...e)}const p=n()((function*(e){var t;const r=yield*(0,s.default)(e);return null!=(t=null==r?void 0:r.options)?t:null}));function u(...e){return(0,o.beginHiddenCallStack)(p.sync)(...e)}const d=n()(a.createConfigItem);function f(...e){return(0,o.beginHiddenCallStack)(d.sync)(...e)}},7003:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(t,r){if("object"!=typeof t||"object"!=typeof r||null==t||null==r)return t===r;if(t.type!==r.type)return!1;const s=Object.keys(n.NODE_FIELDS[t.type]||t.type),i=n.VISITOR_KEYS[t.type];for(const n of s){const s=t[n],a=r[n];if(typeof s!=typeof a)return!1;if(null!=s||null!=a){if(null==s||null==a)return!1;if(Array.isArray(s)){if(!Array.isArray(a))return!1;if(s.length!==a.length)return!1;for(let t=0;t<s.length;t++)if(!e(s[t],a[t]))return!1}else if("object"!=typeof s||null!=i&&i.includes(n)){if(!e(s,a))return!1}else for(const e of Object.keys(s))if(s[e]!==a[e])return!1}}return!0};var n=r(9793)},7095:(e,t,r)=>{"use strict";var n=r(5606),s=r(7596);(0,s.default)("ArgumentPlaceholder",{}),(0,s.default)("BindExpression",{visitor:["object","callee"],aliases:["Expression"],fields:n.env.BABEL_TYPES_8_BREAKING?{object:{validate:(0,s.assertNodeType)("Expression")},callee:{validate:(0,s.assertNodeType)("Expression")}}:{object:{validate:Object.assign((()=>{}),{oneOfNodeTypes:["Expression"]})},callee:{validate:Object.assign((()=>{}),{oneOfNodeTypes:["Expression"]})}}}),(0,s.default)("ImportAttribute",{visitor:["key","value"],fields:{key:{validate:(0,s.assertNodeType)("Identifier","StringLiteral")},value:{validate:(0,s.assertNodeType)("StringLiteral")}}}),(0,s.default)("Decorator",{visitor:["expression"],fields:{expression:{validate:(0,s.assertNodeType)("Expression")}}}),(0,s.default)("DoExpression",{visitor:["body"],builder:["body","async"],aliases:["Expression"],fields:{body:{validate:(0,s.assertNodeType)("BlockStatement")},async:{validate:(0,s.assertValueType)("boolean"),default:!1}}}),(0,s.default)("ExportDefaultSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:(0,s.assertNodeType)("Identifier")}}}),(0,s.default)("RecordExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:(0,s.validateArrayOfType)("ObjectProperty","SpreadElement")}}),(0,s.default)("TupleExpression",{fields:{elements:{validate:(0,s.arrayOfType)("Expression","SpreadElement"),default:[]}},visitor:["elements"],aliases:["Expression"]}),(0,s.default)("DecimalLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,s.default)("ModuleExpression",{visitor:["body"],fields:{body:{validate:(0,s.assertNodeType)("Program")}},aliases:["Expression"]}),(0,s.default)("TopicReference",{aliases:["Expression"]}),(0,s.default)("PipelineTopicExpression",{builder:["expression"],visitor:["expression"],fields:{expression:{validate:(0,s.assertNodeType)("Expression")}},aliases:["Expression"]}),(0,s.default)("PipelineBareFunction",{builder:["callee"],visitor:["callee"],fields:{callee:{validate:(0,s.assertNodeType)("Expression")}},aliases:["Expression"]}),(0,s.default)("PipelinePrimaryTopicReference",{aliases:["Expression"]})},7119:e=>{"use strict";e.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},7145:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(2352),s=n;const{react:i}=n,{cloneNode:a,jsxExpressionContainer:o,variableDeclaration:l,variableDeclarator:c}=s,p={ReferencedIdentifier(e,t){if(e.isJSXIdentifier()&&i.isCompatTag(e.node.name)&&!e.parentPath.isJSXMemberExpression())return;if("this"===e.node.name){let r=e.scope;do{if(r.path.isFunction()&&!r.path.isArrowFunctionExpression())break}while(r=r.parent);r&&t.breakOnScopePaths.push(r.path)}const r=e.scope.getBinding(e.node.name);if(r){for(const n of r.constantViolations)if(n.scope!==r.path.scope)return t.mutableBinding=!0,void e.stop();r===t.scope.getBinding(e.node.name)&&(t.bindings[e.node.name]=r)}}};t.default=class{constructor(e,t){this.breakOnScopePaths=void 0,this.bindings=void 0,this.mutableBinding=void 0,this.scopes=void 0,this.scope=void 0,this.path=void 0,this.attachAfter=void 0,this.breakOnScopePaths=[],this.bindings={},this.mutableBinding=!1,this.scopes=[],this.scope=t,this.path=e,this.attachAfter=!1}isCompatibleScope(e){for(const t of Object.keys(this.bindings)){const r=this.bindings[t];if(!e.bindingIdentifierEquals(t,r.identifier))return!1}return!0}getCompatibleScopes(){let e=this.path.scope;do{if(!this.isCompatibleScope(e))break;if(this.scopes.push(e),this.breakOnScopePaths.includes(e.path))break}while(e=e.parent)}getAttachmentPath(){let e=this._getAttachmentPath();if(!e)return;let t=e.scope;if(t.path===e&&(t=e.scope.parent),t.path.isProgram()||t.path.isFunction())for(const r of Object.keys(this.bindings)){if(!t.hasOwnBinding(r))continue;const n=this.bindings[r];if("param"!==n.kind&&"params"!==n.path.parentKey&&this.getAttachmentParentForPath(n.path).key>=e.key){this.attachAfter=!0,e=n.path;for(const t of n.constantViolations)this.getAttachmentParentForPath(t).key>e.key&&(e=t)}}return e}_getAttachmentPath(){const e=this.scopes.pop();if(e)if(e.path.isFunction()){if(!this.hasOwnParamBindings(e))return this.getNextScopeAttachmentParent();{if(this.scope===e)return;const t=e.path.get("body").get("body");for(let e=0;e<t.length;e++)if(!t[e].node._blockHoist)return t[e]}}else if(e.path.isProgram())return this.getNextScopeAttachmentParent()}getNextScopeAttachmentParent(){const e=this.scopes.pop();if(e)return this.getAttachmentParentForPath(e.path)}getAttachmentParentForPath(e){do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement())return e}while(e=e.parentPath)}hasOwnParamBindings(e){for(const t of Object.keys(this.bindings)){if(!e.hasOwnBinding(t))continue;const r=this.bindings[t];if("param"===r.kind&&r.constant)return!0}return!1}run(){if(this.path.traverse(p,this),this.mutableBinding)return;this.getCompatibleScopes();const e=this.getAttachmentPath();if(!e)return;if(e.getFunctionParent()===this.path.getFunctionParent())return;let t=e.scope.generateUidIdentifier("ref");const r=c(t,this.path.node),n=this.attachAfter?"insertAfter":"insertBefore",[s]=e[n]([e.isVariableDeclarator()?r:l("var",[r])]),i=this.path.parentPath;return i.isJSXElement()&&this.path.container===i.node.children&&(t=o(t)),this.path.replaceWith(a(t)),e.isVariableDeclarator()?s.get("init"):s.get("declarations.0.init")}}},7159:e=>{"use strict";const t={},r=t.hasOwnProperty,n=(e,t)=>{for(const n in e)r.call(e,n)&&t(n,e[n])},s=e=>"\\u"+("0000"+e).slice(-4),i=(e,t)=>{let r=e.toString(16);return t?r:r.toUpperCase()},a=t.toString,o=Array.isArray,l=e=>"bigint"==typeof e,c={"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},p=/[\\\b\f\n\r\t]/,u=/[0-9]/,d=/[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,f=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^]/g,h=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^ !#-&\(-\[\]-_a-~]/g,m=(e,t)=>{const r=()=>{P=E,++t.indentLevel,E=t.indent.repeat(t.indentLevel)},y={escapeEverything:!1,minimal:!1,isScriptContext:!1,quotes:"single",wrap:!1,es6:!1,json:!1,compact:!0,lowercaseHex:!1,numbers:"decimal",indent:"\t",indentLevel:0,__inline1__:!1,__inline2__:!1},g=t&&t.json;var b,v;g&&(y.quotes="double",y.wrap=!0),b=y,"single"!=(t=(v=t)?(n(v,((e,t)=>{b[e]=t})),b):b).quotes&&"double"!=t.quotes&&"backtick"!=t.quotes&&(t.quotes="single");const T="double"==t.quotes?'"':"backtick"==t.quotes?"`":"'",x=t.compact,S=t.lowercaseHex;let E=t.indent.repeat(t.indentLevel),P="";const A=t.__inline1__,w=t.__inline2__,C=x?"":"\n";let O,I=!0;const N="binary"==t.numbers,k="octal"==t.numbers,_="decimal"==t.numbers,D="hexadecimal"==t.numbers;if(g&&e&&(e=>"function"==typeof e)(e.toJSON)&&(e=e.toJSON()),!(e=>"string"==typeof e||"[object String]"==a.call(e))(e)){if((e=>"[object Map]"==a.call(e))(e))return 0==e.size?"new Map()":(x||(t.__inline1__=!0,t.__inline2__=!1),"new Map("+m(Array.from(e),t)+")");if((e=>"[object Set]"==a.call(e))(e))return 0==e.size?"new Set()":"new Set("+m(Array.from(e),t)+")";if((e=>"function"==typeof Buffer&&Buffer.isBuffer(e))(e))return 0==e.length?"Buffer.from([])":"Buffer.from("+m(Array.from(e),t)+")";if(o(e))return O=[],t.wrap=!0,A&&(t.__inline1__=!1,t.__inline2__=!0),w||r(),((e,t)=>{const r=e.length;let n=-1;for(;++n<r;)t(e[n])})(e,(e=>{I=!1,w&&(t.__inline2__=!1),O.push((x||w?"":E)+m(e,t))})),I?"[]":w?"["+O.join(", ")+"]":"["+C+O.join(","+C)+C+(x?"":P)+"]";if((e=>"number"==typeof e||"[object Number]"==a.call(e))(e)||l(e)){if(g)return JSON.stringify(Number(e));let t;if(_)t=String(e);else if(D){let r=e.toString(16);S||(r=r.toUpperCase()),t="0x"+r}else N?t="0b"+e.toString(2):k&&(t="0o"+e.toString(8));return l(e)?t+"n":t}return l(e)?g?JSON.stringify(Number(e)):e+"n":(e=>"[object Object]"==a.call(e))(e)?(O=[],t.wrap=!0,r(),n(e,((e,r)=>{I=!1,O.push((x?"":E)+m(e,t)+":"+(x?"":" ")+m(r,t))})),I?"{}":"{"+C+O.join(","+C)+C+(x?"":P)+"}"):g?JSON.stringify(e)||"null":String(e)}const j=t.escapeEverything?f:h;return O=e.replace(j,((e,r,n,a,o,l)=>{if(r){if(t.minimal)return r;const e=r.charCodeAt(0),n=r.charCodeAt(1);return t.es6?"\\u{"+i(1024*(e-55296)+n-56320+65536,S)+"}":s(i(e,S))+s(i(n,S))}if(n)return s(i(n.charCodeAt(0),S));if("\0"==e&&!g&&!u.test(l.charAt(o+1)))return"\\0";if(a)return a==T||t.escapeEverything?"\\"+a:a;if(p.test(e))return c[e];if(t.minimal&&!d.test(e))return e;const f=i(e.charCodeAt(0),S);return g||f.length>2?s(f):"\\x"+("00"+f).slice(-2)})),"`"==T&&(O=O.replace(/\$\{/g,"\\${")),t.isScriptContext&&(O=O.replace(/<\/(script|style)/gi,"<\\/$1").replace(/<!--/g,g?"\\u003C!--":"\\x3C!--")),t.wrap&&(O=T+O+T),O};m.version="3.0.2",e.exports=m},7165:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assumptionsNames=void 0,t.checkNoUnwrappedItemOptionPairs=function(e,t,r,n){if(0===t)return;const s=e[t-1],i=e[t];s.file&&void 0===s.options&&"object"==typeof i.value&&(n.message+=`\n- Maybe you meant to use\n"${r}s": [\n ["${s.file.request}", ${JSON.stringify(i.value,void 0,2)}]\n]\nTo be a valid ${r}, its name and options should be wrapped in a pair of brackets`)},t.validate=function(e,t,r){try{return u({type:"root",source:e},t)}catch(e){const t=new i.default(e.message,r);throw e.code&&(t.code=e.code),t}};var n=r(2911),s=r(4374),i=r(7445);const a={cwd:s.assertString,root:s.assertString,rootMode:s.assertRootMode,configFile:s.assertConfigFileSearch,caller:s.assertCallerMetadata,filename:s.assertString,filenameRelative:s.assertString,code:s.assertBoolean,ast:s.assertBoolean,cloneInputAst:s.assertBoolean,envName:s.assertString},o={babelrc:s.assertBoolean,babelrcRoots:s.assertBabelrcSearch},l={extends:s.assertString,ignore:s.assertIgnoreList,only:s.assertIgnoreList,targets:s.assertTargets,browserslistConfigFile:s.assertConfigFileSearch,browserslistEnv:s.assertString},c={inputSourceMap:s.assertInputSourceMap,presets:s.assertPluginList,plugins:s.assertPluginList,passPerPreset:s.assertBoolean,assumptions:s.assertAssumptions,env:function(e,t){if("env"===e.parent.type)throw new Error(`${(0,s.msg)(e)} is not allowed inside of another .env block`);const r=e.parent,n=(0,s.assertObject)(e,t);if(n)for(const t of Object.keys(n)){const i=(0,s.assertObject)((0,s.access)(e,t),n[t]);i&&u({type:"env",name:t,parent:r},i)}return n},overrides:function(e,t){if("env"===e.parent.type)throw new Error(`${(0,s.msg)(e)} is not allowed inside an .env block`);if("overrides"===e.parent.type)throw new Error(`${(0,s.msg)(e)} is not allowed inside an .overrides block`);const r=e.parent,n=(0,s.assertArray)(e,t);if(n)for(const[t,i]of n.entries()){const n=(0,s.access)(e,t),a=(0,s.assertObject)(n,i);if(!a)throw new Error(`${(0,s.msg)(n)} must be an object`);u({type:"overrides",index:t,parent:r},a)}return n},test:s.assertConfigApplicableTest,include:s.assertConfigApplicableTest,exclude:s.assertConfigApplicableTest,retainLines:s.assertBoolean,comments:s.assertBoolean,shouldPrintComment:s.assertFunction,compact:s.assertCompact,minified:s.assertBoolean,auxiliaryCommentBefore:s.assertString,auxiliaryCommentAfter:s.assertString,sourceType:s.assertSourceType,wrapPluginVisitorMethod:s.assertFunction,highlightCode:s.assertBoolean,sourceMaps:s.assertSourceMaps,sourceMap:s.assertSourceMaps,sourceFileName:s.assertString,sourceRoot:s.assertString,parserOpts:s.assertObject,generatorOpts:s.assertObject};function p(e){return"root"===e.type?e.source:p(e.parent)}function u(e,t){const r=p(e);return function(e){if(hasOwnProperty.call(e,"sourceMap")&&hasOwnProperty.call(e,"sourceMaps"))throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both")}(t),Object.keys(t).forEach((n=>{const i={type:"option",name:n,parent:e};if("preset"===r&&l[n])throw new Error(`${(0,s.msg)(i)} is not allowed in preset options`);if("arguments"!==r&&a[n])throw new Error(`${(0,s.msg)(i)} is only allowed in root programmatic options`);if("arguments"!==r&&"configfile"!==r&&o[n]){if("babelrcfile"===r||"extendsfile"===r)throw new Error(`${(0,s.msg)(i)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, or babel.config.js/config file options`);throw new Error(`${(0,s.msg)(i)} is only allowed in root programmatic options, or babel.config.js/config file options`)}(c[n]||l[n]||o[n]||a[n]||d)(i,t[n])})),t}function d(e){const t=e.name;if(n.default[t]){const{message:r,version:i=5}=n.default[t];throw new Error(`Using removed Babel ${i} option: ${(0,s.msg)(e)} - ${r}`)}{const t=new Error(`Unknown option: ${(0,s.msg)(e)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`);throw t.code="BABEL_UNKNOWN_OPTION",t}}Object.assign(c,{getModuleId:s.assertFunction,moduleRoot:s.assertString,moduleIds:s.assertBoolean,moduleId:s.assertString}),t.assumptionsNames=new Set(["arrayLikeIsIterable","constantReexports","constantSuper","enumerableModuleMeta","ignoreFunctionLength","ignoreToPrimitiveHint","iterableIsArray","mutableTemplateObject","noClassCalls","noDocumentAll","noIncompleteNsImportDetection","noNewArrows","noUninitializedPrivateFieldAccess","objectRestNoSymbols","privateFieldsAsSymbols","privateFieldsAsProperties","pureGetters","setClassMethods","setComputedProperties","setPublicClassFields","setSpreadProperties","skipForOfIteratorClosing","superIsCallableConstructor"])},7176:(e,t,r)=>{"use strict";var n,s=r(3126),i=r(5795);try{n=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var a=!!n&&i&&i(Object.prototype,"__proto__"),o=Object,l=o.getPrototypeOf;e.exports=a&&"function"==typeof a.get?s([a.get]):"function"==typeof l&&function(e){return l(null==e?e:o(e))}},7244:(e,t,r)=>{"use strict";var n=r(9092)(),s=r(6556)("Object.prototype.toString"),i=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===s(e)},a=function(e){return!!i(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==s(e)&&"callee"in e&&"[object Function]"===s(e.callee)},o=function(){return i(arguments)}();i.isLegacyArguments=a,e.exports=o?i:a},7262:(e,t,r)=>{"use strict";function n(){const e=r(2172);return n=function(){return e},e}function s(){const e=r(2882);return s=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function*(e,{parserOpts:t,highlightCode:r=!0,filename:a="unknown"},o){try{const r=[];for(const s of e)for(const e of s){const{parserOverride:s}=e;if(s){const e=s(o,t,n().parse);void 0!==e&&r.push(e)}}if(0===r.length)return(0,n().parse)(o,t);if(1===r.length){if(yield*[],"function"==typeof r[0].then)throw new Error("You appear to be using an async parser plugin, which your current version of Babel does not support. If you're using a published plugin, you may need to upgrade your @babel/core version.");return r[0]}throw new Error("More than one plugin attempted to override parsing.")}catch(e){"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"===e.code&&(e.message+="\nConsider renaming the file to '.mjs', or setting sourceType:module or sourceType:unambiguous in your Babel config for this file.");const{loc:t,missingPlugin:n}=e;if(t){const l=(0,s().codeFrameColumns)(o,{start:{line:t.line,column:t.column+1}},{highlightCode:r});e.message=n?`${a}: `+(0,i.default)(n[0],t,l,a):`${a}: ${e.message}\n\n`+l,e.code="BABEL_PARSE_ERROR"}throw e}};var i=r(7336)},7298:function(e,t,r){e.exports=function(e,t){"use strict";const r=s("",-1,-1,"",null,!1),n=[];function s(e,t,r,n,s,i){return{source:e,line:t,column:r,name:n,content:s,ignore:i}}function i(e,t,r,n,s){return{map:e,sources:t,source:r,content:n,ignore:s}}function a(e,t){return i(e,t,"",null,!1)}function o(t,n,i,a){if(!t.map)return s(t.source,n,i,a,t.content,t.ignore);const l=e.traceSegment(t.map,n,i);return null==l?null:1===l.length?r:o(t.sources[l[1]],l[2],l[3],5===l.length?t.map.names[l[4]]:a)}function l(t,r){const n=function(e){return Array.isArray(e)?e:[e]}(t).map((t=>new e.TraceMap(t,""))),s=n.pop();for(let e=0;e<n.length;e++)if(n[e].sources.length>1)throw new Error(`Transformation map ${e} must have exactly one source file.\nDid you specify these with the most recent transformation maps first?`);let i=c(s,r,"",0);for(let e=n.length-1;e>=0;e--)i=a(n[e],[i]);return i}function c(t,r,s,o){const{resolvedSources:l,sourcesContent:p,ignoreList:u}=t,d=o+1;return a(t,l.map(((t,a)=>{const o={importer:s,depth:d,source:t||"",content:void 0,ignore:void 0},l=r(o.source,o),{source:f,content:h,ignore:m}=o;return l?c(new e.TraceMap(l,f),r,f,d):function(e,t,r){return i(null,n,e,t,r)}(f,void 0!==h?h:p?p[a]:null,void 0!==m?m:!!u&&u.includes(a))})))}class p{constructor(e,r){const n=r.decodedMappings?t.toDecodedMap(e):t.toEncodedMap(e);this.version=n.version,this.file=n.file,this.mappings=n.mappings,this.names=n.names,this.ignoreList=n.ignoreList,this.sourceRoot=n.sourceRoot,this.sources=n.sources,r.excludeContent||(this.sourcesContent=n.sourcesContent)}toString(){return JSON.stringify(this)}}return function(n,s,i){const a="object"==typeof i?i:{excludeContent:!!i,decodedMappings:!1},c=l(n,s);return new p(function(n){const s=new t.GenMapping({file:n.map.file}),{sources:i,map:a}=n,l=a.names,c=e.decodedMappings(a);for(let e=0;e<c.length;e++){const n=c[e];for(let a=0;a<n.length;a++){const c=n[a],p=c[0];let u=r;if(1!==c.length&&(u=o(i[c[1]],c[2],c[3],5===c.length?l[c[4]]:""),null==u))continue;const{column:d,line:f,name:h,content:m,source:y,ignore:g}=u;t.maybeAddSegment(s,e,p,y,f,d,h),y&&null!=m&&t.setSourceContent(s,y,m),g&&t.setIgnore(s,y,!0)}}return s}(c),a)}}(r(2802),r(9320))},7317:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._getTypeAnnotation=w,t.baseTypeStrictlyMatches=function(e){const t=this.getTypeAnnotation(),r=e.getTypeAnnotation();return!(a(t)||!p(t))&&r.type===t.type},t.couldBeBaseType=function(e){const t=this.getTypeAnnotation();if(a(t))return!0;if(x(t)){for(const r of t.types)if(a(r)||C(e,r,!0))return!0;return!1}return C(e,t,!0)},t.getTypeAnnotation=function(){let e=this.getData("typeAnnotation");return null!=e||(e=w.call(this)||i(),(T(e)||g(e))&&(e=e.typeAnnotation),this.setData("typeAnnotation",e)),e},t.isBaseType=function(e,t){return C(e,this.getTypeAnnotation(),t)},t.isGenericType=function(e){const t=this.getTypeAnnotation();return!("Array"!==e||!(y(t)||o(t)||v(t)))||(u(t)&&d(t.id,{name:e})||b(t)&&d(t.typeName,{name:e}))};var n=r(9937),s=r(2352);const{anyTypeAnnotation:i,isAnyTypeAnnotation:a,isArrayTypeAnnotation:o,isBooleanTypeAnnotation:l,isEmptyTypeAnnotation:c,isFlowBaseAnnotation:p,isGenericTypeAnnotation:u,isIdentifier:d,isMixedTypeAnnotation:f,isNumberTypeAnnotation:h,isStringTypeAnnotation:m,isTSArrayType:y,isTSTypeAnnotation:g,isTSTypeReference:b,isTupleTypeAnnotation:v,isTypeAnnotation:T,isUnionTypeAnnotation:x,isVoidTypeAnnotation:S,stringTypeAnnotation:E,voidTypeAnnotation:P}=s,A=new WeakSet;function w(){const e=this.node;if(e){if(e.typeAnnotation)return e.typeAnnotation;if(!A.has(e)){A.add(e);try{var t;let r=n[e.type];if(r)return r.call(this,e);if(r=n[this.parentPath.type],null!=(t=r)&&t.validParent)return this.parentPath.getTypeAnnotation()}finally{A.delete(e)}}}else if("init"===this.key&&this.parentPath.isVariableDeclarator()){const e=this.parentPath.parentPath,t=e.parentPath;return"left"===e.key&&t.isForInStatement()?E():"left"===e.key&&t.isForOfStatement()?i():P()}}function C(e,t,r){if("string"===e)return m(t);if("number"===e)return h(t);if("boolean"===e)return l(t);if("any"===e)return a(t);if("mixed"===e)return f(t);if("empty"===e)return c(t);if("void"===e)return S(t);if(r)return!1;throw new Error(`Unknown base type ${e}`)}},7336:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,s,i){let a=`Support for the experimental syntax '${e}' isn't currently enabled (${t.line}:${t.column+1}):\n\n`+s;const o=r[e];if(o){const{syntax:e,transform:t}=o;if(e){const r=n(e);a+=t?`\n\nAdd ${n(t)} to the '${t.name.startsWith("@babel/plugin")?"plugins":"presets"}' section of your Babel config to enable transformation.\nIf you want to leave it as-is, add ${r} to the 'plugins' section to enable parsing.`:`\n\nAdd ${r} to the 'plugins' section of your Babel config to enable parsing.`}}return a+=`\n\nIf you already added the plugin for this syntax to your config, it's possible that your config isn't being loaded.\nYou can re-run Babel with the BABEL_SHOW_CONFIG_FOR environment variable to show the loaded configuration:\n\tnpx cross-env BABEL_SHOW_CONFIG_FOR=${"unknown"===i?"<name of the input file>":i} <your build command>\nSee https://babeljs.io/docs/configuration#print-effective-configs for more info.\n`,a};const r={asyncDoExpressions:{syntax:{name:"@babel/plugin-syntax-async-do-expressions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions"}},decimal:{syntax:{name:"@babel/plugin-syntax-decimal",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal"}},decorators:{syntax:{name:"@babel/plugin-syntax-decorators",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators"},transform:{name:"@babel/plugin-proposal-decorators",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators"}},doExpressions:{syntax:{name:"@babel/plugin-syntax-do-expressions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions"},transform:{name:"@babel/plugin-proposal-do-expressions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions"}},exportDefaultFrom:{syntax:{name:"@babel/plugin-syntax-export-default-from",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from"},transform:{name:"@babel/plugin-proposal-export-default-from",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from"}},flow:{syntax:{name:"@babel/plugin-syntax-flow",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow"},transform:{name:"@babel/preset-flow",url:"https://github.com/babel/babel/tree/main/packages/babel-preset-flow"}},functionBind:{syntax:{name:"@babel/plugin-syntax-function-bind",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind"},transform:{name:"@babel/plugin-proposal-function-bind",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind"}},functionSent:{syntax:{name:"@babel/plugin-syntax-function-sent",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent"},transform:{name:"@babel/plugin-proposal-function-sent",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent"}},jsx:{syntax:{name:"@babel/plugin-syntax-jsx",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx"},transform:{name:"@babel/preset-react",url:"https://github.com/babel/babel/tree/main/packages/babel-preset-react"}},pipelineOperator:{syntax:{name:"@babel/plugin-syntax-pipeline-operator",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator"},transform:{name:"@babel/plugin-proposal-pipeline-operator",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator"}},recordAndTuple:{syntax:{name:"@babel/plugin-syntax-record-and-tuple",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple"}},throwExpressions:{syntax:{name:"@babel/plugin-syntax-throw-expressions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions"},transform:{name:"@babel/plugin-proposal-throw-expressions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions"}},typescript:{syntax:{name:"@babel/plugin-syntax-typescript",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript"},transform:{name:"@babel/preset-typescript",url:"https://github.com/babel/babel/tree/main/packages/babel-preset-typescript"}}};Object.assign(r,{asyncGenerators:{syntax:{name:"@babel/plugin-syntax-async-generators",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-generators"},transform:{name:"@babel/plugin-transform-async-generator-functions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-async-generator-functions"}},classProperties:{syntax:{name:"@babel/plugin-syntax-class-properties",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties"},transform:{name:"@babel/plugin-transform-class-properties",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-class-properties"}},classPrivateProperties:{syntax:{name:"@babel/plugin-syntax-class-properties",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties"},transform:{name:"@babel/plugin-transform-class-properties",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-class-properties"}},classPrivateMethods:{syntax:{name:"@babel/plugin-syntax-class-properties",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties"},transform:{name:"@babel/plugin-transform-private-methods",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-private-methods"}},classStaticBlock:{syntax:{name:"@babel/plugin-syntax-class-static-block",url:"https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-syntax-class-static-block"},transform:{name:"@babel/plugin-transform-class-static-block",url:"https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-transform-class-static-block"}},dynamicImport:{syntax:{name:"@babel/plugin-syntax-dynamic-import",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-dynamic-import"}},exportNamespaceFrom:{syntax:{name:"@babel/plugin-syntax-export-namespace-from",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-namespace-from"},transform:{name:"@babel/plugin-transform-export-namespace-from",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-export-namespace-from"}},importAssertions:{syntax:{name:"@babel/plugin-syntax-import-assertions",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions"}},importAttributes:{syntax:{name:"@babel/plugin-syntax-import-attributes",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-attributes"}},importMeta:{syntax:{name:"@babel/plugin-syntax-import-meta",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-meta"}},logicalAssignment:{syntax:{name:"@babel/plugin-syntax-logical-assignment-operators",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-logical-assignment-operators"},transform:{name:"@babel/plugin-transform-logical-assignment-operators",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-logical-assignment-operators"}},moduleStringNames:{syntax:{name:"@babel/plugin-syntax-module-string-names",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-module-string-names"}},numericSeparator:{syntax:{name:"@babel/plugin-syntax-numeric-separator",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-numeric-separator"},transform:{name:"@babel/plugin-transform-numeric-separator",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-numeric-separator"}},nullishCoalescingOperator:{syntax:{name:"@babel/plugin-syntax-nullish-coalescing-operator",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-nullish-coalescing-operator"},transform:{name:"@babel/plugin-transform-nullish-coalescing-operator",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-nullish-coalescing-opearator"}},objectRestSpread:{syntax:{name:"@babel/plugin-syntax-object-rest-spread",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-object-rest-spread"},transform:{name:"@babel/plugin-transform-object-rest-spread",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-object-rest-spread"}},optionalCatchBinding:{syntax:{name:"@babel/plugin-syntax-optional-catch-binding",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-catch-binding"},transform:{name:"@babel/plugin-transform-optional-catch-binding",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-optional-catch-binding"}},optionalChaining:{syntax:{name:"@babel/plugin-syntax-optional-chaining",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-chaining"},transform:{name:"@babel/plugin-transform-optional-chaining",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-optional-chaining"}},privateIn:{syntax:{name:"@babel/plugin-syntax-private-property-in-object",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-private-property-in-object"},transform:{name:"@babel/plugin-transform-private-property-in-object",url:"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-private-property-in-object"}},regexpUnicodeSets:{syntax:{name:"@babel/plugin-syntax-unicode-sets-regex",url:"https://github.com/babel/babel/blob/main/packages/babel-plugin-syntax-unicode-sets-regex/README.md"},transform:{name:"@babel/plugin-transform-unicode-sets-regex",url:"https://github.com/babel/babel/blob/main/packages/babel-plugin-proposalunicode-sets-regex/README.md"}}});const n=({name:e,url:t})=>`${e} (${t})`},7372:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,{importInterop:s,initializeReexports:i=!1,getWrapperPayload:c,esNamespaceOnly:p=!1,filename:u}){t||(t=e.scope.generateUidIdentifier("exports").name);const d=new Set;!function(e){e.get("body").forEach((e=>{e.isExportDefaultDeclaration()&&(null!=e.splitExportDeclaration||(e.splitExportDeclaration=r(5781).NodePath.prototype.splitExportDeclaration),e.splitExportDeclaration())}))}(e);const{local:f,sources:h,hasExports:m}=function(e,{getWrapperPayload:t,initializeReexports:r},s){const i=function(e,t,r){const n=new Map;e.get("body").forEach((e=>{let r;if(e.isImportDeclaration())r="import";else{if(e.isExportDefaultDeclaration()&&(e=e.get("declaration")),e.isExportNamedDeclaration())if(e.node.declaration)e=e.get("declaration");else if(t&&e.node.source&&e.get("source").isStringLiteral())return void e.get("specifiers").forEach((e=>{l(e),n.set(e.get("local").node.name,"block")}));if(e.isFunctionDeclaration())r="hoisted";else if(e.isClassDeclaration())r="block";else if(e.isVariableDeclaration({kind:"var"}))r="var";else{if(!e.isVariableDeclaration())return;r="block"}}Object.keys(e.getOuterBindingIdentifiers()).forEach((e=>{n.set(e,r)}))}));const s=new Map,i=e=>{const t=e.node.name;let r=s.get(t);if(!r){const i=n.get(t);if(void 0===i)throw e.buildCodeFrameError(`Exporting local "${t}", which is not declared.`);r={names:[],kind:i},s.set(t,r)}return r};return e.get("body").forEach((e=>{if(!e.isExportNamedDeclaration()||!t&&e.node.source){if(e.isExportDefaultDeclaration()){const t=e.get("declaration");if(!t.isFunctionDeclaration()&&!t.isClassDeclaration())throw t.buildCodeFrameError("Unexpected default expression export.");i(t.get("id")).names.push("default")}}else if(e.node.declaration){const t=e.get("declaration"),r=t.getOuterBindingIdentifierPaths();Object.keys(r).forEach((e=>{if("__esModule"===e)throw t.buildCodeFrameError('Illegal export "__esModule".');i(r[e]).names.push(e)}))}else e.get("specifiers").forEach((e=>{const t=e.get("local"),n=e.get("exported"),s=i(t),a=o(n,r);if("__esModule"===a)throw n.buildCodeFrameError('Illegal export "__esModule".');s.names.push(a)}))})),s}(e,r,s),a=new Map,c=new Map,p=(t,r)=>{const s=t.value;let i=c.get(s);return i?a.get(s).push(r):(i={name:e.scope.generateUidIdentifier((0,n.basename)(s,(0,n.extname)(s))).name,interop:"none",loc:null,imports:new Map,importsNamespace:new Set,reexports:new Map,reexportNamespace:new Set,reexportAll:null,wrap:null,get lazy(){return"lazy"===this.wrap},referenced:!1},c.set(s,i),a.set(s,[r])),i};let u=!1;e.get("body").forEach((e=>{if(e.isImportDeclaration()){const t=p(e.node.source,e.node);t.loc||(t.loc=e.node.loc),e.get("specifiers").forEach((e=>{if(e.isImportDefaultSpecifier()){const r=e.get("local").node.name;t.imports.set(r,"default");const n=i.get(r);n&&(i.delete(r),n.names.forEach((e=>{t.reexports.set(e,"default")})),t.referenced=!0)}else if(e.isImportNamespaceSpecifier()){const r=e.get("local").node.name;t.importsNamespace.add(r);const n=i.get(r);n&&(i.delete(r),n.names.forEach((e=>{t.reexportNamespace.add(e)})),t.referenced=!0)}else if(e.isImportSpecifier()){const r=o(e.get("imported"),s),n=e.get("local").node.name;t.imports.set(n,r);const a=i.get(n);a&&(i.delete(n),a.names.forEach((e=>{t.reexports.set(e,r)})),t.referenced=!0)}}))}else if(e.isExportAllDeclaration()){u=!0;const t=p(e.node.source,e.node);t.loc||(t.loc=e.node.loc),t.reexportAll={loc:e.node.loc},t.referenced=!0}else if(e.isExportNamedDeclaration()&&e.node.source){u=!0;const t=p(e.node.source,e.node);t.loc||(t.loc=e.node.loc),e.get("specifiers").forEach((e=>{l(e);const r=o(e.get("local"),s),n=o(e.get("exported"),s);if(t.reexports.set(n,r),t.referenced=!0,"__esModule"===n)throw e.get("exported").buildCodeFrameError('Illegal export "__esModule".')}))}else(e.isExportNamedDeclaration()||e.isExportDefaultDeclaration())&&(u=!0)}));for(const e of c.values()){let t=!1,r=!1;e.importsNamespace.size>0&&(t=!0,r=!0),e.reexportAll&&(r=!0);for(const n of e.imports.values())"default"===n?t=!0:r=!0;for(const n of e.reexports.values())"default"===n?t=!0:r=!0;t&&r?e.interop="namespace":t&&(e.interop="default")}if(t)for(const[e,r]of c)r.wrap=t(e,r,a.get(e));return{hasExports:u,local:i,sources:c}}(e,{initializeReexports:i,getWrapperPayload:c},d);!function(e){e.get("body").forEach((e=>{if(e.isImportDeclaration())e.remove();else if(e.isExportNamedDeclaration())e.node.declaration?(e.node.declaration._blockHoist=e.node._blockHoist,e.replaceWith(e.node.declaration)):e.remove();else if(e.isExportDefaultDeclaration()){const t=e.get("declaration");if(!t.isFunctionDeclaration()&&!t.isClassDeclaration())throw t.buildCodeFrameError("Unexpected default expression export.");t._blockHoist=e.node._blockHoist,e.replaceWith(t)}else e.isExportAllDeclaration()&&e.remove()}))}(e);for(const[e,t]of h){const{importsNamespace:r,imports:n}=t;if(r.size>0&&0===n.size){const[e]=r;t.name=e}const i=a(s,e,u);"none"===i?t.interop="none":"node"===i&&"namespace"===t.interop?t.interop="node-namespace":"node"===i&&"default"===t.interop?t.interop="node-default":p&&"namespace"===t.interop&&(t.interop="default")}return{exportName:t,exportNameListName:null,hasExports:m,local:f,source:h,stringSpecifiers:d}},t.hasExports=function(e){return e.hasExports},t.isSideEffectImport=function(e){return 0===e.imports.size&&0===e.importsNamespace.size&&0===e.reexports.size&&0===e.reexportNamespace.size&&!e.reexportAll},t.validateImportInteropOption=i;var n=r(7975),s=r(1e3);function i(e){if("function"!=typeof e&&"none"!==e&&"babel"!==e&&"node"!==e)throw new Error(`.importInterop must be one of "none", "babel", "node", or a function returning one of those values (received ${e}).`);return e}function a(e,t,r){return"function"==typeof e?i(e(t,r)):e}function o(e,t){if(e.isIdentifier())return e.node.name;if(e.isStringLiteral()){const r=e.node.value;return(0,s.isIdentifierName)(r)||t.add(r),r}throw new Error(`Expected export specifier to be either Identifier or StringLiteral, got ${e.node.type}`)}function l(e){if(!e.isExportSpecifier())throw e.isExportNamespaceSpecifier()?e.buildCodeFrameError("Export namespace should be first transformed by `@babel/plugin-transform-export-namespace-from`."):e.buildCodeFrameError("Unexpected export specifier type")}},7411:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clear=function(){s(),i()},t.clearPath=s,t.clearScope=i,t.getCachedPaths=function(e,t){var n;return null==(n=r.get(a))?void 0:n.get(t)},t.getOrCreateCachedPaths=function(e,t){let n=r.get(a);n||r.set(a,n=new WeakMap);let s=n.get(t);return s||n.set(t,s=new Map),s},t.scope=t.path=void 0;let r=t.path=new WeakMap,n=t.scope=new WeakMap;function s(){t.path=r=new WeakMap}function i(){t.scope=n=new WeakMap}const a=Object.freeze({})},7427:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){const r=i(e.ast);return t&&(e.placeholders.forEach((e=>{if(!hasOwnProperty.call(t,e.name)){const t=e.name;throw new Error(`Error: No substitution given for "${t}". If this is not meant to be a\n placeholder you may want to consider passing one of the following options to @babel/template:\n - { placeholderPattern: false, placeholderWhitelist: new Set(['${t}'])}\n - { placeholderPattern: /^${t}$/ }`)}})),Object.keys(t).forEach((t=>{if(!e.placeholderNames.has(t))throw new Error(`Unknown substitution "${t}" given`)}))),e.placeholders.slice().reverse().forEach((e=>{try{!function(e,t,r){e.isDuplicate&&(Array.isArray(r)?r=r.map((e=>i(e))):"object"==typeof r&&(r=i(r)));const{parent:n,key:f,index:h}=e.resolve(t);if("string"===e.type){if("string"==typeof r&&(r=u(r)),!r||!p(r))throw new Error("Expected string substitution")}else if("statement"===e.type)void 0===h?r?Array.isArray(r)?r=s(r):"string"==typeof r?r=o(l(r)):c(r)||(r=o(r)):r=a():r&&!Array.isArray(r)&&("string"==typeof r&&(r=l(r)),c(r)||(r=o(r)));else if("param"===e.type){if("string"==typeof r&&(r=l(r)),void 0===h)throw new Error("Assertion failure.")}else if("string"==typeof r&&(r=l(r)),Array.isArray(r))throw new Error("Cannot replace single expression with an array.");function m(e,t,r){const n=e[t];e[t]=r,"Identifier"!==n.type&&"Placeholder"!==n.type||(n.typeAnnotation&&(r.typeAnnotation=n.typeAnnotation),n.optional&&(r.optional=n.optional),n.decorators&&(r.decorators=n.decorators))}if(void 0===h)d(n,f,r),m(n,f,r);else{const t=n[f].slice();"statement"===e.type||"param"===e.type?null==r?t.splice(h,1):Array.isArray(r)?t.splice(h,1,...r):m(t,h,r):m(t,h,r),d(n,f,t),n[f]=t}}(e,r,t&&t[e.name]||null)}catch(t){throw t.message=`@babel/template placeholder "${e.name}": ${t.message}`,t}})),r};var n=r(2352);const{blockStatement:s,cloneNode:i,emptyStatement:a,expressionStatement:o,identifier:l,isStatement:c,isStringLiteral:p,stringLiteral:u,validate:d}=n},7445:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(1339);class s extends Error{constructor(e,t){super(e),(0,n.expectedError)(this),t&&(0,n.injectVirtualStackFrame)(this,t)}}t.default=s},7446:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){if(!e)return;const a=n.NODE_FIELDS[e.type];if(!a)return;s(e,t,r,a[t]),i(e,t,r)},t.validateChild=i,t.validateField=s,t.validateInternal=function(e,t,r,s,i){if(null!=e&&e.validate&&(!e.optional||null!=s)&&(e.validate(t,r,s),i)){var a;const e=s.type;if(null==e)return;null==(a=n.NODE_PARENT_VALIDATIONS[e])||a.call(n.NODE_PARENT_VALIDATIONS,t,r,s)}};var n=r(9793);function s(e,t,r,n){null!=n&&n.validate&&(n.optional&&null==r||n.validate(e,t,r))}function i(e,t,r){var s;const i=null==r?void 0:r.type;null!=i&&(null==(s=n.NODE_PARENT_VALIDATIONS[i])||s.call(n.NODE_PARENT_VALIDATIONS,e,t,r))}},7591:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){switch(t.type){case"MemberExpression":case"OptionalMemberExpression":return t.property===e?!!t.computed:t.object===e;case"JSXMemberExpression":return t.object===e;case"VariableDeclarator":return t.init===e;case"ArrowFunctionExpression":return t.body===e;case"PrivateName":case"LabeledStatement":case"CatchClause":case"RestElement":case"BreakStatement":case"ContinueStatement":case"FunctionDeclaration":case"FunctionExpression":case"ExportNamespaceSpecifier":case"ExportDefaultSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ImportSpecifier":case"ImportAttribute":case"JSXAttribute":case"ObjectPattern":case"ArrayPattern":case"MetaProperty":return!1;case"ClassMethod":case"ClassPrivateMethod":case"ObjectMethod":return t.key===e&&!!t.computed;case"ObjectProperty":return t.key===e?!!t.computed:!r||"ObjectPattern"!==r.type;case"ClassProperty":case"ClassAccessorProperty":case"TSPropertySignature":return t.key!==e||!!t.computed;case"ClassPrivateProperty":case"ObjectTypeProperty":return t.key!==e;case"ClassDeclaration":case"ClassExpression":return t.superClass===e;case"AssignmentExpression":case"AssignmentPattern":return t.right===e;case"ExportSpecifier":return(null==r||!r.source)&&t.local===e;case"TSEnumMember":return t.id!==e}return!0}},7596:(e,t,r)=>{"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0}),t.VISITOR_KEYS=t.NODE_PARENT_VALIDATIONS=t.NODE_FIELDS=t.FLIPPED_ALIAS_KEYS=t.DEPRECATED_KEYS=t.BUILDER_KEYS=t.ALIAS_KEYS=void 0,t.arrayOf=m,t.arrayOfType=y,t.assertEach=g,t.assertNodeOrValueType=function(...e){function t(t,r,n){for(const a of e)if(f(n)===a||(0,s.default)(a,n))return void(0,i.validateChild)(t,r,n);throw new TypeError(`Property ${r} of ${t.type} expected node to be of a type ${JSON.stringify(e)} but instead got ${JSON.stringify(null==n?void 0:n.type)}`)}return t.oneOfNodeOrValueTypes=e,t},t.assertNodeType=b,t.assertOneOf=function(...e){function t(t,r,n){if(!e.includes(n))throw new TypeError(`Property ${r} expected value to be one of ${JSON.stringify(e)} but got ${JSON.stringify(n)}`)}return t.oneOf=e,t},t.assertOptionalChainStart=function(){return function(e){var t;let r=e;for(;e;){const{type:e}=r;if("OptionalCallExpression"!==e){if("OptionalMemberExpression"!==e)break;if(r.optional)return;r=r.object}else{if(r.optional)return;r=r.callee}}throw new TypeError(`Non-optional ${e.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${null==(t=r)?void 0:t.type}`)}},t.assertShape=function(e){function t(t,r,n){const s=[];for(const r of Object.keys(e))try{(0,i.validateField)(t,r,n[r],e[r])}catch(e){if(e instanceof TypeError){s.push(e.message);continue}throw e}if(s.length)throw new TypeError(`Property ${r} of ${t.type} expected to have the following:\n${s.join("\n")}`)}return t.shapeOf=e,t},t.assertValueType=v,t.chain=T,t.default=P,t.defineAliasedType=function(...e){return(t,r={})=>{let n=r.aliases;var s;n||(r.inherits&&(n=null==(s=E[r.inherits].aliases)?void 0:s.slice()),null!=n||(n=[]),r.aliases=n);const i=e.filter((e=>!n.includes(e)));n.unshift(...i),P(t,r)}},t.validate=h,t.validateArrayOfType=function(...e){return h(y(...e))},t.validateOptional=function(e){return{validate:e,optional:!0}},t.validateOptionalType=function(...e){return{validate:b(...e),optional:!0}},t.validateType=function(...e){return h(b(...e))};var s=r(3828),i=r(7446);const a=t.VISITOR_KEYS={},o=t.ALIAS_KEYS={},l=t.FLIPPED_ALIAS_KEYS={},c=t.NODE_FIELDS={},p=t.BUILDER_KEYS={},u=t.DEPRECATED_KEYS={},d=t.NODE_PARENT_VALIDATIONS={};function f(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function h(e){return{validate:e}}function m(e){return T(v("array"),g(e))}function y(...e){return m(b(...e))}function g(e){const t=n.env.BABEL_TYPES_8_BREAKING?i.validateChild:()=>{};function r(r,n,s){if(Array.isArray(s))for(let i=0;i<s.length;i++){const a=`${n}[${i}]`,o=s[i];e(r,a,o),t(r,a,o)}}return r.each=e,r}function b(...e){function t(t,r,n){for(const a of e)if((0,s.default)(a,n))return void(0,i.validateChild)(t,r,n);throw new TypeError(`Property ${r} of ${t.type} expected node to be of a type ${JSON.stringify(e)} but instead got ${JSON.stringify(null==n?void 0:n.type)}`)}return t.oneOfNodeTypes=e,t}function v(e){function t(t,r,n){if(f(n)!==e)throw new TypeError(`Property ${r} expected type of ${e} but got ${f(n)}`)}return t.type=e,t}function T(...e){function t(...t){for(const r of e)r(...t)}if(t.chainOf=e,e.length>=2&&"type"in e[0]&&"array"===e[0].type&&!("each"in e[1]))throw new Error('An assertValueType("array") validator can only be followed by an assertEach(...) validator.');return t}const x=new Set(["aliases","builder","deprecatedAlias","fields","inherits","visitor","validate"]),S=new Set(["default","optional","deprecated","validate"]),E={};function P(e,t={}){const r=t.inherits&&E[t.inherits]||{};let n=t.fields;if(!n&&(n={},r.fields)){const e=Object.getOwnPropertyNames(r.fields);for(const t of e){const e=r.fields[t],s=e.default;if(Array.isArray(s)?s.length>0:s&&"object"==typeof s)throw new Error("field defaults can only be primitives or empty arrays currently");n[t]={default:Array.isArray(s)?[]:s,optional:e.optional,deprecated:e.deprecated,validate:e.validate}}}const s=t.visitor||r.visitor||[],i=t.aliases||r.aliases||[],h=t.builder||r.builder||t.visitor||[];for(const r of Object.keys(t))if(!x.has(r))throw new Error(`Unknown type option "${r}" on ${e}`);t.deprecatedAlias&&(u[t.deprecatedAlias]=e);for(const e of s.concat(h))n[e]=n[e]||{};for(const t of Object.keys(n)){const r=n[t];void 0===r.default||h.includes(t)||(r.optional=!0),void 0===r.default?r.default=null:r.validate||null==r.default||(r.validate=v(f(r.default)));for(const n of Object.keys(r))if(!S.has(n))throw new Error(`Unknown field key "${n}" on ${e}.${t}`)}a[e]=t.visitor=s,p[e]=t.builder=h,c[e]=t.fields=n,o[e]=t.aliases=i,i.forEach((t=>{l[t]=l[t]||[],l[t].push(e)})),t.validate&&(d[e]=t.validate),E[e]=t}},7627:(e,t,r)=>{"use strict";e.exports=r(4652)},7639:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,n.default)(e,s.default,t),e};var n=r(8943),s=r(5333)},7653:(e,t,r)=>{"use strict";var n=r(8452),s=r(487),i=r(9211),a=r(9394),o=r(6576),l=s(a(),Object);n(l,{getPolyfill:a,implementation:i,shim:o}),e.exports=l},7726:e=>{"use strict";e.exports=URIError},7833:(e,t,r)=>{var n=r(5606);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},7860:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hooks=void 0,t.hooks=[function(e,t){if("test"===e.key&&(t.isWhile()||t.isSwitchCase())||"declaration"===e.key&&t.isExportDeclaration()||"body"===e.key&&t.isLabeledStatement()||"declarations"===e.listKey&&t.isVariableDeclaration()&&1===t.node.declarations.length||"expression"===e.key&&t.isExpressionStatement())return t.remove(),!0},function(e,t){if(t.isSequenceExpression()&&1===t.node.expressions.length)return t.replaceWith(t.node.expressions[0]),!0},function(e,t){if(t.isBinary())return"left"===e.key?t.replaceWith(t.node.right):t.replaceWith(t.node.left),!0},function(e,t){if(t.isIfStatement()&&"consequent"===e.key||"body"===e.key&&(t.isLoop()||t.isArrowFunctionExpression()))return e.replaceWith({type:"BlockStatement",body:[]}),!0}]},7878:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=class{getCode(){}getScope(){}addHelper(){throw new Error("Helpers are not supported by the default hub.")}buildError(e,t,r=TypeError){return new r(t)}}},7931:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t="body"){const r=(0,n.default)(e[t],e);return e[t]=r,r};var n=r(5010)},7932:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){(0,n.default)("innerComments",e,t)};var n=r(3205)},7942:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ArgumentPlaceholder=function(){this.tokenChar(63)},t.ArrayPattern=t.ArrayExpression=function(e){const t=e.elements,r=t.length;this.tokenChar(91);const n=this.enterDelimited();for(let e=0;e<t.length;e++){const n=t[e];n?(e>0&&this.space(),this.print(n),(e<r-1||this.shouldPrintTrailingComma("]"))&&this.token(",",!1,e)):this.token(",",!1,e)}n(),this.tokenChar(93)},t.BigIntLiteral=function(e){const t=this.getPossibleRaw(e);this.format.minified||void 0===t?this.word(e.value+"n"):this.word(t)},t.BooleanLiteral=function(e){this.word(e.value?"true":"false")},t.Identifier=function(e){var t;this.sourceIdentifierName((null==(t=e.loc)?void 0:t.identifierName)||e.name),this.word(this.tokenMap?this._getRawIdentifier(e):e.name)},t.NullLiteral=function(){this.word("null")},t.NumericLiteral=function(e){const t=this.getPossibleRaw(e),r=this.format.jsescOption,n=e.value,i=n+"";r.numbers?this.number(s(n,r),n):null==t?this.number(i,n):this.format.minified?this.number(t.length<i.length?t:i,n):this.number(t,n)},t.ObjectPattern=t.ObjectExpression=function(e){const t=e.properties;if(this.tokenChar(123),t.length){const e=this.enterDelimited();this.space(),this.printList(t,this.shouldPrintTrailingComma("}"),!0,!0),this.space(),e()}this.sourceWithOffset("end",e.loc,-1),this.tokenChar(125)},t.ObjectMethod=function(e){this.printJoin(e.decorators),this._methodHead(e),this.space(),this.print(e.body)},t.ObjectProperty=function(e){if(this.printJoin(e.decorators),e.computed)this.tokenChar(91),this.print(e.key),this.tokenChar(93);else{if(i(e.value)&&a(e.key)&&e.key.name===e.value.left.name)return void this.print(e.value);if(this.print(e.key),e.shorthand&&a(e.key)&&a(e.value)&&e.key.name===e.value.name)return}this.tokenChar(58),this.space(),this.print(e.value)},t.PipelineBareFunction=function(e){this.print(e.callee)},t.PipelinePrimaryTopicReference=function(){this.tokenChar(35)},t.PipelineTopicExpression=function(e){this.print(e.expression)},t.RecordExpression=function(e){const t=e.properties;let r,n;if("bar"===this.format.recordAndTupleSyntaxType)r="{|",n="|}";else{if("hash"!==this.format.recordAndTupleSyntaxType&&null!=this.format.recordAndTupleSyntaxType)throw new Error(`The "recordAndTupleSyntaxType" generator option must be "bar" or "hash" (${JSON.stringify(this.format.recordAndTupleSyntaxType)} received).`);r="#{",n="}"}this.token(r),t.length&&(this.space(),this.printList(t,this.shouldPrintTrailingComma(n),!0,!0),this.space()),this.token(n)},t.RegExpLiteral=function(e){this.word(`/${e.pattern}/${e.flags}`)},t.SpreadElement=t.RestElement=function(e){this.token("..."),this.print(e.argument)},t.StringLiteral=function(e){const t=this.getPossibleRaw(e);if(!this.format.minified&&void 0!==t)return void this.token(t);const r=s(e.value,this.format.jsescOption);this.token(r)},t.TopicReference=function(){const{topicToken:e}=this.format;if(!c.has(e)){const t=JSON.stringify(e),r=Array.from(c,(e=>JSON.stringify(e)));throw new Error(`The "topicToken" generator option must be one of ${r.join(", ")} (${t} received instead).`)}this.token(e)},t.TupleExpression=function(e){const t=e.elements,r=t.length;let n,s;if("bar"===this.format.recordAndTupleSyntaxType)n="[|",s="|]";else{if("hash"!==this.format.recordAndTupleSyntaxType)throw new Error(`${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`);n="#[",s="]"}this.token(n);for(let e=0;e<t.length;e++){const n=t[e];n&&(e>0&&this.space(),this.print(n),(e<r-1||this.shouldPrintTrailingComma(s))&&this.token(",",!1,e))}this.token(s)},t._getRawIdentifier=function(e){if(e===o)return l;o=e;const{name:t}=e,r=this.tokenMap.find(e,(e=>e.value===t));return r?(l=this._originalCode.slice(r.start,r.end),l):l=e.name};var n=r(2352),s=r(7159);const{isAssignmentPattern:i,isIdentifier:a}=n;let o=null,l="";const c=new Set(["^^","@@","^","%","#"])},7973:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isBindingIdentifier=function(){const{node:e,parent:t}=this,r=this.parentPath.parent;return u(e)&&s(e,t,r)},t.isBlockScoped=function(){return i(this.node)},t.isExpression=function(){return this.isIdentifier()?this.isReferencedIdentifier():o(this.node)},t.isFlow=function(){const{node:e}=this;return!(!l(e)&&(d(e)?"type"!==e.importKind&&"typeof"!==e.importKind:a(e)?"type"!==e.exportKind:!f(e)||"type"!==e.importKind&&"typeof"!==e.importKind))},t.isForAwaitStatement=function(){return P(this.node,{await:!0})},t.isGenerated=function(){return!this.isUser()},t.isPure=function(e){return this.scope.isPure(this.node,e)},t.isReferenced=function(){return b(this.node,this.parent)},t.isReferencedIdentifier=function(e){const{node:t,parent:r}=this;if(!u(t,e)&&!m(r,e)){if(!h(t,e))return!1;if(A(t.name))return!1}return b(t,r,this.parentPath.parent)},t.isReferencedMemberExpression=function(){const{node:e,parent:t}=this;return y(e)&&b(e,t)},t.isRestProperty=function(){var e;return g(this.node)&&(null==(e=this.parentPath)?void 0:e.isObjectPattern())},t.isScope=function(){return v(this.node,this.parent)},t.isSpreadProperty=function(){var e;return g(this.node)&&(null==(e=this.parentPath)?void 0:e.isObjectExpression())},t.isStatement=function(){const{node:e,parent:t}=this;if(T(e)){if(S(e)){if(p(t,{left:e}))return!1;if(c(t,{init:e}))return!1}return!0}return!1},t.isUser=function(){return this.node&&!!this.node.loc},t.isVar=function(){return x(this.node)};var n=r(2352);const{isBinding:s,isBlockScoped:i,isExportDeclaration:a,isExpression:o,isFlow:l,isForStatement:c,isForXStatement:p,isIdentifier:u,isImportDeclaration:d,isImportSpecifier:f,isJSXIdentifier:h,isJSXMemberExpression:m,isMemberExpression:y,isRestElement:g,isReferenced:b,isScope:v,isStatement:T,isVar:x,isVariableDeclaration:S,react:E,isForOfStatement:P}=n,{isCompatTag:A}=E;t.isExistentialTypeParam=function(){throw new Error("`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.")},t.isNumericLiteralTypeAnnotation=function(){throw new Error("`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.")}},7975:(e,t,r)=>{"use strict";var n=r(5606);function s(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function i(e,t){for(var r,n="",s=0,i=-1,a=0,o=0;o<=e.length;++o){if(o<e.length)r=e.charCodeAt(o);else{if(47===r)break;r=47}if(47===r){if(i===o-1||1===a);else if(i!==o-1&&2===a){if(n.length<2||2!==s||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var l=n.lastIndexOf("/");if(l!==n.length-1){-1===l?(n="",s=0):s=(n=n.slice(0,l)).length-1-n.lastIndexOf("/"),i=o,a=0;continue}}else if(2===n.length||1===n.length){n="",s=0,i=o,a=0;continue}t&&(n.length>0?n+="/..":n="..",s=2)}else n.length>0?n+="/"+e.slice(i+1,o):n=e.slice(i+1,o),s=o-i-1;i=o,a=0}else 46===r&&-1!==a?++a:a=-1}return n}var a={resolve:function(){for(var e,t="",r=!1,a=arguments.length-1;a>=-1&&!r;a--){var o;a>=0?o=arguments[a]:(void 0===e&&(e=n.cwd()),o=e),s(o),0!==o.length&&(t=o+"/"+t,r=47===o.charCodeAt(0))}return t=i(t,!r),r?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(e){if(s(e),0===e.length)return".";var t=47===e.charCodeAt(0),r=47===e.charCodeAt(e.length-1);return 0!==(e=i(e,!t)).length||t||(e="."),e.length>0&&r&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return s(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,t=0;t<arguments.length;++t){var r=arguments[t];s(r),r.length>0&&(void 0===e?e=r:e+="/"+r)}return void 0===e?".":a.normalize(e)},relative:function(e,t){if(s(e),s(t),e===t)return"";if((e=a.resolve(e))===(t=a.resolve(t)))return"";for(var r=1;r<e.length&&47===e.charCodeAt(r);++r);for(var n=e.length,i=n-r,o=1;o<t.length&&47===t.charCodeAt(o);++o);for(var l=t.length-o,c=i<l?i:l,p=-1,u=0;u<=c;++u){if(u===c){if(l>c){if(47===t.charCodeAt(o+u))return t.slice(o+u+1);if(0===u)return t.slice(o+u)}else i>c&&(47===e.charCodeAt(r+u)?p=u:0===u&&(p=0));break}var d=e.charCodeAt(r+u);if(d!==t.charCodeAt(o+u))break;47===d&&(p=u)}var f="";for(u=r+p+1;u<=n;++u)u!==n&&47!==e.charCodeAt(u)||(0===f.length?f+="..":f+="/..");return f.length>0?f+t.slice(o+p):(o+=p,47===t.charCodeAt(o)&&++o,t.slice(o))},_makeLong:function(e){return e},dirname:function(e){if(s(e),0===e.length)return".";for(var t=e.charCodeAt(0),r=47===t,n=-1,i=!0,a=e.length-1;a>=1;--a)if(47===(t=e.charCodeAt(a))){if(!i){n=a;break}}else i=!1;return-1===n?r?"/":".":r&&1===n?"//":e.slice(0,n)},basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');s(e);var r,n=0,i=-1,a=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var o=t.length-1,l=-1;for(r=e.length-1;r>=0;--r){var c=e.charCodeAt(r);if(47===c){if(!a){n=r+1;break}}else-1===l&&(a=!1,l=r+1),o>=0&&(c===t.charCodeAt(o)?-1==--o&&(i=r):(o=-1,i=l))}return n===i?i=l:-1===i&&(i=e.length),e.slice(n,i)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!a){n=r+1;break}}else-1===i&&(a=!1,i=r+1);return-1===i?"":e.slice(n,i)},extname:function(e){s(e);for(var t=-1,r=0,n=-1,i=!0,a=0,o=e.length-1;o>=0;--o){var l=e.charCodeAt(o);if(47!==l)-1===n&&(i=!1,n=o+1),46===l?-1===t?t=o:1!==a&&(a=1):-1!==t&&(a=-1);else if(!i){r=o+1;break}}return-1===t||-1===n||0===a||1===a&&t===n-1&&t===r+1?"":e.slice(t,n)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var r=t.dir||t.root,n=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+n:r+"/"+n:n}(0,e)},parse:function(e){s(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var r,n=e.charCodeAt(0),i=47===n;i?(t.root="/",r=1):r=0;for(var a=-1,o=0,l=-1,c=!0,p=e.length-1,u=0;p>=r;--p)if(47!==(n=e.charCodeAt(p)))-1===l&&(c=!1,l=p+1),46===n?-1===a?a=p:1!==u&&(u=1):-1!==a&&(u=-1);else if(!c){o=p+1;break}return-1===a||-1===l||0===u||1===u&&a===l-1&&a===o+1?-1!==l&&(t.base=t.name=0===o&&i?e.slice(1,l):e.slice(o,l)):(0===o&&i?(t.name=e.slice(1,a),t.base=e.slice(1,l)):(t.name=e.slice(o,a),t.base=e.slice(o,l)),t.ext=e.slice(a,l)),o>0?t.dir=e.slice(0,o-1):i&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};a.posix=a,e.exports=a},7980:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WHILE_TYPES=t.USERWHITESPACABLE_TYPES=t.UNARYLIKE_TYPES=t.TYPESCRIPT_TYPES=t.TSTYPE_TYPES=t.TSTYPEELEMENT_TYPES=t.TSENTITYNAME_TYPES=t.TSBASETYPE_TYPES=t.TERMINATORLESS_TYPES=t.STATEMENT_TYPES=t.STANDARDIZED_TYPES=t.SCOPABLE_TYPES=t.PUREISH_TYPES=t.PROPERTY_TYPES=t.PRIVATE_TYPES=t.PATTERN_TYPES=t.PATTERNLIKE_TYPES=t.OBJECTMEMBER_TYPES=t.MODULESPECIFIER_TYPES=t.MODULEDECLARATION_TYPES=t.MISCELLANEOUS_TYPES=t.METHOD_TYPES=t.LVAL_TYPES=t.LOOP_TYPES=t.LITERAL_TYPES=t.JSX_TYPES=t.IMPORTOREXPORTDECLARATION_TYPES=t.IMMUTABLE_TYPES=t.FUNCTION_TYPES=t.FUNCTIONPARENT_TYPES=t.FOR_TYPES=t.FORXSTATEMENT_TYPES=t.FLOW_TYPES=t.FLOWTYPE_TYPES=t.FLOWPREDICATE_TYPES=t.FLOWDECLARATION_TYPES=t.FLOWBASEANNOTATION_TYPES=t.EXPRESSION_TYPES=t.EXPRESSIONWRAPPER_TYPES=t.EXPORTDECLARATION_TYPES=t.ENUMMEMBER_TYPES=t.ENUMBODY_TYPES=t.DECLARATION_TYPES=t.CONDITIONAL_TYPES=t.COMPLETIONSTATEMENT_TYPES=t.CLASS_TYPES=t.BLOCK_TYPES=t.BLOCKPARENT_TYPES=t.BINARY_TYPES=t.ACCESSOR_TYPES=void 0;var n=r(9793);t.STANDARDIZED_TYPES=n.FLIPPED_ALIAS_KEYS.Standardized,t.EXPRESSION_TYPES=n.FLIPPED_ALIAS_KEYS.Expression,t.BINARY_TYPES=n.FLIPPED_ALIAS_KEYS.Binary,t.SCOPABLE_TYPES=n.FLIPPED_ALIAS_KEYS.Scopable,t.BLOCKPARENT_TYPES=n.FLIPPED_ALIAS_KEYS.BlockParent,t.BLOCK_TYPES=n.FLIPPED_ALIAS_KEYS.Block,t.STATEMENT_TYPES=n.FLIPPED_ALIAS_KEYS.Statement,t.TERMINATORLESS_TYPES=n.FLIPPED_ALIAS_KEYS.Terminatorless,t.COMPLETIONSTATEMENT_TYPES=n.FLIPPED_ALIAS_KEYS.CompletionStatement,t.CONDITIONAL_TYPES=n.FLIPPED_ALIAS_KEYS.Conditional,t.LOOP_TYPES=n.FLIPPED_ALIAS_KEYS.Loop,t.WHILE_TYPES=n.FLIPPED_ALIAS_KEYS.While,t.EXPRESSIONWRAPPER_TYPES=n.FLIPPED_ALIAS_KEYS.ExpressionWrapper,t.FOR_TYPES=n.FLIPPED_ALIAS_KEYS.For,t.FORXSTATEMENT_TYPES=n.FLIPPED_ALIAS_KEYS.ForXStatement,t.FUNCTION_TYPES=n.FLIPPED_ALIAS_KEYS.Function,t.FUNCTIONPARENT_TYPES=n.FLIPPED_ALIAS_KEYS.FunctionParent,t.PUREISH_TYPES=n.FLIPPED_ALIAS_KEYS.Pureish,t.DECLARATION_TYPES=n.FLIPPED_ALIAS_KEYS.Declaration,t.PATTERNLIKE_TYPES=n.FLIPPED_ALIAS_KEYS.PatternLike,t.LVAL_TYPES=n.FLIPPED_ALIAS_KEYS.LVal,t.TSENTITYNAME_TYPES=n.FLIPPED_ALIAS_KEYS.TSEntityName,t.LITERAL_TYPES=n.FLIPPED_ALIAS_KEYS.Literal,t.IMMUTABLE_TYPES=n.FLIPPED_ALIAS_KEYS.Immutable,t.USERWHITESPACABLE_TYPES=n.FLIPPED_ALIAS_KEYS.UserWhitespacable,t.METHOD_TYPES=n.FLIPPED_ALIAS_KEYS.Method,t.OBJECTMEMBER_TYPES=n.FLIPPED_ALIAS_KEYS.ObjectMember,t.PROPERTY_TYPES=n.FLIPPED_ALIAS_KEYS.Property,t.UNARYLIKE_TYPES=n.FLIPPED_ALIAS_KEYS.UnaryLike,t.PATTERN_TYPES=n.FLIPPED_ALIAS_KEYS.Pattern,t.CLASS_TYPES=n.FLIPPED_ALIAS_KEYS.Class;const s=t.IMPORTOREXPORTDECLARATION_TYPES=n.FLIPPED_ALIAS_KEYS.ImportOrExportDeclaration;t.EXPORTDECLARATION_TYPES=n.FLIPPED_ALIAS_KEYS.ExportDeclaration,t.MODULESPECIFIER_TYPES=n.FLIPPED_ALIAS_KEYS.ModuleSpecifier,t.ACCESSOR_TYPES=n.FLIPPED_ALIAS_KEYS.Accessor,t.PRIVATE_TYPES=n.FLIPPED_ALIAS_KEYS.Private,t.FLOW_TYPES=n.FLIPPED_ALIAS_KEYS.Flow,t.FLOWTYPE_TYPES=n.FLIPPED_ALIAS_KEYS.FlowType,t.FLOWBASEANNOTATION_TYPES=n.FLIPPED_ALIAS_KEYS.FlowBaseAnnotation,t.FLOWDECLARATION_TYPES=n.FLIPPED_ALIAS_KEYS.FlowDeclaration,t.FLOWPREDICATE_TYPES=n.FLIPPED_ALIAS_KEYS.FlowPredicate,t.ENUMBODY_TYPES=n.FLIPPED_ALIAS_KEYS.EnumBody,t.ENUMMEMBER_TYPES=n.FLIPPED_ALIAS_KEYS.EnumMember,t.JSX_TYPES=n.FLIPPED_ALIAS_KEYS.JSX,t.MISCELLANEOUS_TYPES=n.FLIPPED_ALIAS_KEYS.Miscellaneous,t.TYPESCRIPT_TYPES=n.FLIPPED_ALIAS_KEYS.TypeScript,t.TSTYPEELEMENT_TYPES=n.FLIPPED_ALIAS_KEYS.TSTypeElement,t.TSTYPE_TYPES=n.FLIPPED_ALIAS_KEYS.TSType,t.TSBASETYPE_TYPES=n.FLIPPED_ALIAS_KEYS.TSBaseType,t.MODULEDECLARATION_TYPES=s},8002:e=>{"use strict";e.exports=Math.min},8068:e=>{"use strict";e.exports=SyntaxError},8075:(e,t,r)=>{"use strict";var n=r(453),s=r(487),i=s(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?s(r):r}},8079:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3286);Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===n[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return n[e]}}))}));var s=r(6779);Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===s[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}}))}))},8093:e=>{e.exports={"0.20":"39",.21:"41",.22:"41",.23:"41",.24:"41",.25:"42",.26:"42",.27:"43",.28:"43",.29:"43","0.30":"44",.31:"45",.32:"45",.33:"45",.34:"45",.35:"45",.36:"47",.37:"49","1.0":"49",1.1:"50",1.2:"51",1.3:"52",1.4:"53",1.5:"54",1.6:"56",1.7:"58",1.8:"59","2.0":"61",2.1:"61","3.0":"66",3.1:"66","4.0":"69",4.1:"69",4.2:"69","5.0":"73","6.0":"76",6.1:"76","7.0":"78",7.1:"78",7.2:"78",7.3:"78","8.0":"80",8.1:"80",8.2:"80",8.3:"80",8.4:"80",8.5:"80","9.0":"83",9.1:"83",9.2:"83",9.3:"83",9.4:"83","10.0":"85",10.1:"85",10.2:"85",10.3:"85",10.4:"85","11.0":"87",11.1:"87",11.2:"87",11.3:"87",11.4:"87",11.5:"87","12.0":"89",12.1:"89",12.2:"89","13.0":"91",13.1:"91",13.2:"91",13.3:"91",13.4:"91",13.5:"91",13.6:"91","14.0":"93",14.1:"93",14.2:"93","15.0":"94",15.1:"94",15.2:"94",15.3:"94",15.4:"94",15.5:"94","16.0":"96",16.1:"96",16.2:"96","17.0":"98",17.1:"98",17.2:"98",17.3:"98",17.4:"98","18.0":"100",18.1:"100",18.2:"100",18.3:"100","19.0":"102",19.1:"102","20.0":"104",20.1:"104",20.2:"104",20.3:"104","21.0":"106",21.1:"106",21.2:"106",21.3:"106",21.4:"106","22.0":"108",22.1:"108",22.2:"108",22.3:"108","23.0":"110",23.1:"110",23.2:"110",23.3:"110","24.0":"112",24.1:"112",24.2:"112",24.3:"112",24.4:"112",24.5:"112",24.6:"112",24.7:"112",24.8:"112","25.0":"114",25.1:"114",25.2:"114",25.3:"114",25.4:"114",25.5:"114",25.6:"114",25.7:"114",25.8:"114",25.9:"114","26.0":"116",26.1:"116",26.2:"116",26.3:"116",26.4:"116",26.5:"116",26.6:"116","27.0":"118",27.1:"118",27.2:"118",27.3:"118","28.0":"120",28.1:"120",28.2:"120",28.3:"120","29.0":"122",29.1:"122",29.2:"122",29.3:"122",29.4:"122","30.0":"124",30.1:"124",30.2:"124",30.3:"124",30.4:"124",30.5:"124","31.0":"126",31.1:"126",31.2:"126",31.3:"126",31.4:"126",31.5:"126",31.6:"126",31.7:"126","32.0":"128",32.1:"128",32.2:"128",32.3:"128","33.0":"130",33.1:"130",33.2:"130",33.3:"130",33.4:"130","34.0":"132",34.1:"132",34.2:"132","35.0":"134"}},8125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,n.default)(e,t),(0,s.default)(e,t),(0,i.default)(e,t),e};var n=r(5586),s=r(5766),i=r(7932)},8184:(e,t,r)=>{"use strict";var n,s=r(6556),i=r(9721)(/^\s*(?:function)?\*/),a=r(9092)(),o=r(3628),l=s("Object.prototype.toString"),c=s("Function.prototype.toString");e.exports=function(e){if("function"!=typeof e)return!1;if(i(c(e)))return!0;if(!a)return"[object GeneratorFunction]"===l(e);if(!o)return!1;if(void 0===n){var t=function(){if(!a)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&o(t)}return o(e)===n}},8274:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){const i=new Map,a=new Map,l=t=>{e.requeue(t)};for(const[e,r]of t.source){for(const[t,n]of r.imports)i.set(t,[e,n,null]);for(const t of r.importsNamespace)i.set(t,[e,null,t])}for(const[e,r]of t.local){let t=a.get(e);t||(t=[],a.set(e,t)),t.push(...r.names)}const c={metadata:t,requeueInParent:l,scope:e.scope,exported:a};e.traverse(s,c);const p={seen:new WeakSet,metadata:t,requeueInParent:l,scope:e.scope,imported:i,exported:a,buildImportReference([e,s,i],a){const o=t.source.get(e);var l;if(o.referenced=!0,i)return o.wrap&&(a=null!=(l=r(a,o.wrap))?l:a),a;let c=n.types.identifier(o.name);var p;if(o.wrap&&(c=null!=(p=r(c,o.wrap))?p:c),"default"===s&&"node-default"===o.interop)return c;const u=t.stringSpecifiers.has(s);return n.types.memberExpression(c,u?n.types.stringLiteral(s):n.types.identifier(s),u)}};e.traverse(o,p)};var n=r(6416);const s={Scope(e){e.skip()},ClassDeclaration(e){const{requeueInParent:t,exported:r,metadata:s}=this,{id:a}=e.node;if(!a)throw new Error("Expected class to have a name");const o=a.name,l=r.get(o)||[];if(l.length>0){const r=n.types.expressionStatement(i(s,l,n.types.identifier(o),e.scope));r._blockHoist=e.node._blockHoist,t(e.insertAfter(r)[0])}},VariableDeclaration(e){const{requeueInParent:t,exported:r,metadata:s}=this,a="var"===e.node.kind;for(const o of e.get("declarations")){const{id:l}=o.node;let{init:c}=o.node;if(!n.types.isIdentifier(l)||!r.has(l.name)||n.types.isArrowFunctionExpression(c)||n.types.isFunctionExpression(c)&&!c.id||n.types.isClassExpression(c)&&!c.id){for(const a of Object.keys(o.getOuterBindingIdentifiers()))if(r.has(a)){const o=n.types.expressionStatement(i(s,r.get(a),n.types.identifier(a),e.scope));o._blockHoist=e.node._blockHoist,t(e.insertAfter(o)[0])}}else{if(!c){if(a)continue;c=e.scope.buildUndefinedNode()}o.node.init=i(s,r.get(l.name),c,e.scope),t(o.get("init"))}}}},i=(e,t,r,s)=>{const i=e.exportName;for(let e=s;null!=e;e=e.parent)e.hasOwnBinding(i)&&e.rename(i);return(t||[]).reduce(((t,r)=>{const{stringSpecifiers:s}=e,a=s.has(r);return n.types.assignmentExpression("=",n.types.memberExpression(n.types.identifier(i),a?n.types.stringLiteral(r):n.types.identifier(r),a),t)}),r)},a=e=>n.template.expression.ast` - (function() { - throw new Error('"' + '${e}' + '" is read-only.'); - })() - `,o={ReferencedIdentifier(e){const{seen:t,buildImportReference:r,scope:s,imported:i,requeueInParent:a}=this;if(t.has(e.node))return;t.add(e.node);const o=e.node.name,l=i.get(o);if(l){if(function(e){do{switch(e.parent.type){case"TSTypeAnnotation":case"TSTypeAliasDeclaration":case"TSTypeReference":case"TypeAnnotation":case"TypeAlias":return!0;case"ExportSpecifier":return"type"===e.parentPath.parent.exportKind;default:if(e.parentPath.isStatement()||e.parentPath.isExpression())return!1}}while(e=e.parentPath)}(e))throw e.buildCodeFrameError(`Cannot transform the imported binding "${o}" since it's also used in a type annotation. Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`);const t=e.scope.getBinding(o);if(s.getBinding(o)!==t)return;const i=r(l,e.node);if(i.loc=e.node.loc,(e.parentPath.isCallExpression({callee:e.node})||e.parentPath.isOptionalCallExpression({callee:e.node})||e.parentPath.isTaggedTemplateExpression({tag:e.node}))&&n.types.isMemberExpression(i))e.replaceWith(n.types.sequenceExpression([n.types.numericLiteral(0),i]));else if(e.isJSXIdentifier()&&n.types.isMemberExpression(i)){const{object:t,property:r}=i;e.replaceWith(n.types.jsxMemberExpression(n.types.jsxIdentifier(t.name),n.types.jsxIdentifier(r.name)))}else e.replaceWith(i);a(e),e.skip()}},UpdateExpression(e){const{scope:t,seen:r,imported:s,exported:o,requeueInParent:l,buildImportReference:c}=this;if(r.has(e.node))return;r.add(e.node);const p=e.get("argument");if(p.isMemberExpression())return;const u=e.node;if(p.isIdentifier()){const r=p.node.name;if(t.getBinding(r)!==e.scope.getBinding(r))return;const l=o.get(r),d=s.get(r);if((null==l?void 0:l.length)>0||d)if(d)e.replaceWith(n.types.assignmentExpression(u.operator[0]+"=",c(d,p.node),a(r)));else if(u.prefix)e.replaceWith(i(this.metadata,l,n.types.cloneNode(u),e.scope));else{const s=t.generateDeclaredUidIdentifier(r);e.replaceWith(n.types.sequenceExpression([n.types.assignmentExpression("=",n.types.cloneNode(s),n.types.cloneNode(u)),i(this.metadata,l,n.types.identifier(r),e.scope),n.types.cloneNode(s)]))}}l(e),e.skip()},AssignmentExpression:{exit(e){const{scope:t,seen:r,imported:s,exported:o,requeueInParent:l,buildImportReference:c}=this;if(r.has(e.node))return;r.add(e.node);const p=e.get("left");if(!p.isMemberExpression())if(p.isIdentifier()){const r=p.node.name;if(t.getBinding(r)!==e.scope.getBinding(r))return;const u=o.get(r),d=s.get(r);if((null==u?void 0:u.length)>0||d){const t=e.node;d&&(t.left=c(d,p.node),t.right=n.types.sequenceExpression([t.right,a(r)]));const{operator:s}=t;let o;o="="===s?t:"&&="===s||"||="===s||"??="===s?n.types.assignmentExpression("=",t.left,n.types.logicalExpression(s.slice(0,-1),n.types.cloneNode(t.left),t.right)):n.types.assignmentExpression("=",t.left,n.types.binaryExpression(s.slice(0,-1),n.types.cloneNode(t.left),t.right)),e.replaceWith(i(this.metadata,u,o,e.scope)),l(e),e.skip()}}else{const r=p.getOuterBindingIdentifiers(),c=Object.keys(r).filter((r=>t.getBinding(r)===e.scope.getBinding(r))),u=c.find((e=>s.has(e)));u&&(e.node.right=n.types.sequenceExpression([e.node.right,a(u)]));const d=[];if(c.forEach((t=>{const r=o.get(t)||[];r.length>0&&d.push(i(this.metadata,r,n.types.identifier(t),e.scope))})),d.length>0){let t=n.types.sequenceExpression(d);e.parentPath.isExpressionStatement()&&(t=n.types.expressionStatement(t),t._blockHoist=e.parentPath.node._blockHoist),l(e.insertAfter(t)[0])}}}},ForXStatement(e){const{scope:t,node:r}=e,{left:s}=r,{exported:i,imported:o,scope:l}=this;if(!n.types.isVariableDeclaration(s)){let r,c=!1;const p=e.get("body").scope;for(const e of Object.keys(n.types.getOuterBindingIdentifiers(s)))l.getBinding(e)===t.getBinding(e)&&(i.has(e)&&(c=!0,p.hasOwnBinding(e)&&p.rename(e)),o.has(e)&&!r&&(r=e));if(!c&&!r)return;e.ensureBlock();const u=e.get("body"),d=t.generateUidIdentifierBasedOnNode(s);e.get("left").replaceWith(n.types.variableDeclaration("let",[n.types.variableDeclarator(n.types.cloneNode(d))])),t.registerDeclaration(e.get("left")),c&&u.unshiftContainer("body",n.types.expressionStatement(n.types.assignmentExpression("=",s,d))),r&&u.unshiftContainer("body",n.types.expressionStatement(a(r)))}}}},8345:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._containerInsert=P,t._containerInsertAfter=w,t._containerInsertBefore=A,t._verifyNodeList=N,t.insertAfter=function(e){if(a._assertUnremoved.call(this),this.isSequenceExpression())return C(this.get("expressions")).insertAfter(e);const t=N.call(this,e),{parentPath:r,parent:n}=this;if(r.isExpressionStatement()||r.isLabeledStatement()||b(n)||r.isExportDefaultDeclaration()&&this.isDeclaration())return r.insertAfter(t.map((e=>v(e)?m(e):e)));if(this.isNodeType("Expression")&&!this.isJSXElement()&&!r.isJSXElement()||r.isForStatement()&&"init"===this.key){const e=this;if(e.node){const n=e.node;let{scope:s}=this;if(s.path.isPattern())return p(n),e.replaceWith(f(c([],n),[])),e.get("callee.body").insertAfter(t),[e];if(O(e))t.unshift(n);else if(g(n)&&S(n.callee))t.unshift(n),t.push(E());else if(function(e,t){if(!y(e)||!T(e.left))return!1;const r=t.getBlockParent();return r.hasOwnBinding(e.left.name)&&r.getOwnBinding(e.left.name).constantViolations.length<=1}(n,s))t.unshift(n),t.push(h(n.left));else if(s.isPure(n,!0))t.push(n);else{r.isMethod({computed:!0,key:n})&&(s=s.parent);const e=s.generateDeclaredUidIdentifier();t.unshift(m(u("=",h(e),n))),t.push(m(h(e)))}}return this.replaceExpressionWithStatements(t)}if(Array.isArray(this.container))return w.call(this,t);if(this.isStatementOrBlock()){const e=this.node,r=e&&(!this.isExpressionStatement()||null!=e.expression);return this.replaceWith(d(r?[e]:[])),this.pushContainer("body",t)}throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?")},t.insertBefore=function(e){a._assertUnremoved.call(this);const t=N.call(this,e),{parentPath:r,parent:n}=this;if(r.isExpressionStatement()||r.isLabeledStatement()||b(n)||r.isExportDefaultDeclaration()&&this.isDeclaration())return r.insertBefore(t);if(this.isNodeType("Expression")&&!this.isJSXElement()||r.isForStatement()&&"init"===this.key)return this.node&&t.push(this.node),this.replaceExpressionWithStatements(t);if(Array.isArray(this.container))return A.call(this,t);if(this.isStatementOrBlock()){const e=this.node,r=e&&(!this.isExpressionStatement()||null!=e.expression);return this.replaceWith(d(r?[e]:[])),this.unshiftContainer("body",t)}throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?")},t.pushContainer=function(e,t){a._assertUnremoved.call(this);const r=N.call(this,t),n=this.node[e];return s.default.get({parentPath:this,parent:this.node,container:n,listKey:e,key:n.length}).setContext(this.context).replaceWithMultiple(r)},t.unshiftContainer=function(e,t){a._assertUnremoved.call(this),t=N.call(this,t);const r=s.default.get({parentPath:this,parent:this.node,container:this.node[e],listKey:e,key:0}).setContext(this.context);return A.call(r,t)},t.updateSiblingKeys=I;var n=r(7411),s=r(9709),i=r(9578),a=r(3097),o=r(2352),l=r(7145);const{arrowFunctionExpression:c,assertExpression:p,assignmentExpression:u,blockStatement:d,callExpression:f,cloneNode:h,expressionStatement:m,isAssignmentExpression:y,isCallExpression:g,isExportNamedDeclaration:b,isExpression:v,isIdentifier:T,isSequenceExpression:x,isSuper:S,thisExpression:E}=o;function P(e,t){I.call(this,e,t.length);const r=[];this.container.splice(e,0,...t);for(let s=0;s<t.length;s++){var n;const t=e+s,a=this.getSibling(t);r.push(a),null!=(n=this.context)&&n.queue&&i.pushContext.call(a,this.context)}const s=i._getQueueContexts.call(this);for(const e of r){i.setScope.call(e),e.debug("Inserted.");for(const t of s)t.maybeQueue(e,!0)}return r}function A(e){return P.call(this,this.key,e)}function w(e){return P.call(this,this.key+1,e)}const C=e=>e[e.length-1];function O(e){return x(e.parent)&&(C(e.parent.expressions)!==e.node||O(e.parentPath))}function I(e,t){if(!this.parent)return;const r=(0,n.getCachedPaths)(this.hub,this.parent)||[];for(const[,n]of r)"number"==typeof n.key&&n.container===this.container&&n.key>=e&&(n.key+=t)}function N(e){if(!e)return[];Array.isArray(e)||(e=[e]);for(let t=0;t<e.length;t++){const r=e[t];let n;if(r?"object"!=typeof r?n="contains a non-object node":r.type?r instanceof s.default&&(n="has a NodePath when it expected a raw object"):n="without a type":n="has falsy node",n){const e=Array.isArray(r)?"array":typeof r;throw new Error(`Node list ${n} with the index of ${t} and type of ${e}`)}}return e}t.hoist=function(e=this.scope){return new l.default(this,e).run()}},8403:(e,t,r)=>{"use strict";var n=r(1189),s=r(1333)(),i=r(6556),a=r(9612),o=i("Array.prototype.push"),l=i("Object.prototype.propertyIsEnumerable"),c=s?a.getOwnPropertySymbols:null;e.exports=function(e,t){if(null==e)throw new TypeError("target must be an object");var r=a(e);if(1===arguments.length)return r;for(var i=1;i<arguments.length;++i){var p=a(arguments[i]),u=n(p),d=s&&(a.getOwnPropertySymbols||c);if(d)for(var f=d(p),h=0;h<f.length;++h){var m=f[h];l(p,m)&&o(u,m)}for(var y=0;y<u.length;++y){var g=u[y];if(l(p,g)){var b=p[g];r[g]=b}}}return r}},8404:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TargetNames=void 0,t.TargetNames={node:"node",deno:"deno",chrome:"chrome",opera:"opera",edge:"edge",firefox:"firefox",safari:"safari",ie:"ie",ios:"ios",android:"android",electron:"electron",samsung:"samsung",rhino:"rhino",opera_mobile:"opera_mobile"}},8411:()=>{},8441:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.transformFromAst=void 0,t.transformFromAstAsync=function(...e){return(0,a.beginHiddenCallStack)(o.async)(...e)},t.transformFromAstSync=function(...e){return(0,a.beginHiddenCallStack)(o.sync)(...e)};var s=r(6955),i=r(6568),a=r(1339);const o=n()((function*(e,t,r){const n=yield*(0,s.default)(r);if(null===n)return null;if(!e)throw new Error("No AST given");return yield*(0,i.run)(n,t,e)}));t.transformFromAst=function(e,t,r,n){let s,i;if("function"==typeof r?(i=r,s=void 0):(s=r,i=n),void 0===i)return(0,a.beginHiddenCallStack)(o.sync)(e,t,s);(0,a.beginHiddenCallStack)(o.errback)(e,t,s,i)}},8452:(e,t,r)=>{"use strict";var n=r(1189),s="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),i=Object.prototype.toString,a=Array.prototype.concat,o=r(41),l=r(592)(),c=function(e,t,r,n){if(t in e)if(!0===n){if(e[t]===r)return}else if("function"!=typeof(s=n)||"[object Function]"!==i.call(s)||!n())return;var s;l?o(e,t,r,!0):o(e,t,r)},p=function(e,t){var r=arguments.length>2?arguments[2]:{},i=n(t);s&&(i=a.call(i,Object.getOwnPropertySymbols(t)));for(var o=0;o<i.length;o+=1)c(e,i[o],t[i[o]],r[i[o]])};p.supportsDescriptors=!!l,e.exports=p},8500:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findSuggestion=function(e,t){const n=t.map((t=>function(e,t){let n,s,i=[],a=[];const o=e.length,l=t.length;if(!o)return l;if(!l)return o;for(s=0;s<=l;s++)i[s]=s;for(n=1;n<=o;n++){for(a=[n],s=1;s<=l;s++)a[s]=e[n-1]===t[s-1]?i[s-1]:r(i[s-1],i[s],a[s-1])+1;i=a}return a[l]}(t,e)));return t[n.indexOf(r(...n))]};const{min:r}=Math},8633:e=>{var t=String,r=function(){return{isColorSupported:!1,reset:t,bold:t,dim:t,italic:t,underline:t,inverse:t,hidden:t,strikethrough:t,black:t,red:t,green:t,yellow:t,blue:t,magenta:t,cyan:t,white:t,gray:t,bgBlack:t,bgRed:t,bgGreen:t,bgYellow:t,bgBlue:t,bgMagenta:t,bgCyan:t,bgWhite:t,blackBright:t,redBright:t,greenBright:t,yellowBright:t,blueBright:t,magentaBright:t,cyanBright:t,whiteBright:t,bgBlackBright:t,bgRedBright:t,bgGreenBright:t,bgYellowBright:t,bgBlueBright:t,bgMagentaBright:t,bgCyanBright:t,bgWhiteBright:t}};e.exports=r(),e.exports.createColors=r},8648:e=>{"use strict";e.exports="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null},8721:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIdentifierChar=p,t.isIdentifierName=function(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(55296==(64512&n)&&r+1<e.length){const t=e.charCodeAt(++r);56320==(64512&t)&&(n=65536+((1023&n)<<10)+(1023&t))}if(t){if(t=!1,!c(n))return!1}else if(!p(n))return!1}return!t},t.isIdentifierStart=c;let r="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",n="·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・";const s=new RegExp("["+r+"]"),i=new RegExp("["+r+n+"]");r=n=null;const a=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],o=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239];function l(e,t){let r=65536;for(let n=0,s=t.length;n<s;n+=2){if(r+=t[n],r>e)return!1;if(r+=t[n+1],r>=e)return!0}return!1}function c(e){return e<65?36===e:e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&s.test(String.fromCharCode(e)):l(e,a)))}function p(e){return e<48?36===e:e<58||!(e<65)&&(e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&i.test(String.fromCharCode(e)):l(e,a)||l(e,o))))}},8761:(e,t,r)=>{e.exports=r(2378)},8799:(e,t,r)=>{"use strict";function n(e){var t=this;if(t instanceof n||(t=new n),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var r=0,s=arguments.length;r<s;r++)t.push(arguments[r]);return t}function s(e,t,r){var n=t===e.head?new i(r,null,t,e):new i(r,t,t.next,e);return null===n.next&&(e.tail=n),null===n.prev&&(e.head=n),e.length++,n}function i(e,t,r,n){if(!(this instanceof i))return new i(e,t,r,n);this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}e.exports=n,n.Node=i,n.create=n,n.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),e.list.length--,e.next=null,e.prev=null,e.list=null,t},n.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},n.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},n.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)n=arguments[e],(r=this).tail=new i(n,r.tail,null,r),r.head||(r.head=r.tail),r.length++;var r,n;return this.length},n.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)n=arguments[e],(r=this).head=new i(n,null,r.head,r),r.tail||(r.tail=r.head),r.length++;var r,n;return this.length},n.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},n.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},n.prototype.forEach=function(e,t){t=t||this;for(var r=this.head,n=0;null!==r;n++)e.call(t,r.value,n,this),r=r.next},n.prototype.forEachReverse=function(e,t){t=t||this;for(var r=this.tail,n=this.length-1;null!==r;n--)e.call(t,r.value,n,this),r=r.prev},n.prototype.get=function(e){for(var t=0,r=this.head;null!==r&&t<e;t++)r=r.next;if(t===e&&null!==r)return r.value},n.prototype.getReverse=function(e){for(var t=0,r=this.tail;null!==r&&t<e;t++)r=r.prev;if(t===e&&null!==r)return r.value},n.prototype.map=function(e,t){t=t||this;for(var r=new n,s=this.head;null!==s;)r.push(e.call(t,s.value,this)),s=s.next;return r},n.prototype.mapReverse=function(e,t){t=t||this;for(var r=new n,s=this.tail;null!==s;)r.push(e.call(t,s.value,this)),s=s.prev;return r},n.prototype.reduce=function(e,t){var r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var s=0;null!==n;s++)r=e(r,n.value,s),n=n.next;return r},n.prototype.reduceReverse=function(e,t){var r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var s=this.length-1;null!==n;s--)r=e(r,n.value,s),n=n.prev;return r},n.prototype.toArray=function(){for(var e=new Array(this.length),t=0,r=this.head;null!==r;t++)e[t]=r.value,r=r.next;return e},n.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,r=this.tail;null!==r;t++)e[t]=r.value,r=r.prev;return e},n.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=0,i=this.head;null!==i&&s<e;s++)i=i.next;for(;null!==i&&s<t;s++,i=i.next)r.push(i.value);return r},n.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=this.length,i=this.tail;null!==i&&s>t;s--)i=i.prev;for(;null!==i&&s>e;s--,i=i.prev)r.push(i.value);return r},n.prototype.splice=function(e,t){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,n=this.head;null!==n&&r<e;r++)n=n.next;var i=[];for(r=0;n&&r<t;r++)i.push(n.value),n=this.removeNode(n);for(null===n&&(n=this.tail),n!==this.head&&n!==this.tail&&(n=n.prev),r=2;r<arguments.length;r++)n=s(this,n,arguments[r]);return i},n.prototype.reverse=function(){for(var e=this.head,t=this.tail,r=e;null!==r;r=r.prev){var n=r.prev;r.prev=r.next,r.next=n}return this.head=t,this.tail=e,this};try{r(259)(n)}catch(e){}},8812:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(t){const r=Array.from(t),i=new Map,a=new Map,o=new Set,l=[];for(let t=0;t<r.length;t++){const c=r[t];if(!c)continue;if(l.includes(c))continue;if((0,n.isTSAnyKeyword)(c))return[c];if((0,n.isTSBaseType)(c)){a.set(c.type,c);continue}if((0,n.isTSUnionType)(c)){o.has(c.types)||(r.push(...c.types),o.add(c.types));continue}const p="typeParameters";if((0,n.isTSTypeReference)(c)&&c[p]){const t=c[p],r=s(c.typeName);if(i.has(r)){let n=i.get(r);const s=n[p];s?(s.params.push(...t.params),s.params=e(s.params)):n=t}else i.set(r,c)}else l.push(c)}for(const[,e]of a)l.push(e);for(const[,e]of i)l.push(e);return l};var n=r(8960);function s(e){return(0,n.isIdentifier)(e)?e.name:(0,n.isThisExpression)(e)?"this":`${e.right.name}.${s(e.left)}`}},8873:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.once=function(e){let t,r,s=!1;return function*(){if(!t){if(r)return s=!0,yield*(0,n.waitFor)(r);if(yield*(0,n.isAsync)()){let n,i;r=new Promise(((e,t)=>{n=e,i=t}));try{t={ok:!0,value:yield*e()},r=null,s&&n(t.value)}catch(e){t={ok:!1,value:e},r=null,s&&i(e)}}else try{t={ok:!0,value:yield*e()}}catch(e){t={ok:!1,value:e}}}if(t.ok)return t.value;throw t.value}};var n=r(3310)},8875:(e,t,r)=>{"use strict";var n;if(!Object.keys){var s=Object.prototype.hasOwnProperty,i=Object.prototype.toString,a=r(1093),o=Object.prototype.propertyIsEnumerable,l=!o.call({toString:null},"toString"),c=o.call((function(){}),"prototype"),p=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],u=function(e){var t=e.constructor;return t&&t.prototype===e},d={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},f=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!d["$"+e]&&s.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{u(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();n=function(e){var t=null!==e&&"object"==typeof e,r="[object Function]"===i.call(e),n=a(e),o=t&&"[object String]"===i.call(e),d=[];if(!t&&!r&&!n)throw new TypeError("Object.keys called on a non-object");var h=c&&r;if(o&&e.length>0&&!s.call(e,0))for(var m=0;m<e.length;++m)d.push(String(m));if(n&&e.length>0)for(var y=0;y<e.length;++y)d.push(String(y));else for(var g in e)h&&"prototype"===g||!s.call(e,g)||d.push(String(g));if(l)for(var b=function(e){if("undefined"==typeof window||!f)return u(e);try{return u(e)}catch(e){return!1}}(e),v=0;v<p.length;++v)b&&"constructor"===p[v]||!s.call(e,p[v])||d.push(p[v]);return d}}e.exports=n},8943:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(t,r,s){if(!t)return;const i=n.VISITOR_KEYS[t.type];if(i){r(t,s=s||{});for(const n of i){const i=t[n];if(Array.isArray(i))for(const t of i)e(t,r,s);else e(i,r,s)}}};var n=r(9793)},8960:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAccessor=function(e,t){return!!e&&("ClassAccessorProperty"===e.type&&(null==t||(0,n.default)(e,t)))},t.isAnyTypeAnnotation=function(e,t){return!!e&&"AnyTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isArgumentPlaceholder=function(e,t){return!!e&&"ArgumentPlaceholder"===e.type&&(null==t||(0,n.default)(e,t))},t.isArrayExpression=function(e,t){return!!e&&"ArrayExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isArrayPattern=function(e,t){return!!e&&"ArrayPattern"===e.type&&(null==t||(0,n.default)(e,t))},t.isArrayTypeAnnotation=function(e,t){return!!e&&"ArrayTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isArrowFunctionExpression=function(e,t){return!!e&&"ArrowFunctionExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isAssignmentExpression=function(e,t){return!!e&&"AssignmentExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isAssignmentPattern=function(e,t){return!!e&&"AssignmentPattern"===e.type&&(null==t||(0,n.default)(e,t))},t.isAwaitExpression=function(e,t){return!!e&&"AwaitExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isBigIntLiteral=function(e,t){return!!e&&"BigIntLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isBinary=function(e,t){if(!e)return!1;switch(e.type){case"BinaryExpression":case"LogicalExpression":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isBinaryExpression=function(e,t){return!!e&&"BinaryExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isBindExpression=function(e,t){return!!e&&"BindExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isBlock=function(e,t){if(!e)return!1;switch(e.type){case"BlockStatement":case"Program":case"TSModuleBlock":break;case"Placeholder":if("BlockStatement"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isBlockParent=function(e,t){if(!e)return!1;switch(e.type){case"BlockStatement":case"CatchClause":case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"FunctionDeclaration":case"FunctionExpression":case"Program":case"ObjectMethod":case"SwitchStatement":case"WhileStatement":case"ArrowFunctionExpression":case"ForOfStatement":case"ClassMethod":case"ClassPrivateMethod":case"StaticBlock":case"TSModuleBlock":break;case"Placeholder":if("BlockStatement"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isBlockStatement=function(e,t){return!!e&&"BlockStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isBooleanLiteral=function(e,t){return!!e&&"BooleanLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isBooleanLiteralTypeAnnotation=function(e,t){return!!e&&"BooleanLiteralTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isBooleanTypeAnnotation=function(e,t){return!!e&&"BooleanTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isBreakStatement=function(e,t){return!!e&&"BreakStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isCallExpression=function(e,t){return!!e&&"CallExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isCatchClause=function(e,t){return!!e&&"CatchClause"===e.type&&(null==t||(0,n.default)(e,t))},t.isClass=function(e,t){if(!e)return!1;switch(e.type){case"ClassExpression":case"ClassDeclaration":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isClassAccessorProperty=function(e,t){return!!e&&"ClassAccessorProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassBody=function(e,t){return!!e&&"ClassBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassDeclaration=function(e,t){return!!e&&"ClassDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassExpression=function(e,t){return!!e&&"ClassExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassImplements=function(e,t){return!!e&&"ClassImplements"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassMethod=function(e,t){return!!e&&"ClassMethod"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassPrivateMethod=function(e,t){return!!e&&"ClassPrivateMethod"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassPrivateProperty=function(e,t){return!!e&&"ClassPrivateProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isClassProperty=function(e,t){return!!e&&"ClassProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isCompletionStatement=function(e,t){if(!e)return!1;switch(e.type){case"BreakStatement":case"ContinueStatement":case"ReturnStatement":case"ThrowStatement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isConditional=function(e,t){if(!e)return!1;switch(e.type){case"ConditionalExpression":case"IfStatement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isConditionalExpression=function(e,t){return!!e&&"ConditionalExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isContinueStatement=function(e,t){return!!e&&"ContinueStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isDebuggerStatement=function(e,t){return!!e&&"DebuggerStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isDecimalLiteral=function(e,t){return!!e&&"DecimalLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclaration=function(e,t){if(!e)return!1;switch(e.type){case"FunctionDeclaration":case"VariableDeclaration":case"ClassDeclaration":case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":case"ImportDeclaration":case"DeclareClass":case"DeclareFunction":case"DeclareInterface":case"DeclareModule":case"DeclareModuleExports":case"DeclareTypeAlias":case"DeclareOpaqueType":case"DeclareVariable":case"DeclareExportDeclaration":case"DeclareExportAllDeclaration":case"InterfaceDeclaration":case"OpaqueType":case"TypeAlias":case"EnumDeclaration":case"TSDeclareFunction":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":case"TSImportEqualsDeclaration":break;case"Placeholder":if("Declaration"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isDeclareClass=function(e,t){return!!e&&"DeclareClass"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareExportAllDeclaration=function(e,t){return!!e&&"DeclareExportAllDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareExportDeclaration=function(e,t){return!!e&&"DeclareExportDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareFunction=function(e,t){return!!e&&"DeclareFunction"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareInterface=function(e,t){return!!e&&"DeclareInterface"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareModule=function(e,t){return!!e&&"DeclareModule"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareModuleExports=function(e,t){return!!e&&"DeclareModuleExports"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareOpaqueType=function(e,t){return!!e&&"DeclareOpaqueType"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareTypeAlias=function(e,t){return!!e&&"DeclareTypeAlias"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclareVariable=function(e,t){return!!e&&"DeclareVariable"===e.type&&(null==t||(0,n.default)(e,t))},t.isDeclaredPredicate=function(e,t){return!!e&&"DeclaredPredicate"===e.type&&(null==t||(0,n.default)(e,t))},t.isDecorator=function(e,t){return!!e&&"Decorator"===e.type&&(null==t||(0,n.default)(e,t))},t.isDirective=function(e,t){return!!e&&"Directive"===e.type&&(null==t||(0,n.default)(e,t))},t.isDirectiveLiteral=function(e,t){return!!e&&"DirectiveLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isDoExpression=function(e,t){return!!e&&"DoExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isDoWhileStatement=function(e,t){return!!e&&"DoWhileStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isEmptyStatement=function(e,t){return!!e&&"EmptyStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isEmptyTypeAnnotation=function(e,t){return!!e&&"EmptyTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumBody=function(e,t){if(!e)return!1;switch(e.type){case"EnumBooleanBody":case"EnumNumberBody":case"EnumStringBody":case"EnumSymbolBody":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isEnumBooleanBody=function(e,t){return!!e&&"EnumBooleanBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumBooleanMember=function(e,t){return!!e&&"EnumBooleanMember"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumDeclaration=function(e,t){return!!e&&"EnumDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumDefaultedMember=function(e,t){return!!e&&"EnumDefaultedMember"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumMember=function(e,t){if(!e)return!1;switch(e.type){case"EnumBooleanMember":case"EnumNumberMember":case"EnumStringMember":case"EnumDefaultedMember":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isEnumNumberBody=function(e,t){return!!e&&"EnumNumberBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumNumberMember=function(e,t){return!!e&&"EnumNumberMember"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumStringBody=function(e,t){return!!e&&"EnumStringBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumStringMember=function(e,t){return!!e&&"EnumStringMember"===e.type&&(null==t||(0,n.default)(e,t))},t.isEnumSymbolBody=function(e,t){return!!e&&"EnumSymbolBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isExistsTypeAnnotation=function(e,t){return!!e&&"ExistsTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isExportAllDeclaration=function(e,t){return!!e&&"ExportAllDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isExportDeclaration=function(e,t){if(!e)return!1;switch(e.type){case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isExportDefaultDeclaration=function(e,t){return!!e&&"ExportDefaultDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isExportDefaultSpecifier=function(e,t){return!!e&&"ExportDefaultSpecifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isExportNamedDeclaration=function(e,t){return!!e&&"ExportNamedDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isExportNamespaceSpecifier=function(e,t){return!!e&&"ExportNamespaceSpecifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isExportSpecifier=function(e,t){return!!e&&"ExportSpecifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isExpression=function(e,t){if(!e)return!1;switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"StringLiteral":case"NumericLiteral":case"NullLiteral":case"BooleanLiteral":case"RegExpLiteral":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ParenthesizedExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":case"ArrowFunctionExpression":case"ClassExpression":case"ImportExpression":case"MetaProperty":case"Super":case"TaggedTemplateExpression":case"TemplateLiteral":case"YieldExpression":case"AwaitExpression":case"Import":case"BigIntLiteral":case"OptionalMemberExpression":case"OptionalCallExpression":case"TypeCastExpression":case"JSXElement":case"JSXFragment":case"BindExpression":case"DoExpression":case"RecordExpression":case"TupleExpression":case"DecimalLiteral":case"ModuleExpression":case"TopicReference":case"PipelineTopicExpression":case"PipelineBareFunction":case"PipelinePrimaryTopicReference":case"TSInstantiationExpression":case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":break;case"Placeholder":switch(e.expectedNode){case"Expression":case"Identifier":case"StringLiteral":break;default:return!1}break;default:return!1}return null==t||(0,n.default)(e,t)},t.isExpressionStatement=function(e,t){return!!e&&"ExpressionStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isExpressionWrapper=function(e,t){if(!e)return!1;switch(e.type){case"ExpressionStatement":case"ParenthesizedExpression":case"TypeCastExpression":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFile=function(e,t){return!!e&&"File"===e.type&&(null==t||(0,n.default)(e,t))},t.isFlow=function(e,t){if(!e)return!1;switch(e.type){case"AnyTypeAnnotation":case"ArrayTypeAnnotation":case"BooleanTypeAnnotation":case"BooleanLiteralTypeAnnotation":case"NullLiteralTypeAnnotation":case"ClassImplements":case"DeclareClass":case"DeclareFunction":case"DeclareInterface":case"DeclareModule":case"DeclareModuleExports":case"DeclareTypeAlias":case"DeclareOpaqueType":case"DeclareVariable":case"DeclareExportDeclaration":case"DeclareExportAllDeclaration":case"DeclaredPredicate":case"ExistsTypeAnnotation":case"FunctionTypeAnnotation":case"FunctionTypeParam":case"GenericTypeAnnotation":case"InferredPredicate":case"InterfaceExtends":case"InterfaceDeclaration":case"InterfaceTypeAnnotation":case"IntersectionTypeAnnotation":case"MixedTypeAnnotation":case"EmptyTypeAnnotation":case"NullableTypeAnnotation":case"NumberLiteralTypeAnnotation":case"NumberTypeAnnotation":case"ObjectTypeAnnotation":case"ObjectTypeInternalSlot":case"ObjectTypeCallProperty":case"ObjectTypeIndexer":case"ObjectTypeProperty":case"ObjectTypeSpreadProperty":case"OpaqueType":case"QualifiedTypeIdentifier":case"StringLiteralTypeAnnotation":case"StringTypeAnnotation":case"SymbolTypeAnnotation":case"ThisTypeAnnotation":case"TupleTypeAnnotation":case"TypeofTypeAnnotation":case"TypeAlias":case"TypeAnnotation":case"TypeCastExpression":case"TypeParameter":case"TypeParameterDeclaration":case"TypeParameterInstantiation":case"UnionTypeAnnotation":case"Variance":case"VoidTypeAnnotation":case"EnumDeclaration":case"EnumBooleanBody":case"EnumNumberBody":case"EnumStringBody":case"EnumSymbolBody":case"EnumBooleanMember":case"EnumNumberMember":case"EnumStringMember":case"EnumDefaultedMember":case"IndexedAccessType":case"OptionalIndexedAccessType":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFlowBaseAnnotation=function(e,t){if(!e)return!1;switch(e.type){case"AnyTypeAnnotation":case"BooleanTypeAnnotation":case"NullLiteralTypeAnnotation":case"MixedTypeAnnotation":case"EmptyTypeAnnotation":case"NumberTypeAnnotation":case"StringTypeAnnotation":case"SymbolTypeAnnotation":case"ThisTypeAnnotation":case"VoidTypeAnnotation":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFlowDeclaration=function(e,t){if(!e)return!1;switch(e.type){case"DeclareClass":case"DeclareFunction":case"DeclareInterface":case"DeclareModule":case"DeclareModuleExports":case"DeclareTypeAlias":case"DeclareOpaqueType":case"DeclareVariable":case"DeclareExportDeclaration":case"DeclareExportAllDeclaration":case"InterfaceDeclaration":case"OpaqueType":case"TypeAlias":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFlowPredicate=function(e,t){if(!e)return!1;switch(e.type){case"DeclaredPredicate":case"InferredPredicate":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFlowType=function(e,t){if(!e)return!1;switch(e.type){case"AnyTypeAnnotation":case"ArrayTypeAnnotation":case"BooleanTypeAnnotation":case"BooleanLiteralTypeAnnotation":case"NullLiteralTypeAnnotation":case"ExistsTypeAnnotation":case"FunctionTypeAnnotation":case"GenericTypeAnnotation":case"InterfaceTypeAnnotation":case"IntersectionTypeAnnotation":case"MixedTypeAnnotation":case"EmptyTypeAnnotation":case"NullableTypeAnnotation":case"NumberLiteralTypeAnnotation":case"NumberTypeAnnotation":case"ObjectTypeAnnotation":case"StringLiteralTypeAnnotation":case"StringTypeAnnotation":case"SymbolTypeAnnotation":case"ThisTypeAnnotation":case"TupleTypeAnnotation":case"TypeofTypeAnnotation":case"UnionTypeAnnotation":case"VoidTypeAnnotation":case"IndexedAccessType":case"OptionalIndexedAccessType":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFor=function(e,t){if(!e)return!1;switch(e.type){case"ForInStatement":case"ForStatement":case"ForOfStatement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isForInStatement=function(e,t){return!!e&&"ForInStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isForOfStatement=function(e,t){return!!e&&"ForOfStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isForStatement=function(e,t){return!!e&&"ForStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isForXStatement=function(e,t){if(!e)return!1;switch(e.type){case"ForInStatement":case"ForOfStatement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFunction=function(e,t){if(!e)return!1;switch(e.type){case"FunctionDeclaration":case"FunctionExpression":case"ObjectMethod":case"ArrowFunctionExpression":case"ClassMethod":case"ClassPrivateMethod":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFunctionDeclaration=function(e,t){return!!e&&"FunctionDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isFunctionExpression=function(e,t){return!!e&&"FunctionExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isFunctionParent=function(e,t){if(!e)return!1;switch(e.type){case"FunctionDeclaration":case"FunctionExpression":case"ObjectMethod":case"ArrowFunctionExpression":case"ClassMethod":case"ClassPrivateMethod":case"StaticBlock":case"TSModuleBlock":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isFunctionTypeAnnotation=function(e,t){return!!e&&"FunctionTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isFunctionTypeParam=function(e,t){return!!e&&"FunctionTypeParam"===e.type&&(null==t||(0,n.default)(e,t))},t.isGenericTypeAnnotation=function(e,t){return!!e&&"GenericTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isIdentifier=function(e,t){return!!e&&"Identifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isIfStatement=function(e,t){return!!e&&"IfStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isImmutable=function(e,t){if(!e)return!1;switch(e.type){case"StringLiteral":case"NumericLiteral":case"NullLiteral":case"BooleanLiteral":case"BigIntLiteral":case"JSXAttribute":case"JSXClosingElement":case"JSXElement":case"JSXExpressionContainer":case"JSXSpreadChild":case"JSXOpeningElement":case"JSXText":case"JSXFragment":case"JSXOpeningFragment":case"JSXClosingFragment":case"DecimalLiteral":break;case"Placeholder":if("StringLiteral"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isImport=function(e,t){return!!e&&"Import"===e.type&&(null==t||(0,n.default)(e,t))},t.isImportAttribute=function(e,t){return!!e&&"ImportAttribute"===e.type&&(null==t||(0,n.default)(e,t))},t.isImportDeclaration=function(e,t){return!!e&&"ImportDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isImportDefaultSpecifier=function(e,t){return!!e&&"ImportDefaultSpecifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isImportExpression=function(e,t){return!!e&&"ImportExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isImportNamespaceSpecifier=function(e,t){return!!e&&"ImportNamespaceSpecifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isImportOrExportDeclaration=i,t.isImportSpecifier=function(e,t){return!!e&&"ImportSpecifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isIndexedAccessType=function(e,t){return!!e&&"IndexedAccessType"===e.type&&(null==t||(0,n.default)(e,t))},t.isInferredPredicate=function(e,t){return!!e&&"InferredPredicate"===e.type&&(null==t||(0,n.default)(e,t))},t.isInterfaceDeclaration=function(e,t){return!!e&&"InterfaceDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isInterfaceExtends=function(e,t){return!!e&&"InterfaceExtends"===e.type&&(null==t||(0,n.default)(e,t))},t.isInterfaceTypeAnnotation=function(e,t){return!!e&&"InterfaceTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isInterpreterDirective=function(e,t){return!!e&&"InterpreterDirective"===e.type&&(null==t||(0,n.default)(e,t))},t.isIntersectionTypeAnnotation=function(e,t){return!!e&&"IntersectionTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSX=function(e,t){if(!e)return!1;switch(e.type){case"JSXAttribute":case"JSXClosingElement":case"JSXElement":case"JSXEmptyExpression":case"JSXExpressionContainer":case"JSXSpreadChild":case"JSXIdentifier":case"JSXMemberExpression":case"JSXNamespacedName":case"JSXOpeningElement":case"JSXSpreadAttribute":case"JSXText":case"JSXFragment":case"JSXOpeningFragment":case"JSXClosingFragment":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isJSXAttribute=function(e,t){return!!e&&"JSXAttribute"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXClosingElement=function(e,t){return!!e&&"JSXClosingElement"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXClosingFragment=function(e,t){return!!e&&"JSXClosingFragment"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXElement=function(e,t){return!!e&&"JSXElement"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXEmptyExpression=function(e,t){return!!e&&"JSXEmptyExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXExpressionContainer=function(e,t){return!!e&&"JSXExpressionContainer"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXFragment=function(e,t){return!!e&&"JSXFragment"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXIdentifier=function(e,t){return!!e&&"JSXIdentifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXMemberExpression=function(e,t){return!!e&&"JSXMemberExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXNamespacedName=function(e,t){return!!e&&"JSXNamespacedName"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXOpeningElement=function(e,t){return!!e&&"JSXOpeningElement"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXOpeningFragment=function(e,t){return!!e&&"JSXOpeningFragment"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXSpreadAttribute=function(e,t){return!!e&&"JSXSpreadAttribute"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXSpreadChild=function(e,t){return!!e&&"JSXSpreadChild"===e.type&&(null==t||(0,n.default)(e,t))},t.isJSXText=function(e,t){return!!e&&"JSXText"===e.type&&(null==t||(0,n.default)(e,t))},t.isLVal=function(e,t){if(!e)return!1;switch(e.type){case"Identifier":case"MemberExpression":case"RestElement":case"AssignmentPattern":case"ArrayPattern":case"ObjectPattern":case"TSParameterProperty":case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":break;case"Placeholder":switch(e.expectedNode){case"Pattern":case"Identifier":break;default:return!1}break;default:return!1}return null==t||(0,n.default)(e,t)},t.isLabeledStatement=function(e,t){return!!e&&"LabeledStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isLiteral=function(e,t){if(!e)return!1;switch(e.type){case"StringLiteral":case"NumericLiteral":case"NullLiteral":case"BooleanLiteral":case"RegExpLiteral":case"TemplateLiteral":case"BigIntLiteral":case"DecimalLiteral":break;case"Placeholder":if("StringLiteral"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isLogicalExpression=function(e,t){return!!e&&"LogicalExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isLoop=function(e,t){if(!e)return!1;switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":case"ForOfStatement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isMemberExpression=function(e,t){return!!e&&"MemberExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isMetaProperty=function(e,t){return!!e&&"MetaProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isMethod=function(e,t){if(!e)return!1;switch(e.type){case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isMiscellaneous=function(e,t){if(!e)return!1;switch(e.type){case"Noop":case"Placeholder":case"V8IntrinsicIdentifier":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isMixedTypeAnnotation=function(e,t){return!!e&&"MixedTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isModuleDeclaration=function(e,t){return(0,s.default)("isModuleDeclaration","isImportOrExportDeclaration"),i(e,t)},t.isModuleExpression=function(e,t){return!!e&&"ModuleExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isModuleSpecifier=function(e,t){if(!e)return!1;switch(e.type){case"ExportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ImportSpecifier":case"ExportNamespaceSpecifier":case"ExportDefaultSpecifier":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isNewExpression=function(e,t){return!!e&&"NewExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isNoop=function(e,t){return!!e&&"Noop"===e.type&&(null==t||(0,n.default)(e,t))},t.isNullLiteral=function(e,t){return!!e&&"NullLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isNullLiteralTypeAnnotation=function(e,t){return!!e&&"NullLiteralTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isNullableTypeAnnotation=function(e,t){return!!e&&"NullableTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isNumberLiteral=function(e,t){return(0,s.default)("isNumberLiteral","isNumericLiteral"),!!e&&"NumberLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isNumberLiteralTypeAnnotation=function(e,t){return!!e&&"NumberLiteralTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isNumberTypeAnnotation=function(e,t){return!!e&&"NumberTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isNumericLiteral=function(e,t){return!!e&&"NumericLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectExpression=function(e,t){return!!e&&"ObjectExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectMember=function(e,t){if(!e)return!1;switch(e.type){case"ObjectMethod":case"ObjectProperty":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isObjectMethod=function(e,t){return!!e&&"ObjectMethod"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectPattern=function(e,t){return!!e&&"ObjectPattern"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectProperty=function(e,t){return!!e&&"ObjectProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectTypeAnnotation=function(e,t){return!!e&&"ObjectTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectTypeCallProperty=function(e,t){return!!e&&"ObjectTypeCallProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectTypeIndexer=function(e,t){return!!e&&"ObjectTypeIndexer"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectTypeInternalSlot=function(e,t){return!!e&&"ObjectTypeInternalSlot"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectTypeProperty=function(e,t){return!!e&&"ObjectTypeProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isObjectTypeSpreadProperty=function(e,t){return!!e&&"ObjectTypeSpreadProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isOpaqueType=function(e,t){return!!e&&"OpaqueType"===e.type&&(null==t||(0,n.default)(e,t))},t.isOptionalCallExpression=function(e,t){return!!e&&"OptionalCallExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isOptionalIndexedAccessType=function(e,t){return!!e&&"OptionalIndexedAccessType"===e.type&&(null==t||(0,n.default)(e,t))},t.isOptionalMemberExpression=function(e,t){return!!e&&"OptionalMemberExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isParenthesizedExpression=function(e,t){return!!e&&"ParenthesizedExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isPattern=function(e,t){if(!e)return!1;switch(e.type){case"AssignmentPattern":case"ArrayPattern":case"ObjectPattern":break;case"Placeholder":if("Pattern"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isPatternLike=function(e,t){if(!e)return!1;switch(e.type){case"Identifier":case"RestElement":case"AssignmentPattern":case"ArrayPattern":case"ObjectPattern":case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":break;case"Placeholder":switch(e.expectedNode){case"Pattern":case"Identifier":break;default:return!1}break;default:return!1}return null==t||(0,n.default)(e,t)},t.isPipelineBareFunction=function(e,t){return!!e&&"PipelineBareFunction"===e.type&&(null==t||(0,n.default)(e,t))},t.isPipelinePrimaryTopicReference=function(e,t){return!!e&&"PipelinePrimaryTopicReference"===e.type&&(null==t||(0,n.default)(e,t))},t.isPipelineTopicExpression=function(e,t){return!!e&&"PipelineTopicExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isPlaceholder=function(e,t){return!!e&&"Placeholder"===e.type&&(null==t||(0,n.default)(e,t))},t.isPrivate=function(e,t){if(!e)return!1;switch(e.type){case"ClassPrivateProperty":case"ClassPrivateMethod":case"PrivateName":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isPrivateName=function(e,t){return!!e&&"PrivateName"===e.type&&(null==t||(0,n.default)(e,t))},t.isProgram=function(e,t){return!!e&&"Program"===e.type&&(null==t||(0,n.default)(e,t))},t.isProperty=function(e,t){if(!e)return!1;switch(e.type){case"ObjectProperty":case"ClassProperty":case"ClassAccessorProperty":case"ClassPrivateProperty":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isPureish=function(e,t){if(!e)return!1;switch(e.type){case"FunctionDeclaration":case"FunctionExpression":case"StringLiteral":case"NumericLiteral":case"NullLiteral":case"BooleanLiteral":case"RegExpLiteral":case"ArrowFunctionExpression":case"BigIntLiteral":case"DecimalLiteral":break;case"Placeholder":if("StringLiteral"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isQualifiedTypeIdentifier=function(e,t){return!!e&&"QualifiedTypeIdentifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isRecordExpression=function(e,t){return!!e&&"RecordExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isRegExpLiteral=function(e,t){return!!e&&"RegExpLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isRegexLiteral=function(e,t){return(0,s.default)("isRegexLiteral","isRegExpLiteral"),!!e&&"RegexLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isRestElement=function(e,t){return!!e&&"RestElement"===e.type&&(null==t||(0,n.default)(e,t))},t.isRestProperty=function(e,t){return(0,s.default)("isRestProperty","isRestElement"),!!e&&"RestProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isReturnStatement=function(e,t){return!!e&&"ReturnStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isScopable=function(e,t){if(!e)return!1;switch(e.type){case"BlockStatement":case"CatchClause":case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"FunctionDeclaration":case"FunctionExpression":case"Program":case"ObjectMethod":case"SwitchStatement":case"WhileStatement":case"ArrowFunctionExpression":case"ClassExpression":case"ClassDeclaration":case"ForOfStatement":case"ClassMethod":case"ClassPrivateMethod":case"StaticBlock":case"TSModuleBlock":break;case"Placeholder":if("BlockStatement"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isSequenceExpression=function(e,t){return!!e&&"SequenceExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isSpreadElement=function(e,t){return!!e&&"SpreadElement"===e.type&&(null==t||(0,n.default)(e,t))},t.isSpreadProperty=function(e,t){return(0,s.default)("isSpreadProperty","isSpreadElement"),!!e&&"SpreadProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isStandardized=function(e,t){if(!e)return!1;switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"InterpreterDirective":case"Directive":case"DirectiveLiteral":case"BlockStatement":case"BreakStatement":case"CallExpression":case"CatchClause":case"ConditionalExpression":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"File":case"ForInStatement":case"ForStatement":case"FunctionDeclaration":case"FunctionExpression":case"Identifier":case"IfStatement":case"LabeledStatement":case"StringLiteral":case"NumericLiteral":case"NullLiteral":case"BooleanLiteral":case"RegExpLiteral":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"Program":case"ObjectExpression":case"ObjectMethod":case"ObjectProperty":case"RestElement":case"ReturnStatement":case"SequenceExpression":case"ParenthesizedExpression":case"SwitchCase":case"SwitchStatement":case"ThisExpression":case"ThrowStatement":case"TryStatement":case"UnaryExpression":case"UpdateExpression":case"VariableDeclaration":case"VariableDeclarator":case"WhileStatement":case"WithStatement":case"AssignmentPattern":case"ArrayPattern":case"ArrowFunctionExpression":case"ClassBody":case"ClassExpression":case"ClassDeclaration":case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":case"ExportSpecifier":case"ForOfStatement":case"ImportDeclaration":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ImportSpecifier":case"ImportExpression":case"MetaProperty":case"ClassMethod":case"ObjectPattern":case"SpreadElement":case"Super":case"TaggedTemplateExpression":case"TemplateElement":case"TemplateLiteral":case"YieldExpression":case"AwaitExpression":case"Import":case"BigIntLiteral":case"ExportNamespaceSpecifier":case"OptionalMemberExpression":case"OptionalCallExpression":case"ClassProperty":case"ClassAccessorProperty":case"ClassPrivateProperty":case"ClassPrivateMethod":case"PrivateName":case"StaticBlock":break;case"Placeholder":switch(e.expectedNode){case"Identifier":case"StringLiteral":case"BlockStatement":case"ClassBody":break;default:return!1}break;default:return!1}return null==t||(0,n.default)(e,t)},t.isStatement=function(e,t){if(!e)return!1;switch(e.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"FunctionDeclaration":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":case"ClassDeclaration":case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":case"ForOfStatement":case"ImportDeclaration":case"DeclareClass":case"DeclareFunction":case"DeclareInterface":case"DeclareModule":case"DeclareModuleExports":case"DeclareTypeAlias":case"DeclareOpaqueType":case"DeclareVariable":case"DeclareExportDeclaration":case"DeclareExportAllDeclaration":case"InterfaceDeclaration":case"OpaqueType":case"TypeAlias":case"EnumDeclaration":case"TSDeclareFunction":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":case"TSImportEqualsDeclaration":case"TSExportAssignment":case"TSNamespaceExportDeclaration":break;case"Placeholder":switch(e.expectedNode){case"Statement":case"Declaration":case"BlockStatement":break;default:return!1}break;default:return!1}return null==t||(0,n.default)(e,t)},t.isStaticBlock=function(e,t){return!!e&&"StaticBlock"===e.type&&(null==t||(0,n.default)(e,t))},t.isStringLiteral=function(e,t){return!!e&&"StringLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isStringLiteralTypeAnnotation=function(e,t){return!!e&&"StringLiteralTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isStringTypeAnnotation=function(e,t){return!!e&&"StringTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isSuper=function(e,t){return!!e&&"Super"===e.type&&(null==t||(0,n.default)(e,t))},t.isSwitchCase=function(e,t){return!!e&&"SwitchCase"===e.type&&(null==t||(0,n.default)(e,t))},t.isSwitchStatement=function(e,t){return!!e&&"SwitchStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isSymbolTypeAnnotation=function(e,t){return!!e&&"SymbolTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSAnyKeyword=function(e,t){return!!e&&"TSAnyKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSArrayType=function(e,t){return!!e&&"TSArrayType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSAsExpression=function(e,t){return!!e&&"TSAsExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSBaseType=function(e,t){if(!e)return!1;switch(e.type){case"TSAnyKeyword":case"TSBooleanKeyword":case"TSBigIntKeyword":case"TSIntrinsicKeyword":case"TSNeverKeyword":case"TSNullKeyword":case"TSNumberKeyword":case"TSObjectKeyword":case"TSStringKeyword":case"TSSymbolKeyword":case"TSUndefinedKeyword":case"TSUnknownKeyword":case"TSVoidKeyword":case"TSThisType":case"TSTemplateLiteralType":case"TSLiteralType":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isTSBigIntKeyword=function(e,t){return!!e&&"TSBigIntKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSBooleanKeyword=function(e,t){return!!e&&"TSBooleanKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSCallSignatureDeclaration=function(e,t){return!!e&&"TSCallSignatureDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSConditionalType=function(e,t){return!!e&&"TSConditionalType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSConstructSignatureDeclaration=function(e,t){return!!e&&"TSConstructSignatureDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSConstructorType=function(e,t){return!!e&&"TSConstructorType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSDeclareFunction=function(e,t){return!!e&&"TSDeclareFunction"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSDeclareMethod=function(e,t){return!!e&&"TSDeclareMethod"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSEntityName=function(e,t){if(!e)return!1;switch(e.type){case"Identifier":case"TSQualifiedName":break;case"Placeholder":if("Identifier"===e.expectedNode)break;default:return!1}return null==t||(0,n.default)(e,t)},t.isTSEnumBody=function(e,t){return!!e&&"TSEnumBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSEnumDeclaration=function(e,t){return!!e&&"TSEnumDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSEnumMember=function(e,t){return!!e&&"TSEnumMember"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSExportAssignment=function(e,t){return!!e&&"TSExportAssignment"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSExpressionWithTypeArguments=function(e,t){return!!e&&"TSExpressionWithTypeArguments"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSExternalModuleReference=function(e,t){return!!e&&"TSExternalModuleReference"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSFunctionType=function(e,t){return!!e&&"TSFunctionType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSImportEqualsDeclaration=function(e,t){return!!e&&"TSImportEqualsDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSImportType=function(e,t){return!!e&&"TSImportType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSIndexSignature=function(e,t){return!!e&&"TSIndexSignature"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSIndexedAccessType=function(e,t){return!!e&&"TSIndexedAccessType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSInferType=function(e,t){return!!e&&"TSInferType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSInstantiationExpression=function(e,t){return!!e&&"TSInstantiationExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSInterfaceBody=function(e,t){return!!e&&"TSInterfaceBody"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSInterfaceDeclaration=function(e,t){return!!e&&"TSInterfaceDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSIntersectionType=function(e,t){return!!e&&"TSIntersectionType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSIntrinsicKeyword=function(e,t){return!!e&&"TSIntrinsicKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSLiteralType=function(e,t){return!!e&&"TSLiteralType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSMappedType=function(e,t){return!!e&&"TSMappedType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSMethodSignature=function(e,t){return!!e&&"TSMethodSignature"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSModuleBlock=function(e,t){return!!e&&"TSModuleBlock"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSModuleDeclaration=function(e,t){return!!e&&"TSModuleDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSNamedTupleMember=function(e,t){return!!e&&"TSNamedTupleMember"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSNamespaceExportDeclaration=function(e,t){return!!e&&"TSNamespaceExportDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSNeverKeyword=function(e,t){return!!e&&"TSNeverKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSNonNullExpression=function(e,t){return!!e&&"TSNonNullExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSNullKeyword=function(e,t){return!!e&&"TSNullKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSNumberKeyword=function(e,t){return!!e&&"TSNumberKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSObjectKeyword=function(e,t){return!!e&&"TSObjectKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSOptionalType=function(e,t){return!!e&&"TSOptionalType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSParameterProperty=function(e,t){return!!e&&"TSParameterProperty"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSParenthesizedType=function(e,t){return!!e&&"TSParenthesizedType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSPropertySignature=function(e,t){return!!e&&"TSPropertySignature"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSQualifiedName=function(e,t){return!!e&&"TSQualifiedName"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSRestType=function(e,t){return!!e&&"TSRestType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSSatisfiesExpression=function(e,t){return!!e&&"TSSatisfiesExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSStringKeyword=function(e,t){return!!e&&"TSStringKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSSymbolKeyword=function(e,t){return!!e&&"TSSymbolKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTemplateLiteralType=function(e,t){return!!e&&"TSTemplateLiteralType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSThisType=function(e,t){return!!e&&"TSThisType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTupleType=function(e,t){return!!e&&"TSTupleType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSType=function(e,t){if(!e)return!1;switch(e.type){case"TSAnyKeyword":case"TSBooleanKeyword":case"TSBigIntKeyword":case"TSIntrinsicKeyword":case"TSNeverKeyword":case"TSNullKeyword":case"TSNumberKeyword":case"TSObjectKeyword":case"TSStringKeyword":case"TSSymbolKeyword":case"TSUndefinedKeyword":case"TSUnknownKeyword":case"TSVoidKeyword":case"TSThisType":case"TSFunctionType":case"TSConstructorType":case"TSTypeReference":case"TSTypePredicate":case"TSTypeQuery":case"TSTypeLiteral":case"TSArrayType":case"TSTupleType":case"TSOptionalType":case"TSRestType":case"TSUnionType":case"TSIntersectionType":case"TSConditionalType":case"TSInferType":case"TSParenthesizedType":case"TSTypeOperator":case"TSIndexedAccessType":case"TSMappedType":case"TSTemplateLiteralType":case"TSLiteralType":case"TSExpressionWithTypeArguments":case"TSImportType":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isTSTypeAliasDeclaration=function(e,t){return!!e&&"TSTypeAliasDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeAnnotation=function(e,t){return!!e&&"TSTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeAssertion=function(e,t){return!!e&&"TSTypeAssertion"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeElement=function(e,t){if(!e)return!1;switch(e.type){case"TSCallSignatureDeclaration":case"TSConstructSignatureDeclaration":case"TSPropertySignature":case"TSMethodSignature":case"TSIndexSignature":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isTSTypeLiteral=function(e,t){return!!e&&"TSTypeLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeOperator=function(e,t){return!!e&&"TSTypeOperator"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeParameter=function(e,t){return!!e&&"TSTypeParameter"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeParameterDeclaration=function(e,t){return!!e&&"TSTypeParameterDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeParameterInstantiation=function(e,t){return!!e&&"TSTypeParameterInstantiation"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypePredicate=function(e,t){return!!e&&"TSTypePredicate"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeQuery=function(e,t){return!!e&&"TSTypeQuery"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSTypeReference=function(e,t){return!!e&&"TSTypeReference"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSUndefinedKeyword=function(e,t){return!!e&&"TSUndefinedKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSUnionType=function(e,t){return!!e&&"TSUnionType"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSUnknownKeyword=function(e,t){return!!e&&"TSUnknownKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTSVoidKeyword=function(e,t){return!!e&&"TSVoidKeyword"===e.type&&(null==t||(0,n.default)(e,t))},t.isTaggedTemplateExpression=function(e,t){return!!e&&"TaggedTemplateExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTemplateElement=function(e,t){return!!e&&"TemplateElement"===e.type&&(null==t||(0,n.default)(e,t))},t.isTemplateLiteral=function(e,t){return!!e&&"TemplateLiteral"===e.type&&(null==t||(0,n.default)(e,t))},t.isTerminatorless=function(e,t){if(!e)return!1;switch(e.type){case"BreakStatement":case"ContinueStatement":case"ReturnStatement":case"ThrowStatement":case"YieldExpression":case"AwaitExpression":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isThisExpression=function(e,t){return!!e&&"ThisExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isThisTypeAnnotation=function(e,t){return!!e&&"ThisTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isThrowStatement=function(e,t){return!!e&&"ThrowStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isTopicReference=function(e,t){return!!e&&"TopicReference"===e.type&&(null==t||(0,n.default)(e,t))},t.isTryStatement=function(e,t){return!!e&&"TryStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isTupleExpression=function(e,t){return!!e&&"TupleExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTupleTypeAnnotation=function(e,t){return!!e&&"TupleTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeAlias=function(e,t){return!!e&&"TypeAlias"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeAnnotation=function(e,t){return!!e&&"TypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeCastExpression=function(e,t){return!!e&&"TypeCastExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeParameter=function(e,t){return!!e&&"TypeParameter"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeParameterDeclaration=function(e,t){return!!e&&"TypeParameterDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeParameterInstantiation=function(e,t){return!!e&&"TypeParameterInstantiation"===e.type&&(null==t||(0,n.default)(e,t))},t.isTypeScript=function(e,t){if(!e)return!1;switch(e.type){case"TSParameterProperty":case"TSDeclareFunction":case"TSDeclareMethod":case"TSQualifiedName":case"TSCallSignatureDeclaration":case"TSConstructSignatureDeclaration":case"TSPropertySignature":case"TSMethodSignature":case"TSIndexSignature":case"TSAnyKeyword":case"TSBooleanKeyword":case"TSBigIntKeyword":case"TSIntrinsicKeyword":case"TSNeverKeyword":case"TSNullKeyword":case"TSNumberKeyword":case"TSObjectKeyword":case"TSStringKeyword":case"TSSymbolKeyword":case"TSUndefinedKeyword":case"TSUnknownKeyword":case"TSVoidKeyword":case"TSThisType":case"TSFunctionType":case"TSConstructorType":case"TSTypeReference":case"TSTypePredicate":case"TSTypeQuery":case"TSTypeLiteral":case"TSArrayType":case"TSTupleType":case"TSOptionalType":case"TSRestType":case"TSNamedTupleMember":case"TSUnionType":case"TSIntersectionType":case"TSConditionalType":case"TSInferType":case"TSParenthesizedType":case"TSTypeOperator":case"TSIndexedAccessType":case"TSMappedType":case"TSTemplateLiteralType":case"TSLiteralType":case"TSExpressionWithTypeArguments":case"TSInterfaceDeclaration":case"TSInterfaceBody":case"TSTypeAliasDeclaration":case"TSInstantiationExpression":case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSEnumBody":case"TSEnumDeclaration":case"TSEnumMember":case"TSModuleDeclaration":case"TSModuleBlock":case"TSImportType":case"TSImportEqualsDeclaration":case"TSExternalModuleReference":case"TSNonNullExpression":case"TSExportAssignment":case"TSNamespaceExportDeclaration":case"TSTypeAnnotation":case"TSTypeParameterInstantiation":case"TSTypeParameterDeclaration":case"TSTypeParameter":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isTypeofTypeAnnotation=function(e,t){return!!e&&"TypeofTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isUnaryExpression=function(e,t){return!!e&&"UnaryExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isUnaryLike=function(e,t){if(!e)return!1;switch(e.type){case"UnaryExpression":case"SpreadElement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isUnionTypeAnnotation=function(e,t){return!!e&&"UnionTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isUpdateExpression=function(e,t){return!!e&&"UpdateExpression"===e.type&&(null==t||(0,n.default)(e,t))},t.isUserWhitespacable=function(e,t){if(!e)return!1;switch(e.type){case"ObjectMethod":case"ObjectProperty":case"ObjectTypeInternalSlot":case"ObjectTypeCallProperty":case"ObjectTypeIndexer":case"ObjectTypeProperty":case"ObjectTypeSpreadProperty":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isV8IntrinsicIdentifier=function(e,t){return!!e&&"V8IntrinsicIdentifier"===e.type&&(null==t||(0,n.default)(e,t))},t.isVariableDeclaration=function(e,t){return!!e&&"VariableDeclaration"===e.type&&(null==t||(0,n.default)(e,t))},t.isVariableDeclarator=function(e,t){return!!e&&"VariableDeclarator"===e.type&&(null==t||(0,n.default)(e,t))},t.isVariance=function(e,t){return!!e&&"Variance"===e.type&&(null==t||(0,n.default)(e,t))},t.isVoidTypeAnnotation=function(e,t){return!!e&&"VoidTypeAnnotation"===e.type&&(null==t||(0,n.default)(e,t))},t.isWhile=function(e,t){if(!e)return!1;switch(e.type){case"DoWhileStatement":case"WhileStatement":break;default:return!1}return null==t||(0,n.default)(e,t)},t.isWhileStatement=function(e,t){return!!e&&"WhileStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isWithStatement=function(e,t){return!!e&&"WithStatement"===e.type&&(null==t||(0,n.default)(e,t))},t.isYieldExpression=function(e,t){return!!e&&"YieldExpression"===e.type&&(null==t||(0,n.default)(e,t))};var n=r(6616),s=r(3762);function i(e,t){if(!e)return!1;switch(e.type){case"ExportAllDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":case"ImportDeclaration":break;default:return!1}return null==t||(0,n.default)(e,t)}},8968:e=>{"use strict";e.exports=Math.floor},8992:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t={},r){const a=i(r,t,e),o=t.sourceMaps?new n.default(t,r):null;return new s.default(a,o,e.tokens,"string"==typeof r?r:null).generate(e)};var n=r(4068),s=r(6636);function i(e,t,r){if(t.experimental_preserveFormat){if("string"!=typeof e)throw new Error("`experimental_preserveFormat` requires the original `code` to be passed to @babel/generator as a string");if(!t.retainLines)throw new Error("`experimental_preserveFormat` requires `retainLines` to be set to `true`");if(t.compact&&"auto"!==t.compact)throw new Error("`experimental_preserveFormat` is not compatible with the `compact` option");if(t.minified)throw new Error("`experimental_preserveFormat` is not compatible with the `minified` option");if(t.jsescOption)throw new Error("`experimental_preserveFormat` is not compatible with the `jsescOption` option");if(!Array.isArray(r.tokens))throw new Error("`experimental_preserveFormat` requires the AST to have attatched the token of the input code. Make sure to enable the `tokens: true` parser option.")}const n={auxiliaryCommentBefore:t.auxiliaryCommentBefore,auxiliaryCommentAfter:t.auxiliaryCommentAfter,shouldPrintComment:t.shouldPrintComment,preserveFormat:t.experimental_preserveFormat,retainLines:t.retainLines,retainFunctionParens:t.retainFunctionParens,comments:null==t.comments||t.comments,compact:t.compact,minified:t.minified,concise:t.concise,indent:{adjustMultilineComment:!0,style:" "},jsescOption:Object.assign({quotes:"double",wrap:!0,minimal:!1},t.jsescOption),topicToken:t.topicToken,importAttributesKeyword:t.importAttributesKeyword};var s;n.decoratorsBeforeExport=t.decoratorsBeforeExport,n.jsescOption.json=t.jsonCompatibleStrings,n.recordAndTupleSyntaxType=null!=(s=t.recordAndTupleSyntaxType)?s:"hash",n.minified?(n.compact=!0,n.shouldPrintComment=n.shouldPrintComment||(()=>n.comments)):n.shouldPrintComment=n.shouldPrintComment||(e=>n.comments||e.includes("@license")||e.includes("@preserve")),"auto"===n.compact&&(n.compact="string"==typeof e&&e.length>5e5,n.compact&&console.error(`[BABEL] Note: The code generator has deoptimised the styling of ${t.filename} as it exceeds the max of 500KB.`)),(n.compact||n.preserveFormat)&&(n.indent.adjustMultilineComment=!1);const{auxiliaryCommentBefore:i,auxiliaryCommentAfter:a,shouldPrintComment:o}=n;return i&&!o(i)&&(n.auxiliaryCommentBefore=void 0),a&&!o(a)&&(n.auxiliaryCommentAfter=void 0),n}t.CodeGenerator=class{constructor(e,t={},r){this._ast=void 0,this._format=void 0,this._map=void 0,this._ast=e,this._format=i(r,t,e),this._map=t.sourceMaps?new n.default(t,r):null}generate(){return new s.default(this._format,this._map).generate(this._ast)}}},9018:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){const t=[];for(let r=0;r<e.children.length;r++){let i=e.children[r];(0,n.isJSXText)(i)?(0,s.default)(i,t):((0,n.isJSXExpressionContainer)(i)&&(i=i.expression),(0,n.isJSXEmptyExpression)(i)||t.push(i))}return t};var n=r(8960),s=r(3043)},9032:(e,t,r)=>{"use strict";var n=r(7244),s=r(8184),i=r(5767),a=r(5680);function o(e){return e.call.bind(e)}var l="undefined"!=typeof BigInt,c="undefined"!=typeof Symbol,p=o(Object.prototype.toString),u=o(Number.prototype.valueOf),d=o(String.prototype.valueOf),f=o(Boolean.prototype.valueOf);if(l)var h=o(BigInt.prototype.valueOf);if(c)var m=o(Symbol.prototype.valueOf);function y(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function g(e){return"[object Map]"===p(e)}function b(e){return"[object Set]"===p(e)}function v(e){return"[object WeakMap]"===p(e)}function T(e){return"[object WeakSet]"===p(e)}function x(e){return"[object ArrayBuffer]"===p(e)}function S(e){return"undefined"!=typeof ArrayBuffer&&(x.working?x(e):e instanceof ArrayBuffer)}function E(e){return"[object DataView]"===p(e)}function P(e){return"undefined"!=typeof DataView&&(E.working?E(e):e instanceof DataView)}t.isArgumentsObject=n,t.isGeneratorFunction=s,t.isTypedArray=a,t.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},t.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):a(e)||P(e)},t.isUint8Array=function(e){return"Uint8Array"===i(e)},t.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===i(e)},t.isUint16Array=function(e){return"Uint16Array"===i(e)},t.isUint32Array=function(e){return"Uint32Array"===i(e)},t.isInt8Array=function(e){return"Int8Array"===i(e)},t.isInt16Array=function(e){return"Int16Array"===i(e)},t.isInt32Array=function(e){return"Int32Array"===i(e)},t.isFloat32Array=function(e){return"Float32Array"===i(e)},t.isFloat64Array=function(e){return"Float64Array"===i(e)},t.isBigInt64Array=function(e){return"BigInt64Array"===i(e)},t.isBigUint64Array=function(e){return"BigUint64Array"===i(e)},g.working="undefined"!=typeof Map&&g(new Map),t.isMap=function(e){return"undefined"!=typeof Map&&(g.working?g(e):e instanceof Map)},b.working="undefined"!=typeof Set&&b(new Set),t.isSet=function(e){return"undefined"!=typeof Set&&(b.working?b(e):e instanceof Set)},v.working="undefined"!=typeof WeakMap&&v(new WeakMap),t.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(v.working?v(e):e instanceof WeakMap)},T.working="undefined"!=typeof WeakSet&&T(new WeakSet),t.isWeakSet=function(e){return T(e)},x.working="undefined"!=typeof ArrayBuffer&&x(new ArrayBuffer),t.isArrayBuffer=S,E.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&E(new DataView(new ArrayBuffer(1),0,1)),t.isDataView=P;var A="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function w(e){return"[object SharedArrayBuffer]"===p(e)}function C(e){return void 0!==A&&(void 0===w.working&&(w.working=w(new A)),w.working?w(e):e instanceof A)}function O(e){return y(e,u)}function I(e){return y(e,d)}function N(e){return y(e,f)}function k(e){return l&&y(e,h)}function _(e){return c&&y(e,m)}t.isSharedArrayBuffer=C,t.isAsyncFunction=function(e){return"[object AsyncFunction]"===p(e)},t.isMapIterator=function(e){return"[object Map Iterator]"===p(e)},t.isSetIterator=function(e){return"[object Set Iterator]"===p(e)},t.isGeneratorObject=function(e){return"[object Generator]"===p(e)},t.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===p(e)},t.isNumberObject=O,t.isStringObject=I,t.isBooleanObject=N,t.isBigIntObject=k,t.isSymbolObject=_,t.isBoxedPrimitive=function(e){return O(e)||I(e)||N(e)||k(e)||_(e)},t.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(S(e)||C(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(t,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},9092:(e,t,r)=>{"use strict";var n=r(1333);e.exports=function(){return n()&&!!Symbol.toStringTag}},9127:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,n.isFunctionDeclaration)(e)||(0,n.isClassDeclaration)(e)||(0,s.default)(e)};var n=r(8960),s=r(3847)},9133:(e,t,r)=>{"use strict";var n=r(8403);e.exports=function(){return Object.assign?function(){if(!Object.assign)return!1;for(var e="abcdefghijklmnopqrst",t=e.split(""),r={},n=0;n<t.length;++n)r[t[n]]=t[n];var s=Object.assign({},r),i="";for(var a in s)i+=a;return e!==i}()||function(){if(!Object.assign||!Object.preventExtensions)return!1;var e=Object.preventExtensions({1:2});try{Object.assign(e,"xy")}catch(t){return"y"===e[1]}return!1}()?n:Object.assign:n}},9187:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PLACEHOLDERS_FLIPPED_ALIAS=t.PLACEHOLDERS_ALIAS=t.PLACEHOLDERS=void 0;var n=r(7596);const s=t.PLACEHOLDERS=["Identifier","StringLiteral","Expression","Statement","Declaration","BlockStatement","ClassBody","Pattern"],i=t.PLACEHOLDERS_ALIAS={Declaration:["Statement"],Pattern:["PatternLike","LVal"]};for(const e of s){const t=n.ALIAS_KEYS[e];null!=t&&t.length&&(i[e]=t)}const a=t.PLACEHOLDERS_FLIPPED_ALIAS={};Object.keys(i).forEach((e=>{i[e].forEach((t=>{hasOwnProperty.call(a,t)||(a[t]=[]),a[t].push(e)}))}))},9198:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(8960),s=r(8079);t.default=function(e,t){if((0,n.isStatement)(e))return e;let r,i=!1;if((0,n.isClass)(e))i=!0,r="ClassDeclaration";else if((0,n.isFunction)(e))i=!0,r="FunctionDeclaration";else if((0,n.isAssignmentExpression)(e))return(0,s.expressionStatement)(e);if(i&&!e.id&&(r=!1),!r){if(t)return!1;throw new Error(`cannot turn ${e.type} to a statement`)}return e.type=r,e}},9209:(e,t,r)=>{"use strict";var n=r(6578),s="undefined"==typeof globalThis?r.g:globalThis;e.exports=function(){for(var e=[],t=0;t<n.length;t++)"function"==typeof s[n[t]]&&(e[e.length]=n[t]);return e}},9211:e=>{"use strict";var t=function(e){return e!=e};e.exports=function(e,r){return 0===e&&0===r?1/e==1/r:e===r||!(!t(e)||!t(r))}},9246:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(!(0,n.isBlockStatement)(e)||!(0,n.isFunction)(t)&&!(0,n.isCatchClause)(t))&&(!(!(0,n.isPattern)(e)||!(0,n.isFunction)(t)&&!(0,n.isCatchClause)(t))||(0,n.isScopable)(e))};var n=r(8960)},9276:(e,t)=>{"use strict";function r(e,t){e.tokenMap&&t.start&&t.end?e.tokenMap.endMatches(t,",")?e.token(","):e.tokenMap.endMatches(t,";")&&e.semicolon():e.semicolon()}function n(e,t,r){var n;let s=0;null!=(n=e.tokenMap)&&n.startMatches(t,r)&&(s=1,e.token(r)),e.printJoin(t.types,void 0,void 0,(function(e){this.space(),this.token(r,null,e+s),this.space()}))}function s(e,t){!0!==t&&e.token(t)}function i(e){a(this,e,(()=>{var t;return this.printList(e.members,null==(t=this.shouldPrintTrailingComma("}"))||t,!0,!0)}))}function a(e,t,r){e.token("{");const n=e.enterDelimited();r(),n(),e.rightBrace(t)}function o(e,t,r){var n;const s=new Set;for(const e of r)e&&s.add(e);null==(n=e.tokenMap)||n.find(t,(t=>{if(s.has(t.value))return e.token(t.value),e.space(),s.delete(t.value),0===s.size}));for(const t of s)e.word(t),e.space()}Object.defineProperty(t,"__esModule",{value:!0}),t.TSAnyKeyword=function(){this.word("any")},t.TSArrayType=function(e){this.print(e.elementType,!0),this.tokenChar(91),this.tokenChar(93)},t.TSSatisfiesExpression=t.TSAsExpression=function(e){const{type:t,expression:r,typeAnnotation:n}=e;this.print(r,!0),this.space(),this.word("TSAsExpression"===t?"as":"satisfies"),this.space(),this.print(n)},t.TSBigIntKeyword=function(){this.word("bigint")},t.TSBooleanKeyword=function(){this.word("boolean")},t.TSCallSignatureDeclaration=function(e){this.tsPrintSignatureDeclarationBase(e),r(this,e)},t.TSInterfaceHeritage=t.TSClassImplements=function(e){this.print(e.expression),this.print(e.typeArguments)},t.TSConditionalType=function(e){this.print(e.checkType),this.space(),this.word("extends"),this.space(),this.print(e.extendsType),this.space(),this.tokenChar(63),this.space(),this.print(e.trueType),this.space(),this.tokenChar(58),this.space(),this.print(e.falseType)},t.TSConstructSignatureDeclaration=function(e){this.word("new"),this.space(),this.tsPrintSignatureDeclarationBase(e),r(this,e)},t.TSConstructorType=function(e){e.abstract&&(this.word("abstract"),this.space()),this.word("new"),this.space(),this.tsPrintFunctionOrConstructorType(e)},t.TSDeclareFunction=function(e,t){e.declare&&(this.word("declare"),this.space()),this._functionHead(e,t),this.semicolon()},t.TSDeclareMethod=function(e){this._classMethodHead(e),this.semicolon()},t.TSEnumBody=i,t.TSEnumDeclaration=function(e){const{declare:t,const:r,id:n}=e;t&&(this.word("declare"),this.space()),r&&(this.word("const"),this.space()),this.word("enum"),this.space(),this.print(n),this.space(),i.call(this,e)},t.TSEnumMember=function(e){const{id:t,initializer:r}=e;this.print(t),r&&(this.space(),this.tokenChar(61),this.space(),this.print(r))},t.TSExportAssignment=function(e){this.word("export"),this.space(),this.tokenChar(61),this.space(),this.print(e.expression),this.semicolon()},t.TSExternalModuleReference=function(e){this.token("require("),this.print(e.expression),this.tokenChar(41)},t.TSFunctionType=function(e){this.tsPrintFunctionOrConstructorType(e)},t.TSImportEqualsDeclaration=function(e){const{id:t,moduleReference:r}=e;e.isExport&&(this.word("export"),this.space()),this.word("import"),this.space(),this.print(t),this.space(),this.tokenChar(61),this.space(),this.print(r),this.semicolon()},t.TSImportType=function(e){const{argument:t,qualifier:r,options:n}=e;this.word("import"),this.tokenChar(40),this.print(t),n&&(this.tokenChar(44),this.print(n)),this.tokenChar(41),r&&(this.tokenChar(46),this.print(r));const s=e.typeParameters;s&&this.print(s)},t.TSIndexSignature=function(e){const{readonly:t,static:n}=e;n&&(this.word("static"),this.space()),t&&(this.word("readonly"),this.space()),this.tokenChar(91),this._parameters(e.parameters,"]"),this.print(e.typeAnnotation),r(this,e)},t.TSIndexedAccessType=function(e){this.print(e.objectType,!0),this.tokenChar(91),this.print(e.indexType),this.tokenChar(93)},t.TSInferType=function(e){this.word("infer"),this.print(e.typeParameter)},t.TSInstantiationExpression=function(e){this.print(e.expression),this.print(e.typeParameters)},t.TSInterfaceBody=function(e){a(this,e,(()=>this.printJoin(e.body,!0,!0)))},t.TSInterfaceDeclaration=function(e){const{declare:t,id:r,typeParameters:n,extends:s,body:i}=e;t&&(this.word("declare"),this.space()),this.word("interface"),this.space(),this.print(r),this.print(n),null!=s&&s.length&&(this.space(),this.word("extends"),this.space(),this.printList(s)),this.space(),this.print(i)},t.TSIntersectionType=function(e){n(this,e,"&")},t.TSIntrinsicKeyword=function(){this.word("intrinsic")},t.TSLiteralType=function(e){this.print(e.literal)},t.TSMappedType=function(e){const{nameType:t,optional:r,readonly:n,typeAnnotation:i}=e;this.tokenChar(123);const a=this.enterDelimited();this.space(),n&&(s(this,n),this.word("readonly"),this.space()),this.tokenChar(91),this.word(e.typeParameter.name),this.space(),this.word("in"),this.space(),this.print(e.typeParameter.constraint),t&&(this.space(),this.word("as"),this.space(),this.print(t)),this.tokenChar(93),r&&(s(this,r),this.tokenChar(63)),i&&(this.tokenChar(58),this.space(),this.print(i)),this.space(),a(),this.tokenChar(125)},t.TSMethodSignature=function(e){const{kind:t}=e;"set"!==t&&"get"!==t||(this.word(t),this.space()),this.tsPrintPropertyOrMethodName(e),this.tsPrintSignatureDeclarationBase(e),r(this,e)},t.TSModuleBlock=function(e){a(this,e,(()=>this.printSequence(e.body,!0)))},t.TSModuleDeclaration=function(e){const{declare:t,id:r,kind:n}=e;t&&(this.word("declare"),this.space());{if(e.global||(this.word(null!=n?n:"Identifier"===r.type?"namespace":"module"),this.space()),this.print(r),!e.body)return void this.semicolon();let t=e.body;for(;"TSModuleDeclaration"===t.type;)this.tokenChar(46),this.print(t.id),t=t.body;this.space(),this.print(t)}},t.TSNamedTupleMember=function(e){this.print(e.label),e.optional&&this.tokenChar(63),this.tokenChar(58),this.space(),this.print(e.elementType)},t.TSNamespaceExportDeclaration=function(e){this.word("export"),this.space(),this.word("as"),this.space(),this.word("namespace"),this.space(),this.print(e.id),this.semicolon()},t.TSNeverKeyword=function(){this.word("never")},t.TSNonNullExpression=function(e){this.print(e.expression),this.tokenChar(33)},t.TSNullKeyword=function(){this.word("null")},t.TSNumberKeyword=function(){this.word("number")},t.TSObjectKeyword=function(){this.word("object")},t.TSOptionalType=function(e){this.print(e.typeAnnotation),this.tokenChar(63)},t.TSParameterProperty=function(e){e.accessibility&&(this.word(e.accessibility),this.space()),e.readonly&&(this.word("readonly"),this.space()),this._param(e.parameter)},t.TSParenthesizedType=function(e){this.tokenChar(40),this.print(e.typeAnnotation),this.tokenChar(41)},t.TSPropertySignature=function(e){const{readonly:t}=e;t&&(this.word("readonly"),this.space()),this.tsPrintPropertyOrMethodName(e),this.print(e.typeAnnotation),r(this,e)},t.TSQualifiedName=function(e){this.print(e.left),this.tokenChar(46),this.print(e.right)},t.TSRestType=function(e){this.token("..."),this.print(e.typeAnnotation)},t.TSStringKeyword=function(){this.word("string")},t.TSSymbolKeyword=function(){this.word("symbol")},t.TSTemplateLiteralType=function(e){this._printTemplate(e,e.types)},t.TSThisType=function(){this.word("this")},t.TSTupleType=function(e){this.tokenChar(91),this.printList(e.elementTypes,this.shouldPrintTrailingComma("]")),this.tokenChar(93)},t.TSTypeAliasDeclaration=function(e){const{declare:t,id:r,typeParameters:n,typeAnnotation:s}=e;t&&(this.word("declare"),this.space()),this.word("type"),this.space(),this.print(r),this.print(n),this.space(),this.tokenChar(61),this.space(),this.print(s),this.semicolon()},t.TSTypeAnnotation=function(e,t){this.token("TSFunctionType"!==t.type&&"TSConstructorType"!==t.type||t.typeAnnotation!==e?":":"=>"),this.space(),e.optional&&this.tokenChar(63),this.print(e.typeAnnotation)},t.TSTypeAssertion=function(e){const{typeAnnotation:t,expression:r}=e;this.tokenChar(60),this.print(t),this.tokenChar(62),this.space(),this.print(r)},t.TSTypeLiteral=function(e){a(this,e,(()=>this.printJoin(e.members,!0,!0)))},t.TSTypeOperator=function(e){this.word(e.operator),this.space(),this.print(e.typeAnnotation)},t.TSTypeParameter=function(e){e.in&&(this.word("in"),this.space()),e.out&&(this.word("out"),this.space()),this.word(e.name),e.constraint&&(this.space(),this.word("extends"),this.space(),this.print(e.constraint)),e.default&&(this.space(),this.tokenChar(61),this.space(),this.print(e.default))},t.TSTypeParameterDeclaration=t.TSTypeParameterInstantiation=function(e,t){this.tokenChar(60);let r="ArrowFunctionExpression"===t.type&&1===e.params.length;this.tokenMap&&null!=e.start&&null!=e.end&&(r&&(r=!!this.tokenMap.find(e,(e=>this.tokenMap.matchesOriginal(e,",")))),r||(r=this.shouldPrintTrailingComma(">"))),this.printList(e.params,r),this.tokenChar(62)},t.TSTypePredicate=function(e){e.asserts&&(this.word("asserts"),this.space()),this.print(e.parameterName),e.typeAnnotation&&(this.space(),this.word("is"),this.space(),this.print(e.typeAnnotation.typeAnnotation))},t.TSTypeQuery=function(e){this.word("typeof"),this.space(),this.print(e.exprName);const t=e.typeParameters;t&&this.print(t)},t.TSTypeReference=function(e){const t=e.typeParameters;this.print(e.typeName,!!t),this.print(t)},t.TSUndefinedKeyword=function(){this.word("undefined")},t.TSUnionType=function(e){n(this,e,"|")},t.TSUnknownKeyword=function(){this.word("unknown")},t.TSVoidKeyword=function(){this.word("void")},t.tsPrintClassMemberModifiers=function(e){const t="ClassPrivateProperty"===e.type,r="ClassAccessorProperty"===e.type||"ClassProperty"===e.type;o(this,e,[r&&e.declare&&"declare",!t&&e.accessibility]),e.static&&(this.word("static"),this.space()),o(this,e,[!t&&e.override&&"override",!t&&e.abstract&&"abstract",(r||t)&&e.readonly&&"readonly"])},t.tsPrintFunctionOrConstructorType=function(e){const{typeParameters:t}=e,r=e.parameters;this.print(t),this.tokenChar(40),this._parameters(r,")"),this.space();const n=e.typeAnnotation;this.print(n)},t.tsPrintPropertyOrMethodName=function(e){e.computed&&this.tokenChar(91),this.print(e.key),e.computed&&this.tokenChar(93),e.optional&&this.tokenChar(63)},t.tsPrintSignatureDeclarationBase=function(e){const{typeParameters:t}=e,r=e.parameters;this.print(t),this.tokenChar(40),this._parameters(r,")");const n=e.typeAnnotation;this.print(n)}},9290:e=>{"use strict";e.exports=RangeError},9320:function(e,t,r){!function(e,t,r,n){"use strict";class s{constructor({file:e,sourceRoot:r}={}){this._names=new t.SetArray,this._sources=new t.SetArray,this._sourcesContent=[],this._mappings=[],this.file=e,this.sourceRoot=r,this._ignoreList=new t.SetArray}}function i(e){const{_mappings:t,_sources:r,_sourcesContent:n,_names:s,_ignoreList:i}=e;return function(e){const{length:t}=e;let r=t;for(let t=r-1;t>=0&&!(e[t].length>0);r=t,t--);r<t&&(e.length=r)}(t),{version:3,file:e.file||void 0,names:s.array,sourceRoot:e.sourceRoot||void 0,sources:r.array,sourcesContent:n,mappings:t,ignoreList:i.array}}function a(e,r,n,s,i,a,l,c,p){const{_mappings:u,_sources:d,_sourcesContent:f,_names:h}=r,m=function(e,t){for(let r=e.length;r<=t;r++)e[r]=[];return e[t]}(u,n),y=function(e,t){let r=e.length;for(let n=r-1;n>=0&&!(t>=e[n][0]);r=n--);return r}(m,s);if(!i){if(e&&function(e,t){return 0===t||1===e[t-1].length}(m,y))return;return o(m,y,[s])}const g=t.put(d,i),b=c?t.put(h,c):-1;if(g===f.length&&(f[g]=null!=p?p:null),!e||!function(e,t,r,n,s,i){if(0===t)return!1;const a=e[t-1];return 1!==a.length&&r===a[1]&&n===a[2]&&s===a[3]&&i===(5===a.length?a[4]:-1)}(m,y,g,a,l,b))return o(m,y,c?[s,g,a,l,b]:[s,g,a,l])}function o(e,t,r){for(let r=e.length;r>t;r--)e[r]=e[r-1];e[t]=r}function l(e,r){for(let n=0;n<r.length;n++)t.put(e,r[n])}function c(e,t,r){const{generated:n,source:s,original:i,name:o,content:l}=r;return s?a(e,t,n.line-1,n.column,s,i.line-1,i.column,o,l):a(e,t,n.line-1,n.column,null,null,null,null,null)}e.GenMapping=s,e.addMapping=function(e,t){return c(!1,e,t)},e.addSegment=function(e,t,r,n,s,i,o,l){return a(!1,e,t,r,n,s,i,o,l)},e.allMappings=function(e){const t=[],{_mappings:r,_sources:n,_names:s}=e;for(let e=0;e<r.length;e++){const i=r[e];for(let r=0;r<i.length;r++){const a=i[r],o={line:e+1,column:a[0]};let l,c,p;1!==a.length&&(l=n.array[a[1]],c={line:a[2]+1,column:a[3]},5===a.length&&(p=s.array[a[4]])),t.push({generated:o,source:l,original:c,name:p})}}return t},e.fromMap=function(e){const t=new n.TraceMap(e),r=new s({file:t.file,sourceRoot:t.sourceRoot});return l(r._names,t.names),l(r._sources,t.sources),r._sourcesContent=t.sourcesContent||t.sources.map((()=>null)),r._mappings=n.decodedMappings(t),t.ignoreList&&l(r._ignoreList,t.ignoreList),r},e.maybeAddMapping=(e,t)=>c(!0,e,t),e.maybeAddSegment=(e,t,r,n,s,i,o,l)=>a(!0,e,t,r,n,s,i,o,l),e.setIgnore=function(e,r,n=!0){const{_sources:s,_sourcesContent:i,_ignoreList:a}=e,o=t.put(s,r);o===i.length&&(i[o]=null),n?t.put(a,o):t.remove(a,o)},e.setSourceContent=function(e,r,n){const{_sources:s,_sourcesContent:i}=e;i[t.put(s,r)]=n},e.toDecodedMap=i,e.toEncodedMap=function(e){const t=i(e);return Object.assign(Object.assign({},t),{mappings:r.encode(t.mappings)})},Object.defineProperty(e,"__esModule",{value:!0})}(t,r(3534),r(4318),r(2802))},9353:e=>{"use strict";var t=Object.prototype.toString,r=Math.max,n=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var s=0;s<t.length;s+=1)r[s+e.length]=t[s];return r};e.exports=function(e){var s=this;if("function"!=typeof s||"[object Function]"!==t.apply(s))throw new TypeError("Function.prototype.bind called on incompatible "+s);for(var i,a=function(e){for(var t=[],r=1,n=0;r<e.length;r+=1,n+=1)t[n]=e[r];return t}(arguments),o=r(0,s.length-a.length),l=[],c=0;c<o;c++)l[c]="$"+c;if(i=Function("binder","return function ("+function(e){for(var t="",r=0;r<e.length;r+=1)t+=e[r],r+1<e.length&&(t+=",");return t}(l)+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof i){var t=s.apply(this,n(a,arguments));return Object(t)===t?t:this}return s.apply(e,n(a,arguments))})),s.prototype){var p=function(){};p.prototype=s.prototype,i.prototype=new p,p.prototype=null}return i}},9383:e=>{"use strict";e.exports=Error},9394:(e,t,r)=>{"use strict";var n=r(9211);e.exports=function(){return"function"==typeof Object.is?Object.is:n}},9420:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(329);t.default=function(e,t){return(0,n.default)(e,t,!0)}},9538:e=>{"use strict";e.exports=ReferenceError},9564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(!e||!t)return e;for(const r of n.INHERIT_KEYS.optional)null==e[r]&&(e[r]=t[r]);for(const r of Object.keys(t))"_"===r[0]&&"__clone"!==r&&(e[r]=t[r]);for(const r of n.INHERIT_KEYS.force)e[r]=t[r];return(0,s.default)(e,t),e};var n=r(3422),s=r(8125)},9578:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._call=l,t._getQueueContexts=function(){let e=this,t=this.contexts;for(;!t.length&&(e=e.parentPath,e);)t=e.contexts;return t},t._resyncKey=f,t._resyncList=h,t._resyncParent=d,t._resyncRemoved=function(){null!=this.key&&this.container&&this.container[this.key]===this.node||i._markRemoved.call(this)},t.call=o,t.isDenylisted=c,t.popContext=function(){this.contexts.pop(),this.contexts.length>0?this.setContext(this.contexts[this.contexts.length-1]):this.setContext(void 0)},t.pushContext=function(e){this.contexts.push(e),this.setContext(e)},t.requeue=function(e=this){if(e.removed)return;const t=this.contexts;for(const r of t)r.maybeQueue(e)},t.requeueComputedKeyAndDecorators=function(){const{context:e,node:t}=this;if(!a.isPrivate(t)&&t.computed&&e.maybeQueue(this.get("key")),t.decorators)for(const t of this.get("decorators"))e.maybeQueue(t)},t.resync=function(){this.removed||(d.call(this),h.call(this),f.call(this))},t.setContext=function(e){return null!=this.skipKeys&&(this.skipKeys={}),this._traverseFlags=0,e&&(this.context=e,this.state=e.state,this.opts=e.opts),u.call(this),this},t.setKey=m,t.setScope=u,t.setup=function(e,t,r,n){this.listKey=r,this.container=t,this.parentPath=e||this.parentPath,m.call(this,n)},t.skip=function(){this.shouldSkip=!0},t.skipKey=function(e){null==this.skipKeys&&(this.skipKeys={}),this.skipKeys[e]=!0},t.stop=function(){this._traverseFlags|=s.SHOULD_SKIP|s.SHOULD_STOP},t.visit=function(){var e,t;if(!this.node)return!1;if(this.isDenylisted())return!1;if(null!=(e=(t=this.opts).shouldSkip)&&e.call(t,this))return!1;const r=this.context;return this.shouldSkip||o.call(this,"enter")?(this.debug("Skip..."),this.shouldStop):(p(this,r),this.debug("Recursing into..."),this.shouldStop=(0,n.traverseNode)(this.node,this.opts,this.scope,this.state,this,this.skipKeys),p(this,r),o.call(this,"exit"),this.shouldStop)};var n=r(2264),s=r(9709),i=r(3097),a=r(2352);function o(e){const t=this.opts;return this.debug(e),!(!this.node||!l.call(this,t[e]))||!!this.node&&l.call(this,null==(r=t[this.node.type])?void 0:r[e]);var r}function l(e){if(!e)return!1;for(const t of e){if(!t)continue;const e=this.node;if(!e)return!0;const r=t.call(this.state,this,this.state);if(r&&"object"==typeof r&&"function"==typeof r.then)throw new Error("You appear to be using a plugin with an async traversal visitor, which your current version of Babel does not support. If you're using a published plugin, you may need to upgrade your @babel/core version.");if(r)throw new Error(`Unexpected return value from visitor method ${t}`);if(this.node!==e)return!0;if(this._traverseFlags>0)return!0}return!1}function c(){var e;const t=null!=(e=this.opts.denylist)?e:this.opts.blacklist;return null==t?void 0:t.includes(this.node.type)}function p(e,t){e.context!==t&&(e.context=t,e.state=t.state,e.opts=t.opts)}function u(){var e,t;if(null!=(e=this.opts)&&e.noScope)return;let r,n=this.parentPath;for((("key"===this.key||"decorators"===this.listKey)&&n.isMethod()||"discriminant"===this.key&&n.isSwitchStatement())&&(n=n.parentPath);n&&!r;){var s;if(null!=(s=n.opts)&&s.noScope)return;r=n.scope,n=n.parentPath}this.scope=this.getScope(r),null==(t=this.scope)||t.init()}function d(){this.parentPath&&(this.parent=this.parentPath.node)}function f(){if(this.container&&this.node!==this.container[this.key]){if(Array.isArray(this.container)){for(let e=0;e<this.container.length;e++)if(this.container[e]===this.node)return void m.call(this,e)}else for(const e of Object.keys(this.container))if(this.container[e]===this.node)return void m.call(this,e);this.key=null}}function h(){if(!this.parent||!this.inList)return;const e=this.parent[this.listKey];this.container!==e&&(this.container=e||null)}function m(e){var t;this.key=e,this.node=this.container[this.key],this.type=null==(t=this.node)?void 0:t.type}t.isBlacklisted=c},9594:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenMap=void 0;var n=r(2352);const{traverseFast:s,VISITOR_KEYS:i}=n;t.TokenMap=class{constructor(e,t,r){this._tokens=void 0,this._source=void 0,this._nodesToTokenIndexes=new Map,this._nodesOccurrencesCountCache=new Map,this._tokensCache=new Map,this._tokens=t,this._source=r,s(e,(e=>{const t=this._getTokensIndexesOfNode(e);t.length>0&&this._nodesToTokenIndexes.set(e,t)})),this._tokensCache=null}has(e){return this._nodesToTokenIndexes.has(e)}getIndexes(e){return this._nodesToTokenIndexes.get(e)}find(e,t){const r=this._nodesToTokenIndexes.get(e);if(r)for(let e=0;e<r.length;e++){const n=r[e],s=this._tokens[n];if(t(s,n))return s}return null}findLastIndex(e,t){const r=this._nodesToTokenIndexes.get(e);if(r)for(let e=r.length-1;e>=0;e--){const n=r[e];if(t(this._tokens[n],n))return n}return-1}findMatching(e,t,r=0){const n=this._nodesToTokenIndexes.get(e);if(n){let s=0;const i=r;if(i>1){const n=this._nodesOccurrencesCountCache.get(e);n&&n.test===t&&n.count<i&&(s=n.i+1,r-=n.count+1)}for(;s<n.length;s++){const a=this._tokens[n[s]];if(this.matchesOriginal(a,t)){if(0===r)return i>0&&this._nodesOccurrencesCountCache.set(e,{test:t,count:i,i:s}),a;r--}}}return null}matchesOriginal(e,t){return e.end-e.start===t.length&&(null!=e.value?e.value===t:this._source.startsWith(t,e.start))}startMatches(e,t){const r=this._nodesToTokenIndexes.get(e);if(!r)return!1;const n=this._tokens[r[0]];return n.start===e.start&&this.matchesOriginal(n,t)}endMatches(e,t){const r=this._nodesToTokenIndexes.get(e);if(!r)return!1;const n=this._tokens[r[r.length-1]];return n.end===e.end&&this.matchesOriginal(n,t)}_getTokensIndexesOfNode(e){if(null==e.start||null==e.end)return[];const{first:t,last:r}=this._findTokensOfNode(e,0,this._tokens.length-1);let n=t;const s=function*(e){if("TemplateLiteral"===e.type){yield e.quasis[0];for(let t=1;t<e.quasis.length;t++)yield e.expressions[t-1],yield e.quasis[t];return}const t=i[e.type];for(const r of t){const t=e[r];t&&(Array.isArray(t)?yield*t:yield t)}}(e);"ExportNamedDeclaration"!==e.type&&"ExportDefaultDeclaration"!==e.type||!e.declaration||"ClassDeclaration"!==e.declaration.type||s.next();const a=[];for(const e of s){if(null==e)continue;if(null==e.start||null==e.end)continue;const t=this._findTokensOfNode(e,n,r),s=t.first;for(let e=n;e<s;e++)a.push(e);n=t.last+1}for(let e=n;e<=r;e++)a.push(e);return a}_findTokensOfNode(e,t,r){const n=this._tokensCache.get(e);if(n)return n;const s=this._findFirstTokenOfNode(e.start,t,r),i=this._findLastTokenOfNode(e.end,s,r);return this._tokensCache.set(e,{first:s,last:i}),{first:s,last:i}}_findFirstTokenOfNode(e,t,r){for(;t<=r;){const n=r+t>>1;if(e<this._tokens[n].start)r=n-1;else{if(!(e>this._tokens[n].start))return n;t=n+1}}return t}_findLastTokenOfNode(e,t,r){for(;t<=r;){const n=r+t>>1;if(e<this._tokens[n].end)r=n-1;else{if(!(e>this._tokens[n].end))return n;t=n+1}}return r}}},9597:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function s(e,t){return s=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},s(e,t)}function i(e){return i=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},i(e)}var a,o,l={};function c(e,t,r){r||(r=Error);var a=function(r){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&s(e,t)}(p,r);var a,o,l,c=(o=p,l=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=i(o);if(l){var r=i(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function p(r,n,s){var i;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,p),i=c.call(this,function(e,r,n){return"string"==typeof t?t:t(e,r,n)}(r,n,s)),i.code=e,i}return a=p,Object.defineProperty(a,"prototype",{writable:!1}),a}(r);l[e]=a}function p(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}c("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),c("ERR_INVALID_ARG_TYPE",(function(e,t,s){var i,o,l,c,u;if(void 0===a&&(a=r(4148)),a("string"==typeof e,"'name' must be a string"),"string"==typeof t&&(o="not ",t.substr(0,4)===o)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-9,r)===t}(e," argument"))l="The ".concat(e," ").concat(i," ").concat(p(t,"type"));else{var d=("number"!=typeof u&&(u=0),u+1>(c=e).length||-1===c.indexOf(".",u)?"argument":"property");l='The "'.concat(e,'" ').concat(d," ").concat(i," ").concat(p(t,"type"))}return l+". Received type ".concat(n(s))}),TypeError),c("ERR_INVALID_ARG_VALUE",(function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"is invalid";void 0===o&&(o=r(537));var s=o.inspect(t);return s.length>128&&(s="".concat(s.slice(0,128),"...")),"The argument '".concat(e,"' ").concat(n,". Received ").concat(s)}),TypeError,RangeError),c("ERR_INVALID_RETURN_VALUE",(function(e,t,r){var s;return s=r&&r.constructor&&r.constructor.name?"instance of ".concat(r.constructor.name):"type ".concat(n(r)),"Expected ".concat(e,' to be returned from the "').concat(t,'"')+" function but got ".concat(s,".")}),TypeError),c("ERR_MISSING_ARGS",(function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];void 0===a&&(a=r(4148)),a(t.length>0,"At least one arg needs to be specified");var s="The ",i=t.length;switch(t=t.map((function(e){return'"'.concat(e,'"')})),i){case 1:s+="".concat(t[0]," argument");break;case 2:s+="".concat(t[0]," and ").concat(t[1]," arguments");break;default:s+=t.slice(0,i-1).join(", "),s+=", and ".concat(t[i-1]," arguments")}return"".concat(s," must be specified")}),TypeError),e.exports.codes=l},9600:e=>{"use strict";var t,r,n=Function.prototype.toString,s="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof s&&"function"==typeof Object.defineProperty)try{t=Object.defineProperty({},"length",{get:function(){throw r}}),r={},s((function(){throw 42}),null,t)}catch(e){e!==r&&(s=null)}else s=null;var i=/^\s*class\b/,a=function(e){try{var t=n.call(e);return i.test(t)}catch(e){return!1}},o=function(e){try{return!a(e)&&(n.call(e),!0)}catch(e){return!1}},l=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,p=!(0 in[,]),u=function(){return!1};if("object"==typeof document){var d=document.all;l.call(d)===l.call(document.all)&&(u=function(e){if((p||!e)&&(void 0===e||"object"==typeof e))try{var t=l.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}e.exports=s?function(e){if(u(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{s(e,null,t)}catch(e){if(e!==r)return!1}return!a(e)&&o(e)}:function(e){if(u(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return o(e);if(a(e))return!1;var t=l.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&o(e)}},9612:e=>{"use strict";e.exports=Object},9618:(e,t,r)=>{"use strict";function n(){const e=r(7975);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){const{filename:t,cwd:r,filenameRelative:s=("string"==typeof t?n().relative(r,t):"unknown"),sourceType:i="module",inputSourceMap:a,sourceMaps:o=!!a,sourceRoot:l=e.options.moduleRoot,sourceFileName:c=n().basename(s),comments:p=!0,compact:u="auto"}=e.options,d=e.options,f=Object.assign({},d,{parserOpts:Object.assign({sourceType:".mjs"===n().extname(s)?"module":i,sourceFileName:t,plugins:[]},d.parserOpts),generatorOpts:Object.assign({filename:t,auxiliaryCommentBefore:d.auxiliaryCommentBefore,auxiliaryCommentAfter:d.auxiliaryCommentAfter,retainLines:d.retainLines,comments:p,shouldPrintComment:d.shouldPrintComment,compact:u,minified:d.minified,sourceMaps:o,sourceRoot:l,sourceFileName:c},d.generatorOpts)});for(const t of e.passes)for(const e of t)e.manipulateOptions&&e.manipulateOptions(f,f.parserOpts);return f}},9638:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExportAllDeclaration=function(e){var t,r;this.word("export"),this.space(),"type"===e.exportKind&&(this.word("type"),this.space()),this.tokenChar(42),this.space(),this.word("from"),this.space(),null!=(t=e.attributes)&&t.length||null!=(r=e.assertions)&&r.length?(this.print(e.source,!0),this.space(),this._printAttributes(e,!1)):this.print(e.source),this.semicolon()},t.ExportDefaultDeclaration=function(e){d(this,e),this.word("export"),this.noIndentInnerCommentsHere(),this.space(),this.word("default"),this.space(),this.tokenContext|=s.TokenContext.exportDefault;const t=e.declaration;this.print(t),p(t)||this.semicolon()},t.ExportDefaultSpecifier=function(e){this.print(e.exported)},t.ExportNamedDeclaration=function(e){if(d(this,e),this.word("export"),this.space(),e.declaration){const t=e.declaration;this.print(t),p(t)||this.semicolon()}else{"type"===e.exportKind&&(this.word("type"),this.space());const n=e.specifiers.slice(0);let s=!1;for(;;){const e=n[0];if(!a(e)&&!o(e))break;s=!0,this.print(n.shift()),n.length&&(this.tokenChar(44),this.space())}let i=!1;var t,r;(n.length||!n.length&&!s)&&(i=!0,this.tokenChar(123),n.length&&(this.space(),this.printList(n,this.shouldPrintTrailingComma("}")),this.space()),this.tokenChar(125)),e.source&&(this.space(),this.word("from"),this.space(),null!=(t=e.attributes)&&t.length||null!=(r=e.assertions)&&r.length?(this.print(e.source,!0),this.space(),this._printAttributes(e,i)):this.print(e.source)),this.semicolon()}},t.ExportNamespaceSpecifier=function(e){this.tokenChar(42),this.space(),this.word("as"),this.space(),this.print(e.exported)},t.ExportSpecifier=function(e){"type"===e.exportKind&&(this.word("type"),this.space()),this.print(e.local),e.exported&&e.local.name!==e.exported.name&&(this.space(),this.word("as"),this.space(),this.print(e.exported))},t.ImportAttribute=function(e){this.print(e.key),this.tokenChar(58),this.space(),this.print(e.value)},t.ImportDeclaration=function(e){var t,r;this.word("import"),this.space();const n="type"===e.importKind||"typeof"===e.importKind;n?(this.noIndentInnerCommentsHere(),this.word(e.importKind),this.space()):e.module?(this.noIndentInnerCommentsHere(),this.word("module"),this.space()):e.phase&&(this.noIndentInnerCommentsHere(),this.word(e.phase),this.space());const s=e.specifiers.slice(0),i=!!s.length;for(;i;){const e=s[0];if(!l(e)&&!c(e))break;this.print(s.shift()),s.length&&(this.tokenChar(44),this.space())}let a=!1;s.length?(a=!0,this.tokenChar(123),this.space(),this.printList(s,this.shouldPrintTrailingComma("}")),this.space(),this.tokenChar(125)):n&&!i&&(a=!0,this.tokenChar(123),this.tokenChar(125)),(i||n)&&(this.space(),this.word("from"),this.space()),null!=(t=e.attributes)&&t.length||null!=(r=e.assertions)&&r.length?(this.print(e.source,!0),this.space(),this._printAttributes(e,a)):this.print(e.source),this.semicolon()},t.ImportDefaultSpecifier=function(e){this.print(e.local)},t.ImportExpression=function(e){this.word("import"),e.phase&&(this.tokenChar(46),this.word(e.phase)),this.tokenChar(40),this.print(e.source),null!=e.options&&(this.tokenChar(44),this.space(),this.print(e.options)),this.tokenChar(41)},t.ImportNamespaceSpecifier=function(e){this.tokenChar(42),this.space(),this.word("as"),this.space(),this.print(e.local)},t.ImportSpecifier=function(e){"type"!==e.importKind&&"typeof"!==e.importKind||(this.word(e.importKind),this.space()),this.print(e.imported),e.local&&e.local.name!==e.imported.name&&(this.space(),this.word("as"),this.space(),this.print(e.local))},t._printAttributes=function(e,t){const{importAttributesKeyword:r}=this.format,{attributes:n,assertions:s}=e;!n||r||u||(u=!0,console.warn('You are using import attributes, without specifying the desired output syntax.\nPlease specify the "importAttributesKeyword" generator option, whose value can be one of:\n - "with" : `import { a } from "b" with { type: "json" };`\n - "assert" : `import { a } from "b" assert { type: "json" };`\n - "with-legacy" : `import { a } from "b" with type: "json";`\n'));const i="assert"===r||!r&&s;if(this.word(i?"assert":"with"),this.space(),!i&&"with"!==r)return void this.printList(n||s);const a=t?1:0;this.token("{",null,a),this.space(),this.printList(n||s,this.shouldPrintTrailingComma("}")),this.space(),this.token("}",null,a)};var n=r(2352),s=r(1373);const{isClassDeclaration:i,isExportDefaultSpecifier:a,isExportNamespaceSpecifier:o,isImportDefaultSpecifier:l,isImportNamespaceSpecifier:c,isStatement:p}=n;let u=!1;function d(e,t){i(t.declaration)&&e._shouldPrintDecoratorsBeforeExport(t)&&e.printJoin(t.declaration.decorators)}},9675:e=>{"use strict";e.exports=TypeError},9709:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.SHOULD_STOP=t.SHOULD_SKIP=t.REMOVED=void 0;var n=r(5562),s=r(7833),i=r(5781),a=r(6814),o=r(2352),l=o,c=r(7411),p=r(8992),u=r(940),d=r(7317),f=r(2037),h=r(299),m=r(2257),y=r(854),g=r(9578),b=g,v=r(3097),T=r(8345),x=r(6109),S=r(3383),E=r(7973);const{validate:P}=o,A=s("babel"),w=(t.REMOVED=1,t.SHOULD_STOP=2,t.SHOULD_SKIP=4,t.default=class e{constructor(e,t){this.contexts=[],this.state=null,this.opts=null,this._traverseFlags=0,this.skipKeys=null,this.parentPath=null,this.container=null,this.listKey=null,this.key=null,this.node=null,this.type=null,this.parent=t,this.hub=e,this.data=null,this.context=null,this.scope=null}get removed(){return(1&this._traverseFlags)>0}set removed(e){e?this._traverseFlags|=1:this._traverseFlags&=-2}get shouldStop(){return(2&this._traverseFlags)>0}set shouldStop(e){e?this._traverseFlags|=2:this._traverseFlags&=-3}get shouldSkip(){return(4&this._traverseFlags)>0}set shouldSkip(e){e?this._traverseFlags|=4:this._traverseFlags&=-5}static get({hub:t,parentPath:r,parent:n,container:s,listKey:i,key:a}){if(!t&&r&&(t=r.hub),!n)throw new Error("To get a node path the parent needs to exist");const o=s[a],l=c.getOrCreateCachedPaths(t,n);let p=l.get(o);return p||(p=new e(t,n),o&&l.set(o,p)),g.setup.call(p,r,s,i,a),p}getScope(e){return this.isScope()?new a.default(this):e}setData(e,t){return null==this.data&&(this.data=Object.create(null)),this.data[e]=t}getData(e,t){null==this.data&&(this.data=Object.create(null));let r=this.data[e];return void 0===r&&void 0!==t&&(r=this.data[e]=t),r}hasNode(){return null!=this.node}buildCodeFrameError(e,t=SyntaxError){return this.hub.buildError(this.node,e,t)}traverse(e,t){(0,i.default)(this.node,e,this.scope,t,this)}set(e,t){P(this.node,e,t),this.node[e]=t}getPathLocation(){const e=[];let t=this;do{let r=t.key;t.inList&&(r=`${t.listKey}[${r}]`),e.unshift(r)}while(t=t.parentPath);return e.join(".")}debug(e){A.enabled&&A(`${this.getPathLocation()} ${this.type}: ${e}`)}toString(){return(0,p.default)(this.node).code}get inList(){return!!this.listKey}set inList(e){e||(this.listKey=null)}get parentKey(){return this.listKey||this.key}}),C={findParent:u.findParent,find:u.find,getFunctionParent:u.getFunctionParent,getStatementParent:u.getStatementParent,getEarliestCommonAncestorFrom:u.getEarliestCommonAncestorFrom,getDeepestCommonAncestorFrom:u.getDeepestCommonAncestorFrom,getAncestry:u.getAncestry,isAncestor:u.isAncestor,isDescendant:u.isDescendant,inType:u.inType,getTypeAnnotation:d.getTypeAnnotation,isBaseType:d.isBaseType,couldBeBaseType:d.couldBeBaseType,baseTypeStrictlyMatches:d.baseTypeStrictlyMatches,isGenericType:d.isGenericType,replaceWithMultiple:f.replaceWithMultiple,replaceWithSourceString:f.replaceWithSourceString,replaceWith:f.replaceWith,replaceExpressionWithStatements:f.replaceExpressionWithStatements,replaceInline:f.replaceInline,evaluateTruthy:h.evaluateTruthy,evaluate:h.evaluate,toComputedKey:m.toComputedKey,ensureBlock:m.ensureBlock,unwrapFunctionEnvironment:m.unwrapFunctionEnvironment,arrowFunctionToExpression:m.arrowFunctionToExpression,splitExportDeclaration:m.splitExportDeclaration,ensureFunctionName:m.ensureFunctionName,matchesPattern:y.matchesPattern,isStatic:y.isStatic,isNodeType:y.isNodeType,canHaveVariableDeclarationOrExpression:y.canHaveVariableDeclarationOrExpression,canSwapBetweenExpressionAndStatement:y.canSwapBetweenExpressionAndStatement,isCompletionRecord:y.isCompletionRecord,isStatementOrBlock:y.isStatementOrBlock,referencesImport:y.referencesImport,getSource:y.getSource,willIMaybeExecuteBefore:y.willIMaybeExecuteBefore,_guessExecutionStatusRelativeTo:y._guessExecutionStatusRelativeTo,resolve:y.resolve,isConstantExpression:y.isConstantExpression,isInStrictMode:y.isInStrictMode,isDenylisted:b.isDenylisted,visit:b.visit,skip:b.skip,skipKey:b.skipKey,stop:b.stop,setContext:b.setContext,requeue:b.requeue,requeueComputedKeyAndDecorators:b.requeueComputedKeyAndDecorators,remove:v.remove,insertBefore:T.insertBefore,insertAfter:T.insertAfter,unshiftContainer:T.unshiftContainer,pushContainer:T.pushContainer,getOpposite:x.getOpposite,getCompletionRecords:x.getCompletionRecords,getSibling:x.getSibling,getPrevSibling:x.getPrevSibling,getNextSibling:x.getNextSibling,getAllNextSiblings:x.getAllNextSiblings,getAllPrevSiblings:x.getAllPrevSiblings,get:x.get,getAssignmentIdentifiers:x.getAssignmentIdentifiers,getBindingIdentifiers:x.getBindingIdentifiers,getOuterBindingIdentifiers:x.getOuterBindingIdentifiers,getBindingIdentifierPaths:x.getBindingIdentifierPaths,getOuterBindingIdentifierPaths:x.getOuterBindingIdentifierPaths,shareCommentsWithSiblings:S.shareCommentsWithSiblings,addComment:S.addComment,addComments:S.addComments};Object.assign(w.prototype,C),w.prototype.arrowFunctionToShadowed=m[String("arrowFunctionToShadowed")],Object.assign(w.prototype,{has:y[String("has")],is:y[String("is")],isnt:y[String("isnt")],equals:y[String("equals")],hoist:T[String("hoist")],updateSiblingKeys:T.updateSiblingKeys,call:b.call,isBlacklisted:b[String("isBlacklisted")],setScope:b.setScope,resync:b.resync,popContext:b.popContext,pushContext:b.pushContext,setup:b.setup,setKey:b.setKey}),w.prototype._guessExecutionStatusRelativeToDifferentFunctions=y._guessExecutionStatusRelativeTo,w.prototype._guessExecutionStatusRelativeToDifferentFunctions=y._guessExecutionStatusRelativeTo,Object.assign(w.prototype,{_getTypeAnnotation:d._getTypeAnnotation,_replaceWith:f._replaceWith,_resolve:y._resolve,_call:b._call,_resyncParent:b._resyncParent,_resyncKey:b._resyncKey,_resyncList:b._resyncList,_resyncRemoved:b._resyncRemoved,_getQueueContexts:b._getQueueContexts,_removeFromScope:v._removeFromScope,_callRemovalHooks:v._callRemovalHooks,_remove:v._remove,_markRemoved:v._markRemoved,_assertUnremoved:v._assertUnremoved,_containerInsert:T._containerInsert,_containerInsertBefore:T._containerInsertBefore,_containerInsertAfter:T._containerInsertAfter,_verifyNodeList:T._verifyNodeList,_getKey:x._getKey,_getPattern:x._getPattern});for(const e of l.TYPES){const t=`is${e}`,r=l[t];w.prototype[t]=function(e){return r(this.node,e)},w.prototype[`assert${e}`]=function(t){if(!r(this.node,t))throw new TypeError(`Expected node path of type ${e}`)}}Object.assign(w.prototype,E);for(const e of Object.keys(n))"_"!==e[0]&&(l.TYPES.includes(e)||l.TYPES.push(e))},9721:(e,t,r)=>{"use strict";var n=r(6556),s=r(4035),i=n("RegExp.prototype.exec"),a=r(9675);e.exports=function(e){if(!s(e))throw new a("`regex` must be a RegExp");return function(t){return null!==i(e,t)}}},9722:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return!!(0,n.default)(e.type,"Immutable")||!!(0,s.isIdentifier)(e)&&"undefined"===e.name};var n=r(4460),s=r(8960)},9749:(e,t,r)=>{"use strict";const n=r(8799),s=Symbol("max"),i=Symbol("length"),a=Symbol("lengthCalculator"),o=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),p=Symbol("noDisposeOnSet"),u=Symbol("lruList"),d=Symbol("cache"),f=Symbol("updateAgeOnGet"),h=()=>1,m=(e,t,r)=>{const n=e[d].get(t);if(n){const t=n.value;if(y(e,t)){if(b(e,n),!e[o])return}else r&&(e[f]&&(n.value.now=Date.now()),e[u].unshiftNode(n));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[l])return!1;const r=Date.now()-t.now;return t.maxAge?r>t.maxAge:e[l]&&r>e[l]},g=e=>{if(e[i]>e[s])for(let t=e[u].tail;e[i]>e[s]&&null!==t;){const r=t.prev;b(e,t),t=r}},b=(e,t)=>{if(t){const r=t.value;e[c]&&e[c](r.key,r.value),e[i]-=r.length,e[d].delete(r.key),e[u].removeNode(t)}};class v{constructor(e,t,r,n,s){this.key=e,this.value=t,this.length=r,this.now=n,this.maxAge=s||0}}const T=(e,t,r,n)=>{let s=r.value;y(e,s)&&(b(e,r),e[o]||(s=void 0)),s&&t.call(n,s.value,s.key,e)};e.exports=class{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[s]=e.max||1/0;const t=e.length||h;if(this[a]="function"!=typeof t?h:t,this[o]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[l]=e.maxAge||0,this[c]=e.dispose,this[p]=e.noDisposeOnSet||!1,this[f]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[s]=e||1/0,g(this)}get max(){return this[s]}set allowStale(e){this[o]=!!e}get allowStale(){return this[o]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[l]=e,g(this)}get maxAge(){return this[l]}set lengthCalculator(e){"function"!=typeof e&&(e=h),e!==this[a]&&(this[a]=e,this[i]=0,this[u].forEach((e=>{e.length=this[a](e.value,e.key),this[i]+=e.length}))),g(this)}get lengthCalculator(){return this[a]}get length(){return this[i]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let r=this[u].tail;null!==r;){const n=r.prev;T(this,e,r,t),r=n}}forEach(e,t){t=t||this;for(let r=this[u].head;null!==r;){const n=r.next;T(this,e,r,t),r=n}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[c]&&this[u]&&this[u].length&&this[u].forEach((e=>this[c](e.key,e.value))),this[d]=new Map,this[u]=new n,this[i]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,r){if((r=r||this[l])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,o=this[a](t,e);if(this[d].has(e)){if(o>this[s])return b(this,this[d].get(e)),!1;const a=this[d].get(e).value;return this[c]&&(this[p]||this[c](e,a.value)),a.now=n,a.maxAge=r,a.value=t,this[i]+=o-a.length,a.length=o,this.get(e),g(this),!0}const f=new v(e,t,o,n,r);return f.length>this[s]?(this[c]&&this[c](e,t),!1):(this[i]+=f.length,this[u].unshift(f),this[d].set(e,this[u].head),g(this),!0)}has(e){if(!this[d].has(e))return!1;const t=this[d].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[d].get(e))}load(e){this.reset();const t=Date.now();for(let r=e.length-1;r>=0;r--){const n=e[r],s=n.e||0;if(0===s)this.set(n.k,n.v);else{const e=s-t;e>0&&this.set(n.k,n.v,e)}}}prune(){this[d].forEach(((e,t)=>m(this,t,!1)))}}},9757:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(4148),s=r(2352),i=r(4418),a=r(6818);const{identifier:o,importSpecifier:l,numericLiteral:c,sequenceExpression:p,isImportDeclaration:u}=s;function d(e){return"type"!==e.importKind&&"typeof"!==e.importKind}function f(e){return 1===e.specifiers.length&&"ImportNamespaceSpecifier"===e.specifiers[0].type||2===e.specifiers.length&&"ImportNamespaceSpecifier"===e.specifiers[1].type}function h(e){return e.specifiers.length>0&&"ImportDefaultSpecifier"===e.specifiers[0].type}function m(e,t){return e.specifiers.length?!t.specifiers.length||!f(e)&&!f(t)&&(h(t)&&(h(e)?t.specifiers[0]=l(t.specifiers[0].local,o("default")):e.specifiers.unshift(t.specifiers.shift())),e.specifiers.push(...t.specifiers),!0):(e.specifiers=t.specifiers,!0)}t.default=class{constructor(e,t,r){this._defaultOpts={importedSource:null,importedType:"commonjs",importedInterop:"babel",importingInterop:"babel",ensureLiveReference:!1,ensureNoContext:!1,importPosition:"before"};const n=e.find((e=>e.isProgram()));this._programPath=n,this._programScope=n.scope,this._hub=n.hub,this._defaultOpts=this._applyDefaults(t,r,!0)}addDefault(e,t){return this.addNamed("default",e,t)}addNamed(e,t,r){return n("string"==typeof e),this._generateImport(this._applyDefaults(t,r),e)}addNamespace(e,t){return this._generateImport(this._applyDefaults(e,t),null)}addSideEffect(e,t){return this._generateImport(this._applyDefaults(e,t),void 0)}_applyDefaults(e,t,r=!1){let s;return"string"==typeof e?s=Object.assign({},this._defaultOpts,{importedSource:e},t):(n(!t,"Unexpected secondary arguments."),s=Object.assign({},this._defaultOpts,e)),!r&&t&&(void 0!==t.nameHint&&(s.nameHint=t.nameHint),void 0!==t.blockHoist&&(s.blockHoist=t.blockHoist)),s}_generateImport(e,t){const r="default"===t,n=!!t&&!r,s=null===t,{importedSource:o,importedType:l,importedInterop:u,importingInterop:d,ensureLiveReference:f,ensureNoContext:h,nameHint:m,importPosition:y,blockHoist:g}=e;let b=m||t;const v=(0,a.default)(this._programPath),T=v&&"node"===d,x=v&&"babel"===d;if("after"===y&&!v)throw new Error('"importPosition": "after" is only supported in modules');const S=new i.default(o,this._programScope,this._hub);if("es6"===l){if(!T&&!x)throw new Error("Cannot import an ES6 module from CommonJS");S.import(),s?S.namespace(m||o):(r||n)&&S.named(b,t)}else{if("commonjs"!==l)throw new Error(`Unexpected interopType "${l}"`);if("babel"===u)if(T){b="default"!==b?b:o;const e=`${o}$es6Default`;S.import(),s?S.default(e).var(b||o).wildcardInterop():r?f?S.default(e).var(b||o).defaultInterop().read("default"):S.default(e).var(b).defaultInterop().prop(t):n&&S.default(e).read(t)}else x?(S.import(),s?S.namespace(b||o):(r||n)&&S.named(b,t)):(S.require(),s?S.var(b||o).wildcardInterop():(r||n)&&f?r?(b="default"!==b?b:o,S.var(b).read(t),S.defaultInterop()):S.var(o).read(t):r?S.var(b).defaultInterop().prop(t):n&&S.var(b).prop(t));else if("compiled"===u)T?(S.import(),s?S.default(b||o):(r||n)&&S.default(o).read(b)):x?(S.import(),s?S.namespace(b||o):(r||n)&&S.named(b,t)):(S.require(),s?S.var(b||o):(r||n)&&(f?S.var(o).read(b):S.prop(t).var(b)));else{if("uncompiled"!==u)throw new Error(`Unknown importedInterop "${u}".`);if(r&&f)throw new Error("No live reference for commonjs default");T?(S.import(),s?S.default(b||o):r?S.default(b):n&&S.default(o).read(b)):x?(S.import(),s?S.default(b||o):r?S.default(b):n&&S.named(b,t)):(S.require(),s?S.var(b||o):r?S.var(b):n&&(f?S.var(o).read(b):S.var(b).prop(t)))}}const{statements:E,resultName:P}=S.done();return this._insertStatements(E,y,g),(r||n)&&h&&"Identifier"!==P.type?p([c(0),P]):P}_insertStatements(e,t="before",r=3){if("after"===t){if(this._insertStatementsAfter(e))return}else if(this._insertStatementsBefore(e,r))return;this._programPath.unshiftContainer("body",e)}_insertStatementsBefore(e,t){if(1===e.length&&u(e[0])&&d(e[0])){const t=this._programPath.get("body").find((e=>e.isImportDeclaration()&&d(e.node)));if((null==t?void 0:t.node.source.value)===e[0].source.value&&m(t.node,e[0]))return!0}e.forEach((e=>{e._blockHoist=t}));const r=this._programPath.get("body").find((e=>{const t=e.node._blockHoist;return Number.isFinite(t)&&t<4}));return!!r&&(r.insertBefore(e),!0)}_insertStatementsAfter(e){const t=new Set(e),r=new Map;for(const t of e)if(u(t)&&d(t)){const e=t.source.value;r.has(e)||r.set(e,[]),r.get(e).push(t)}let n=null;for(const e of this._programPath.get("body"))if(e.isImportDeclaration()&&d(e.node)){n=e;const s=e.node.source.value,i=r.get(s);if(!i)continue;for(const r of i)t.has(r)&&m(e.node,r)&&t.delete(r)}return 0===t.size||(n&&n.insertAfter(Array.from(t)),!!n)}}},9793:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ALIAS_KEYS",{enumerable:!0,get:function(){return n.ALIAS_KEYS}}),Object.defineProperty(t,"BUILDER_KEYS",{enumerable:!0,get:function(){return n.BUILDER_KEYS}}),Object.defineProperty(t,"DEPRECATED_ALIASES",{enumerable:!0,get:function(){return i.DEPRECATED_ALIASES}}),Object.defineProperty(t,"DEPRECATED_KEYS",{enumerable:!0,get:function(){return n.DEPRECATED_KEYS}}),Object.defineProperty(t,"FLIPPED_ALIAS_KEYS",{enumerable:!0,get:function(){return n.FLIPPED_ALIAS_KEYS}}),Object.defineProperty(t,"NODE_FIELDS",{enumerable:!0,get:function(){return n.NODE_FIELDS}}),Object.defineProperty(t,"NODE_PARENT_VALIDATIONS",{enumerable:!0,get:function(){return n.NODE_PARENT_VALIDATIONS}}),Object.defineProperty(t,"PLACEHOLDERS",{enumerable:!0,get:function(){return s.PLACEHOLDERS}}),Object.defineProperty(t,"PLACEHOLDERS_ALIAS",{enumerable:!0,get:function(){return s.PLACEHOLDERS_ALIAS}}),Object.defineProperty(t,"PLACEHOLDERS_FLIPPED_ALIAS",{enumerable:!0,get:function(){return s.PLACEHOLDERS_FLIPPED_ALIAS}}),t.TYPES=void 0,Object.defineProperty(t,"VISITOR_KEYS",{enumerable:!0,get:function(){return n.VISITOR_KEYS}}),r(5158),r(9897),r(6184),r(5589),r(7095),r(6106);var n=r(7596),s=r(9187),i=r(5689);Object.keys(i.DEPRECATED_ALIASES).forEach((e=>{n.FLIPPED_ALIAS_KEYS[e]=n.FLIPPED_ALIAS_KEYS[i.DEPRECATED_ALIASES[e]]})),t.TYPES=[].concat(Object.keys(n.VISITOR_KEYS),Object.keys(n.FLIPPED_ALIAS_KEYS),Object.keys(n.DEPRECATED_KEYS))},9815:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.merge=function(e,t){const{placeholderWhitelist:r=e.placeholderWhitelist,placeholderPattern:n=e.placeholderPattern,preserveComments:s=e.preserveComments,syntacticPlaceholders:i=e.syntacticPlaceholders}=t;return{parser:Object.assign({},e.parser,t.parser),placeholderWhitelist:r,placeholderPattern:n,preserveComments:s,syntacticPlaceholders:i}},t.normalizeReplacements=function(e){if(Array.isArray(e))return e.reduce(((e,t,r)=>(e["$"+r]=t,e)),{});if("object"==typeof e||null==e)return e||void 0;throw new Error("Template replacements must be an array, object, null, or undefined")},t.validate=function(e){if(null!=e&&"object"!=typeof e)throw new Error("Unknown template options.");const t=e||{},{placeholderWhitelist:n,placeholderPattern:s,preserveComments:i,syntacticPlaceholders:a}=t,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}(t,r);if(null!=n&&!(n instanceof Set))throw new Error("'.placeholderWhitelist' must be a Set, null, or undefined");if(null!=s&&!(s instanceof RegExp)&&!1!==s)throw new Error("'.placeholderPattern' must be a RegExp, false, null, or undefined");if(null!=i&&"boolean"!=typeof i)throw new Error("'.preserveComments' must be a boolean, null, or undefined");if(null!=a&&"boolean"!=typeof a)throw new Error("'.syntacticPlaceholders' must be a boolean, null, or undefined");if(!0===a&&(null!=n||null!=s))throw new Error("'.placeholderWhitelist' and '.placeholderPattern' aren't compatible with '.syntacticPlaceholders: true'");return{parser:o,placeholderWhitelist:n||void 0,placeholderPattern:null==s?void 0:s,preserveComments:null==i?void 0:i,syntacticPlaceholders:null==a?void 0:a}};const r=["placeholderWhitelist","placeholderPattern","preserveComments","syntacticPlaceholders"]},9889:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(2485);function s(e,t,r){return Object.freeze({minVersion:e,ast:()=>n.default.program.ast(t,{preserveComments:!0}),metadata:r})}const i=t.default={__proto__:null,OverloadYield:s("7.18.14","function _OverloadYield(e,d){this.v=e,this.k=d}",{globals:[],locals:{_OverloadYield:["body.0.id"]},exportBindingAssignments:[],exportName:"_OverloadYield",dependencies:{}}),applyDecoratedDescriptor:s("7.0.0-beta.0",'function _applyDecoratedDescriptor(i,e,r,n,l){var a={};return Object.keys(n).forEach((function(i){a[i]=n[i]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce((function(r,n){return n(i,e,r)||r}),a),l&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(l):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(i,e,a),null):a}',{globals:["Object"],locals:{_applyDecoratedDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_applyDecoratedDescriptor",dependencies:{}}),applyDecs2311:s("7.24.0",'function applyDecs2311(e,t,n,r,o,i){var a,c,u,s,f,l,p,d=Symbol.metadata||Symbol.for("Symbol.metadata"),m=Object.defineProperty,h=Object.create,y=[h(null),h(null)],v=t.length;function g(t,n,r){return function(o,i){n&&(i=o,o=e);for(var a=0;a<t.length;a++)i=t[a].apply(o,r?[i]:[]);return r?i:o}}function b(e,t,n,r){if("function"!=typeof e&&(r||void 0!==e))throw new TypeError(t+" must "+(n||"be")+" a function"+(r?"":" or undefined"));return e}function applyDec(e,t,n,r,o,i,u,s,f,l,p){function d(e){if(!p(e))throw new TypeError("Attempted to access private element on non-instance")}var h=[].concat(t[0]),v=t[3],w=!u,D=1===o,S=3===o,j=4===o,E=2===o;function I(t,n,r){return function(o,i){return n&&(i=o,o=e),r&&r(o),P[t].call(o,i)}}if(!w){var P={},k=[],F=S?"get":j||D?"set":"value";if(f?(l||D?P={get:setFunctionName((function(){return v(this)}),r,"get"),set:function(e){t[4](this,e)}}:P[F]=v,l||setFunctionName(P[F],r,E?"":F)):l||(P=Object.getOwnPropertyDescriptor(e,r)),!l&&!f){if((c=y[+s][r])&&7!=(c^o))throw Error("Decorating two elements with the same name ("+P[F].name+") is not supported yet");y[+s][r]=o<3?1:o}}for(var N=e,O=h.length-1;O>=0;O-=n?2:1){var T=b(h[O],"A decorator","be",!0),z=n?h[O-1]:void 0,A={},H={kind:["field","accessor","method","getter","setter","class"][o],name:r,metadata:a,addInitializer:function(e,t){if(e.v)throw new TypeError("attempted to call addInitializer after decoration was finished");b(t,"An initializer","be",!0),i.push(t)}.bind(null,A)};if(w)c=T.call(z,N,H),A.v=1,b(c,"class decorators","return")&&(N=c);else if(H.static=s,H.private=f,c=H.access={has:f?p.bind():function(e){return r in e}},j||(c.get=f?E?function(e){return d(e),P.value}:I("get",0,d):function(e){return e[r]}),E||S||(c.set=f?I("set",0,d):function(e,t){e[r]=t}),N=T.call(z,D?{get:P.get,set:P.set}:P[F],H),A.v=1,D){if("object"==typeof N&&N)(c=b(N.get,"accessor.get"))&&(P.get=c),(c=b(N.set,"accessor.set"))&&(P.set=c),(c=b(N.init,"accessor.init"))&&k.unshift(c);else if(void 0!==N)throw new TypeError("accessor decorators must return an object with get, set, or init properties or undefined")}else b(N,(l?"field":"method")+" decorators","return")&&(l?k.unshift(N):P[F]=N)}return o<2&&u.push(g(k,s,1),g(i,s,0)),l||w||(f?D?u.splice(-1,0,I("get",s),I("set",s)):u.push(E?P[F]:b.call.bind(P[F])):m(e,r,P)),N}function w(e){return m(e,d,{configurable:!0,enumerable:!0,value:a})}return void 0!==i&&(a=i[d]),a=h(null==a?null:a),f=[],l=function(e){e&&f.push(g(e))},p=function(t,r){for(var i=0;i<n.length;i++){var a=n[i],c=a[1],l=7&c;if((8&c)==t&&!l==r){var p=a[2],d=!!a[3],m=16&c;applyDec(t?e:e.prototype,a,m,d?"#"+p:toPropertyKey(p),l,l<2?[]:t?s=s||[]:u=u||[],f,!!t,d,r,t&&d?function(t){return checkInRHS(t)===e}:o)}}},p(8,0),p(0,0),p(8,1),p(0,1),l(u),l(s),c=f,v||w(e),{e:c,get c(){var n=[];return v&&[w(e=applyDec(e,[t],r,e.name,5,n)),g(n,1)]}}}',{globals:["Symbol","Object","TypeError","Error"],locals:{applyDecs2311:["body.0.id"]},exportBindingAssignments:[],exportName:"applyDecs2311",dependencies:{checkInRHS:["body.0.body.body.5.argument.expressions.4.right.body.body.0.body.body.1.consequent.body.1.expression.arguments.10.consequent.body.body.0.argument.left.callee"],setFunctionName:["body.0.body.body.3.body.body.3.consequent.body.1.test.expressions.0.consequent.expressions.0.consequent.right.properties.0.value.callee","body.0.body.body.3.body.body.3.consequent.body.1.test.expressions.0.consequent.expressions.1.right.callee"],toPropertyKey:["body.0.body.body.5.argument.expressions.4.right.body.body.0.body.body.1.consequent.body.1.expression.arguments.3.alternate.callee"]}}),arrayLikeToArray:s("7.9.0","function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}",{globals:["Array"],locals:{_arrayLikeToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_arrayLikeToArray",dependencies:{}}),arrayWithHoles:s("7.0.0-beta.0","function _arrayWithHoles(r){if(Array.isArray(r))return r}",{globals:["Array"],locals:{_arrayWithHoles:["body.0.id"]},exportBindingAssignments:[],exportName:"_arrayWithHoles",dependencies:{}}),arrayWithoutHoles:s("7.0.0-beta.0","function _arrayWithoutHoles(r){if(Array.isArray(r))return arrayLikeToArray(r)}",{globals:["Array"],locals:{_arrayWithoutHoles:["body.0.id"]},exportBindingAssignments:[],exportName:"_arrayWithoutHoles",dependencies:{arrayLikeToArray:["body.0.body.body.0.consequent.argument.callee"]}}),assertClassBrand:s("7.24.0",'function _assertClassBrand(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}',{globals:["TypeError"],locals:{_assertClassBrand:["body.0.id"]},exportBindingAssignments:[],exportName:"_assertClassBrand",dependencies:{}}),assertThisInitialized:s("7.0.0-beta.0","function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return e}",{globals:["ReferenceError"],locals:{_assertThisInitialized:["body.0.id"]},exportBindingAssignments:[],exportName:"_assertThisInitialized",dependencies:{}}),asyncGeneratorDelegate:s("7.0.0-beta.0",'function _asyncGeneratorDelegate(t){var e={},n=!1;function pump(e,r){return n=!0,r=new Promise((function(n){n(t[e](r))})),{done:!1,value:new OverloadYield(r,1)}}return e["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},e.next=function(t){return n?(n=!1,t):pump("next",t)},"function"==typeof t.throw&&(e.throw=function(t){if(n)throw n=!1,t;return pump("throw",t)}),"function"==typeof t.return&&(e.return=function(t){return n?(n=!1,t):pump("return",t)}),e}',{globals:["Promise","Symbol"],locals:{_asyncGeneratorDelegate:["body.0.id"]},exportBindingAssignments:[],exportName:"_asyncGeneratorDelegate",dependencies:{OverloadYield:["body.0.body.body.1.body.body.0.argument.expressions.2.properties.1.value.callee"]}}),asyncIterator:s("7.15.9",'function _asyncIterator(r){var n,t,o,e=2;for("undefined"!=typeof Symbol&&(t=Symbol.asyncIterator,o=Symbol.iterator);e--;){if(t&&null!=(n=r[t]))return n.call(r);if(o&&null!=(n=r[o]))return new AsyncFromSyncIterator(n.call(r));t="@@asyncIterator",o="@@iterator"}throw new TypeError("Object is not async iterable")}function AsyncFromSyncIterator(r){function AsyncFromSyncIteratorContinuation(r){if(Object(r)!==r)return Promise.reject(new TypeError(r+" is not an object."));var n=r.done;return Promise.resolve(r.value).then((function(r){return{value:r,done:n}}))}return AsyncFromSyncIterator=function(r){this.s=r,this.n=r.next},AsyncFromSyncIterator.prototype={s:null,n:null,next:function(){return AsyncFromSyncIteratorContinuation(this.n.apply(this.s,arguments))},return:function(r){var n=this.s.return;return void 0===n?Promise.resolve({value:r,done:!0}):AsyncFromSyncIteratorContinuation(n.apply(this.s,arguments))},throw:function(r){var n=this.s.return;return void 0===n?Promise.reject(r):AsyncFromSyncIteratorContinuation(n.apply(this.s,arguments))}},new AsyncFromSyncIterator(r)}',{globals:["Symbol","TypeError","Object","Promise"],locals:{_asyncIterator:["body.0.id"],AsyncFromSyncIterator:["body.1.id","body.0.body.body.1.body.body.1.consequent.argument.callee","body.1.body.body.1.argument.expressions.1.left.object","body.1.body.body.1.argument.expressions.2.callee","body.1.body.body.1.argument.expressions.0.left"]},exportBindingAssignments:[],exportName:"_asyncIterator",dependencies:{}}),asyncToGenerator:s("7.0.0-beta.0",'function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise((function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)}))}}',{globals:["Promise"],locals:{asyncGeneratorStep:["body.0.id","body.1.body.body.0.argument.body.body.1.argument.arguments.0.body.body.1.body.body.0.expression.callee","body.1.body.body.0.argument.body.body.1.argument.arguments.0.body.body.2.body.body.0.expression.callee"],_asyncToGenerator:["body.1.id"]},exportBindingAssignments:[],exportName:"_asyncToGenerator",dependencies:{}}),awaitAsyncGenerator:s("7.0.0-beta.0","function _awaitAsyncGenerator(e){return new OverloadYield(e,0)}",{globals:[],locals:{_awaitAsyncGenerator:["body.0.id"]},exportBindingAssignments:[],exportName:"_awaitAsyncGenerator",dependencies:{OverloadYield:["body.0.body.body.0.argument.callee"]}}),callSuper:s("7.23.8","function _callSuper(t,o,e){return o=getPrototypeOf(o),possibleConstructorReturn(t,isNativeReflectConstruct()?Reflect.construct(o,e||[],getPrototypeOf(t).constructor):o.apply(t,e))}",{globals:["Reflect"],locals:{_callSuper:["body.0.id"]},exportBindingAssignments:[],exportName:"_callSuper",dependencies:{getPrototypeOf:["body.0.body.body.0.argument.expressions.0.right.callee","body.0.body.body.0.argument.expressions.1.arguments.1.consequent.arguments.2.object.callee"],isNativeReflectConstruct:["body.0.body.body.0.argument.expressions.1.arguments.1.test.callee"],possibleConstructorReturn:["body.0.body.body.0.argument.expressions.1.callee"]}}),checkInRHS:s("7.20.5",'function _checkInRHS(e){if(Object(e)!==e)throw TypeError("right-hand side of \'in\' should be an object, got "+(null!==e?typeof e:"null"));return e}',{globals:["Object","TypeError"],locals:{_checkInRHS:["body.0.id"]},exportBindingAssignments:[],exportName:"_checkInRHS",dependencies:{}}),checkPrivateRedeclaration:s("7.14.1",'function _checkPrivateRedeclaration(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}',{globals:["TypeError"],locals:{_checkPrivateRedeclaration:["body.0.id"]},exportBindingAssignments:[],exportName:"_checkPrivateRedeclaration",dependencies:{}}),classCallCheck:s("7.0.0-beta.0",'function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}',{globals:["TypeError"],locals:{_classCallCheck:["body.0.id"]},exportBindingAssignments:[],exportName:"_classCallCheck",dependencies:{}}),classNameTDZError:s("7.0.0-beta.0","function _classNameTDZError(e){throw new ReferenceError('Class \"'+e+'\" cannot be referenced in computed property keys.')}",{globals:["ReferenceError"],locals:{_classNameTDZError:["body.0.id"]},exportBindingAssignments:[],exportName:"_classNameTDZError",dependencies:{}}),classPrivateFieldGet2:s("7.24.0","function _classPrivateFieldGet2(s,a){return s.get(assertClassBrand(s,a))}",{globals:[],locals:{_classPrivateFieldGet2:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldGet2",dependencies:{assertClassBrand:["body.0.body.body.0.argument.arguments.0.callee"]}}),classPrivateFieldInitSpec:s("7.14.1","function _classPrivateFieldInitSpec(e,t,a){checkPrivateRedeclaration(e,t),t.set(e,a)}",{globals:[],locals:{_classPrivateFieldInitSpec:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldInitSpec",dependencies:{checkPrivateRedeclaration:["body.0.body.body.0.expression.expressions.0.callee"]}}),classPrivateFieldLooseBase:s("7.0.0-beta.0",'function _classPrivateFieldBase(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}',{globals:["TypeError"],locals:{_classPrivateFieldBase:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldBase",dependencies:{}}),classPrivateFieldLooseKey:s("7.0.0-beta.0",'var id=0;function _classPrivateFieldKey(e){return"__private_"+id+++"_"+e}',{globals:[],locals:{id:["body.0.declarations.0.id","body.1.body.body.0.argument.left.left.right.argument","body.1.body.body.0.argument.left.left.right.argument"],_classPrivateFieldKey:["body.1.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldKey",dependencies:{}}),classPrivateFieldSet2:s("7.24.0","function _classPrivateFieldSet2(s,a,r){return s.set(assertClassBrand(s,a),r),r}",{globals:[],locals:{_classPrivateFieldSet2:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldSet2",dependencies:{assertClassBrand:["body.0.body.body.0.argument.expressions.0.arguments.0.callee"]}}),classPrivateGetter:s("7.24.0","function _classPrivateGetter(s,r,a){return a(assertClassBrand(s,r))}",{globals:[],locals:{_classPrivateGetter:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateGetter",dependencies:{assertClassBrand:["body.0.body.body.0.argument.arguments.0.callee"]}}),classPrivateMethodInitSpec:s("7.14.1","function _classPrivateMethodInitSpec(e,a){checkPrivateRedeclaration(e,a),a.add(e)}",{globals:[],locals:{_classPrivateMethodInitSpec:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateMethodInitSpec",dependencies:{checkPrivateRedeclaration:["body.0.body.body.0.expression.expressions.0.callee"]}}),classPrivateSetter:s("7.24.0","function _classPrivateSetter(s,r,a,t){return r(assertClassBrand(s,a),t),t}",{globals:[],locals:{_classPrivateSetter:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateSetter",dependencies:{assertClassBrand:["body.0.body.body.0.argument.expressions.0.arguments.0.callee"]}}),classStaticPrivateMethodGet:s("7.3.2","function _classStaticPrivateMethodGet(s,a,t){return assertClassBrand(a,s),t}",{globals:[],locals:{_classStaticPrivateMethodGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateMethodGet",dependencies:{assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"]}}),construct:s("7.0.0-beta.0","function _construct(t,e,r){if(isNativeReflectConstruct())return Reflect.construct.apply(null,arguments);var o=[null];o.push.apply(o,e);var p=new(t.bind.apply(t,o));return r&&setPrototypeOf(p,r.prototype),p}",{globals:["Reflect"],locals:{_construct:["body.0.id"]},exportBindingAssignments:[],exportName:"_construct",dependencies:{isNativeReflectConstruct:["body.0.body.body.0.test.callee"],setPrototypeOf:["body.0.body.body.4.argument.expressions.0.right.callee"]}}),createClass:s("7.0.0-beta.0",'function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}',{globals:["Object"],locals:{_defineProperties:["body.0.id","body.1.body.body.0.argument.expressions.0.right.callee","body.1.body.body.0.argument.expressions.1.right.callee"],_createClass:["body.1.id"]},exportBindingAssignments:[],exportName:"_createClass",dependencies:{toPropertyKey:["body.0.body.body.0.body.body.1.expression.expressions.3.arguments.1.callee"]}}),createForOfIteratorHelper:s("7.9.0",'function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var n=0,F=function(){};return{s:F,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function(){t=t.call(r)},n:function(){var r=t.next();return a=r.done,r},e:function(r){u=!0,o=r},f:function(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}',{globals:["Symbol","Array","TypeError"],locals:{_createForOfIteratorHelper:["body.0.id"]},exportBindingAssignments:[],exportName:"_createForOfIteratorHelper",dependencies:{unsupportedIterableToArray:["body.0.body.body.1.consequent.body.0.test.left.right.right.callee"]}}),createForOfIteratorHelperLoose:s("7.9.0",'function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}',{globals:["Symbol","Array","TypeError"],locals:{_createForOfIteratorHelperLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_createForOfIteratorHelperLoose",dependencies:{unsupportedIterableToArray:["body.0.body.body.2.test.left.right.right.callee"]}}),createSuper:s("7.9.0","function _createSuper(t){var r=isNativeReflectConstruct();return function(){var e,o=getPrototypeOf(t);if(r){var s=getPrototypeOf(this).constructor;e=Reflect.construct(o,arguments,s)}else e=o.apply(this,arguments);return possibleConstructorReturn(this,e)}}",{globals:["Reflect"],locals:{_createSuper:["body.0.id"]},exportBindingAssignments:[],exportName:"_createSuper",dependencies:{getPrototypeOf:["body.0.body.body.1.argument.body.body.0.declarations.1.init.callee","body.0.body.body.1.argument.body.body.1.consequent.body.0.declarations.0.init.object.callee"],isNativeReflectConstruct:["body.0.body.body.0.declarations.0.init.callee"],possibleConstructorReturn:["body.0.body.body.1.argument.body.body.2.argument.callee"]}}),decorate:s("7.1.5",'function _decorate(e,r,t,i){var o=_getDecoratorsApi();if(i)for(var n=0;n<i.length;n++)o=i[n](o);var s=r((function(e){o.initializeInstanceElements(e,a.elements)}),t),a=o.decorateClass(_coalesceClassElements(s.d.map(_createElementDescriptor)),e);return o.initializeClassElements(s.F,a.elements),o.runClassFinishers(s.F,a.finishers)}function _getDecoratorsApi(){_getDecoratorsApi=function(){return e};var e={elementsDefinitionOrder:[["method"],["field"]],initializeInstanceElements:function(e,r){["method","field"].forEach((function(t){r.forEach((function(r){r.kind===t&&"own"===r.placement&&this.defineClassElement(e,r)}),this)}),this)},initializeClassElements:function(e,r){var t=e.prototype;["method","field"].forEach((function(i){r.forEach((function(r){var o=r.placement;if(r.kind===i&&("static"===o||"prototype"===o)){var n="static"===o?e:t;this.defineClassElement(n,r)}}),this)}),this)},defineClassElement:function(e,r){var t=r.descriptor;if("field"===r.kind){var i=r.initializer;t={enumerable:t.enumerable,writable:t.writable,configurable:t.configurable,value:void 0===i?void 0:i.call(e)}}Object.defineProperty(e,r.key,t)},decorateClass:function(e,r){var t=[],i=[],o={static:[],prototype:[],own:[]};if(e.forEach((function(e){this.addElementPlacement(e,o)}),this),e.forEach((function(e){if(!_hasDecorators(e))return t.push(e);var r=this.decorateElement(e,o);t.push(r.element),t.push.apply(t,r.extras),i.push.apply(i,r.finishers)}),this),!r)return{elements:t,finishers:i};var n=this.decorateConstructor(t,r);return i.push.apply(i,n.finishers),n.finishers=i,n},addElementPlacement:function(e,r,t){var i=r[e.placement];if(!t&&-1!==i.indexOf(e.key))throw new TypeError("Duplicated element ("+e.key+")");i.push(e.key)},decorateElement:function(e,r){for(var t=[],i=[],o=e.decorators,n=o.length-1;n>=0;n--){var s=r[e.placement];s.splice(s.indexOf(e.key),1);var a=this.fromElementDescriptor(e),l=this.toElementFinisherExtras((0,o[n])(a)||a);e=l.element,this.addElementPlacement(e,r),l.finisher&&i.push(l.finisher);var c=l.extras;if(c){for(var p=0;p<c.length;p++)this.addElementPlacement(c[p],r);t.push.apply(t,c)}}return{element:e,finishers:i,extras:t}},decorateConstructor:function(e,r){for(var t=[],i=r.length-1;i>=0;i--){var o=this.fromClassDescriptor(e),n=this.toClassDescriptor((0,r[i])(o)||o);if(void 0!==n.finisher&&t.push(n.finisher),void 0!==n.elements){e=n.elements;for(var s=0;s<e.length-1;s++)for(var a=s+1;a<e.length;a++)if(e[s].key===e[a].key&&e[s].placement===e[a].placement)throw new TypeError("Duplicated element ("+e[s].key+")")}}return{elements:e,finishers:t}},fromElementDescriptor:function(e){var r={kind:e.kind,key:e.key,placement:e.placement,descriptor:e.descriptor};return Object.defineProperty(r,Symbol.toStringTag,{value:"Descriptor",configurable:!0}),"field"===e.kind&&(r.initializer=e.initializer),r},toElementDescriptors:function(e){if(void 0!==e)return toArray(e).map((function(e){var r=this.toElementDescriptor(e);return this.disallowProperty(e,"finisher","An element descriptor"),this.disallowProperty(e,"extras","An element descriptor"),r}),this)},toElementDescriptor:function(e){var r=e.kind+"";if("method"!==r&&"field"!==r)throw new TypeError(\'An element descriptor\\\'s .kind property must be either "method" or "field", but a decorator created an element descriptor with .kind "\'+r+\'"\');var t=toPropertyKey(e.key),i=e.placement+"";if("static"!==i&&"prototype"!==i&&"own"!==i)throw new TypeError(\'An element descriptor\\\'s .placement property must be one of "static", "prototype" or "own", but a decorator created an element descriptor with .placement "\'+i+\'"\');var o=e.descriptor;this.disallowProperty(e,"elements","An element descriptor");var n={kind:r,key:t,placement:i,descriptor:Object.assign({},o)};return"field"!==r?this.disallowProperty(e,"initializer","A method descriptor"):(this.disallowProperty(o,"get","The property descriptor of a field descriptor"),this.disallowProperty(o,"set","The property descriptor of a field descriptor"),this.disallowProperty(o,"value","The property descriptor of a field descriptor"),n.initializer=e.initializer),n},toElementFinisherExtras:function(e){return{element:this.toElementDescriptor(e),finisher:_optionalCallableProperty(e,"finisher"),extras:this.toElementDescriptors(e.extras)}},fromClassDescriptor:function(e){var r={kind:"class",elements:e.map(this.fromElementDescriptor,this)};return Object.defineProperty(r,Symbol.toStringTag,{value:"Descriptor",configurable:!0}),r},toClassDescriptor:function(e){var r=e.kind+"";if("class"!==r)throw new TypeError(\'A class descriptor\\\'s .kind property must be "class", but a decorator created a class descriptor with .kind "\'+r+\'"\');this.disallowProperty(e,"key","A class descriptor"),this.disallowProperty(e,"placement","A class descriptor"),this.disallowProperty(e,"descriptor","A class descriptor"),this.disallowProperty(e,"initializer","A class descriptor"),this.disallowProperty(e,"extras","A class descriptor");var t=_optionalCallableProperty(e,"finisher");return{elements:this.toElementDescriptors(e.elements),finisher:t}},runClassFinishers:function(e,r){for(var t=0;t<r.length;t++){var i=(0,r[t])(e);if(void 0!==i){if("function"!=typeof i)throw new TypeError("Finishers must return a constructor.");e=i}}return e},disallowProperty:function(e,r,t){if(void 0!==e[r])throw new TypeError(t+" can\'t have a ."+r+" property.")}};return e}function _createElementDescriptor(e){var r,t=toPropertyKey(e.key);"method"===e.kind?r={value:e.value,writable:!0,configurable:!0,enumerable:!1}:"get"===e.kind?r={get:e.value,configurable:!0,enumerable:!1}:"set"===e.kind?r={set:e.value,configurable:!0,enumerable:!1}:"field"===e.kind&&(r={configurable:!0,writable:!0,enumerable:!0});var i={kind:"field"===e.kind?"field":"method",key:t,placement:e.static?"static":"field"===e.kind?"own":"prototype",descriptor:r};return e.decorators&&(i.decorators=e.decorators),"field"===e.kind&&(i.initializer=e.value),i}function _coalesceGetterSetter(e,r){void 0!==e.descriptor.get?r.descriptor.get=e.descriptor.get:r.descriptor.set=e.descriptor.set}function _coalesceClassElements(e){for(var r=[],isSameElement=function(e){return"method"===e.kind&&e.key===o.key&&e.placement===o.placement},t=0;t<e.length;t++){var i,o=e[t];if("method"===o.kind&&(i=r.find(isSameElement)))if(_isDataDescriptor(o.descriptor)||_isDataDescriptor(i.descriptor)){if(_hasDecorators(o)||_hasDecorators(i))throw new ReferenceError("Duplicated methods ("+o.key+") can\'t be decorated.");i.descriptor=o.descriptor}else{if(_hasDecorators(o)){if(_hasDecorators(i))throw new ReferenceError("Decorators can\'t be placed on different accessors with for the same property ("+o.key+").");i.decorators=o.decorators}_coalesceGetterSetter(o,i)}else r.push(o)}return r}function _hasDecorators(e){return e.decorators&&e.decorators.length}function _isDataDescriptor(e){return void 0!==e&&!(void 0===e.value&&void 0===e.writable)}function _optionalCallableProperty(e,r){var t=e[r];if(void 0!==t&&"function"!=typeof t)throw new TypeError("Expected \'"+r+"\' to be a function");return t}',{globals:["Object","TypeError","Symbol","ReferenceError"],locals:{_decorate:["body.0.id"],_getDecoratorsApi:["body.1.id","body.0.body.body.0.declarations.0.init.callee","body.1.body.body.0.expression.left"],_createElementDescriptor:["body.2.id","body.0.body.body.2.declarations.1.init.arguments.0.arguments.0.arguments.0"],_coalesceGetterSetter:["body.3.id","body.4.body.body.0.body.body.1.consequent.alternate.body.1.expression.callee"],_coalesceClassElements:["body.4.id","body.0.body.body.2.declarations.1.init.arguments.0.callee"],_hasDecorators:["body.5.id","body.1.body.body.1.declarations.0.init.properties.4.value.body.body.1.test.expressions.1.arguments.0.body.body.0.test.argument.callee","body.4.body.body.0.body.body.1.consequent.consequent.body.0.test.left.callee","body.4.body.body.0.body.body.1.consequent.consequent.body.0.test.right.callee","body.4.body.body.0.body.body.1.consequent.alternate.body.0.test.callee","body.4.body.body.0.body.body.1.consequent.alternate.body.0.consequent.body.0.test.callee"],_isDataDescriptor:["body.6.id","body.4.body.body.0.body.body.1.consequent.test.left.callee","body.4.body.body.0.body.body.1.consequent.test.right.callee"],_optionalCallableProperty:["body.7.id","body.1.body.body.1.declarations.0.init.properties.11.value.body.body.0.argument.properties.1.value.callee","body.1.body.body.1.declarations.0.init.properties.13.value.body.body.3.declarations.0.init.callee"]},exportBindingAssignments:[],exportName:"_decorate",dependencies:{toArray:["body.1.body.body.1.declarations.0.init.properties.9.value.body.body.0.consequent.argument.callee.object.callee"],toPropertyKey:["body.1.body.body.1.declarations.0.init.properties.10.value.body.body.2.declarations.0.init.callee","body.2.body.body.0.declarations.1.init.callee"]}}),defaults:s("7.0.0-beta.0","function _defaults(e,r){for(var t=Object.getOwnPropertyNames(r),o=0;o<t.length;o++){var n=t[o],a=Object.getOwnPropertyDescriptor(r,n);a&&a.configurable&&void 0===e[n]&&Object.defineProperty(e,n,a)}return e}",{globals:["Object"],locals:{_defaults:["body.0.id"]},exportBindingAssignments:[],exportName:"_defaults",dependencies:{}}),defineAccessor:s("7.20.7","function _defineAccessor(e,r,n,t){var c={configurable:!0,enumerable:!0};return c[e]=t,Object.defineProperty(r,n,c)}",{globals:["Object"],locals:{_defineAccessor:["body.0.id"]},exportBindingAssignments:[],exportName:"_defineAccessor",dependencies:{}}),defineProperty:s("7.0.0-beta.0","function _defineProperty(e,r,t){return(r=toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}",{globals:["Object"],locals:{_defineProperty:["body.0.id"]},exportBindingAssignments:[],exportName:"_defineProperty",dependencies:{toPropertyKey:["body.0.body.body.0.argument.expressions.0.test.left.right.callee"]}}),extends:s("7.0.0-beta.0","function _extends(){return _extends=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(n[r]=t[r])}return n},_extends.apply(null,arguments)}",{globals:["Object"],locals:{_extends:["body.0.id","body.0.body.body.0.argument.expressions.1.callee.object","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_extends",dependencies:{}}),get:s("7.0.0-beta.0",'function _get(){return _get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var p=superPropBase(e,t);if(p){var n=Object.getOwnPropertyDescriptor(p,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},_get.apply(null,arguments)}',{globals:["Reflect","Object"],locals:{_get:["body.0.id","body.0.body.body.0.argument.expressions.1.callee.object","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_get",dependencies:{superPropBase:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.0.declarations.0.init.callee"]}}),getPrototypeOf:s("7.0.0-beta.0","function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}",{globals:["Object"],locals:{_getPrototypeOf:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_getPrototypeOf",dependencies:{}}),identity:s("7.17.0","function _identity(t){return t}",{globals:[],locals:{_identity:["body.0.id"]},exportBindingAssignments:[],exportName:"_identity",dependencies:{}}),importDeferProxy:s("7.23.0","function _importDeferProxy(e){var t=null,constValue=function(e){return function(){return e}},proxy=function(r){return function(n,o,f){return null===t&&(t=e()),r(t,o,f)}};return new Proxy({},{defineProperty:constValue(!1),deleteProperty:constValue(!1),get:proxy(Reflect.get),getOwnPropertyDescriptor:proxy(Reflect.getOwnPropertyDescriptor),getPrototypeOf:constValue(null),isExtensible:constValue(!1),has:proxy(Reflect.has),ownKeys:proxy(Reflect.ownKeys),preventExtensions:constValue(!0),set:constValue(!1),setPrototypeOf:constValue(!1)})}",{globals:["Proxy","Reflect"],locals:{_importDeferProxy:["body.0.id"]},exportBindingAssignments:[],exportName:"_importDeferProxy",dependencies:{}}),inherits:s("7.0.0-beta.0",'function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&setPrototypeOf(t,e)}',{globals:["TypeError","Object"],locals:{_inherits:["body.0.id"]},exportBindingAssignments:[],exportName:"_inherits",dependencies:{setPrototypeOf:["body.0.body.body.1.expression.expressions.2.right.callee"]}}),inheritsLoose:s("7.0.0-beta.0","function _inheritsLoose(t,o){t.prototype=Object.create(o.prototype),t.prototype.constructor=t,setPrototypeOf(t,o)}",{globals:["Object"],locals:{_inheritsLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_inheritsLoose",dependencies:{setPrototypeOf:["body.0.body.body.0.expression.expressions.2.callee"]}}),initializerDefineProperty:s("7.0.0-beta.0","function _initializerDefineProperty(e,i,r,l){r&&Object.defineProperty(e,i,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(l):void 0})}",{globals:["Object"],locals:{_initializerDefineProperty:["body.0.id"]},exportBindingAssignments:[],exportName:"_initializerDefineProperty",dependencies:{}}),initializerWarningHelper:s("7.0.0-beta.0",'function _initializerWarningHelper(r,e){throw Error("Decorating class property failed. Please ensure that transform-class-properties is enabled and runs after the decorators transform.")}',{globals:["Error"],locals:{_initializerWarningHelper:["body.0.id"]},exportBindingAssignments:[],exportName:"_initializerWarningHelper",dependencies:{}}),instanceof:s("7.0.0-beta.0",'function _instanceof(n,e){return null!=e&&"undefined"!=typeof Symbol&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](n):n instanceof e}',{globals:["Symbol"],locals:{_instanceof:["body.0.id"]},exportBindingAssignments:[],exportName:"_instanceof",dependencies:{}}),interopRequireDefault:s("7.0.0-beta.0","function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}",{globals:[],locals:{_interopRequireDefault:["body.0.id"]},exportBindingAssignments:[],exportName:"_interopRequireDefault",dependencies:{}}),interopRequireWildcard:s("7.14.0",'function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}',{globals:["WeakMap","Object"],locals:{_getRequireWildcardCache:["body.0.id","body.1.body.body.2.declarations.0.init.callee","body.0.body.body.2.argument.callee.left"],_interopRequireWildcard:["body.1.id"]},exportBindingAssignments:[],exportName:"_interopRequireWildcard",dependencies:{}}),isNativeFunction:s("7.0.0-beta.0",'function _isNativeFunction(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(n){return"function"==typeof t}}',{globals:["Function"],locals:{_isNativeFunction:["body.0.id"]},exportBindingAssignments:[],exportName:"_isNativeFunction",dependencies:{}}),isNativeReflectConstruct:s("7.9.0","function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(_isNativeReflectConstruct=function(){return!!t})()}",{globals:["Boolean","Reflect"],locals:{_isNativeReflectConstruct:["body.0.id","body.0.body.body.1.argument.callee.left"]},exportBindingAssignments:["body.0.body.body.1.argument.callee"],exportName:"_isNativeReflectConstruct",dependencies:{}}),iterableToArray:s("7.0.0-beta.0",'function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}',{globals:["Symbol","Array"],locals:{_iterableToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_iterableToArray",dependencies:{}}),iterableToArrayLimit:s("7.0.0-beta.0",'function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}',{globals:["Symbol","Object"],locals:{_iterableToArrayLimit:["body.0.id"]},exportBindingAssignments:[],exportName:"_iterableToArrayLimit",dependencies:{}}),jsx:s("7.0.0-beta.0",'var REACT_ELEMENT_TYPE;function _createRawReactElement(e,r,E,l){REACT_ELEMENT_TYPE||(REACT_ELEMENT_TYPE="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103);var o=e&&e.defaultProps,n=arguments.length-3;if(r||0===n||(r={children:void 0}),1===n)r.children=l;else if(n>1){for(var t=Array(n),f=0;f<n;f++)t[f]=arguments[f+3];r.children=t}if(r&&o)for(var i in o)void 0===r[i]&&(r[i]=o[i]);else r||(r=o||{});return{$$typeof:REACT_ELEMENT_TYPE,type:e,key:void 0===E?null:""+E,ref:null,props:r,_owner:null}}',{globals:["Symbol","Array"],locals:{REACT_ELEMENT_TYPE:["body.0.declarations.0.id","body.1.body.body.0.expression.left","body.1.body.body.4.argument.properties.0.value","body.1.body.body.0.expression.right.left"],_createRawReactElement:["body.1.id"]},exportBindingAssignments:[],exportName:"_createRawReactElement",dependencies:{}}),maybeArrayLike:s("7.9.0",'function _maybeArrayLike(r,a,e){if(a&&!Array.isArray(a)&&"number"==typeof a.length){var y=a.length;return arrayLikeToArray(a,void 0!==e&&e<y?e:y)}return r(a,e)}',{globals:["Array"],locals:{_maybeArrayLike:["body.0.id"]},exportBindingAssignments:[],exportName:"_maybeArrayLike",dependencies:{arrayLikeToArray:["body.0.body.body.0.consequent.body.1.argument.callee"]}}),newArrowCheck:s("7.0.0-beta.0",'function _newArrowCheck(n,r){if(n!==r)throw new TypeError("Cannot instantiate an arrow function")}',{globals:["TypeError"],locals:{_newArrowCheck:["body.0.id"]},exportBindingAssignments:[],exportName:"_newArrowCheck",dependencies:{}}),nonIterableRest:s("7.0.0-beta.0",'function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}',{globals:["TypeError"],locals:{_nonIterableRest:["body.0.id"]},exportBindingAssignments:[],exportName:"_nonIterableRest",dependencies:{}}),nonIterableSpread:s("7.0.0-beta.0",'function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}',{globals:["TypeError"],locals:{_nonIterableSpread:["body.0.id"]},exportBindingAssignments:[],exportName:"_nonIterableSpread",dependencies:{}}),nullishReceiverError:s("7.22.6",'function _nullishReceiverError(r){throw new TypeError("Cannot set property of null or undefined.")}',{globals:["TypeError"],locals:{_nullishReceiverError:["body.0.id"]},exportBindingAssignments:[],exportName:"_nullishReceiverError",dependencies:{}}),objectDestructuringEmpty:s("7.0.0-beta.0",'function _objectDestructuringEmpty(t){if(null==t)throw new TypeError("Cannot destructure "+t)}',{globals:["TypeError"],locals:{_objectDestructuringEmpty:["body.0.id"]},exportBindingAssignments:[],exportName:"_objectDestructuringEmpty",dependencies:{}}),objectSpread2:s("7.5.0","function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function _objectSpread2(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach((function(r){defineProperty(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}",{globals:["Object"],locals:{ownKeys:["body.0.id","body.1.body.body.0.body.body.1.expression.consequent.callee.object.callee","body.1.body.body.0.body.body.1.expression.alternate.alternate.callee.object.callee"],_objectSpread2:["body.1.id"]},exportBindingAssignments:[],exportName:"_objectSpread2",dependencies:{defineProperty:["body.1.body.body.0.body.body.1.expression.consequent.arguments.0.body.body.0.expression.callee"]}}),objectWithoutProperties:s("7.0.0-beta.0","function _objectWithoutProperties(e,t){if(null==e)return{};var o,r,i=objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(r=0;r<n.length;r++)o=n[r],-1===t.indexOf(o)&&{}.propertyIsEnumerable.call(e,o)&&(i[o]=e[o])}return i}",{globals:["Object"],locals:{_objectWithoutProperties:["body.0.id"]},exportBindingAssignments:[],exportName:"_objectWithoutProperties",dependencies:{objectWithoutPropertiesLoose:["body.0.body.body.1.declarations.2.init.callee"]}}),objectWithoutPropertiesLoose:s("7.0.0-beta.0","function _objectWithoutPropertiesLoose(r,e){if(null==r)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(-1!==e.indexOf(n))continue;t[n]=r[n]}return t}",{globals:[],locals:{_objectWithoutPropertiesLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_objectWithoutPropertiesLoose",dependencies:{}}),possibleConstructorReturn:s("7.0.0-beta.0",'function _possibleConstructorReturn(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return assertThisInitialized(t)}',{globals:["TypeError"],locals:{_possibleConstructorReturn:["body.0.id"]},exportBindingAssignments:[],exportName:"_possibleConstructorReturn",dependencies:{assertThisInitialized:["body.0.body.body.2.argument.callee"]}}),readOnlyError:s("7.0.0-beta.0","function _readOnlyError(r){throw new TypeError('\"'+r+'\" is read-only')}",{globals:["TypeError"],locals:{_readOnlyError:["body.0.id"]},exportBindingAssignments:[],exportName:"_readOnlyError",dependencies:{}}),regeneratorRuntime:s("7.18.0",'function _regeneratorRuntime(){"use strict";\n/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function define(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{define({},"")}catch(t){define=function(t,e,r){return t[e]=r}}function wrap(t,e,r,n){var i=e&&e.prototype instanceof Generator?e:Generator,a=Object.create(i.prototype),c=new Context(n||[]);return o(a,"_invoke",{value:makeInvokeMethod(t,r,c)}),a}function tryCatch(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=wrap;var h="suspendedStart",l="suspendedYield",f="executing",s="completed",y={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var p={};define(p,a,(function(){return this}));var d=Object.getPrototypeOf,v=d&&d(d(values([])));v&&v!==r&&n.call(v,a)&&(p=v);var g=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(p);function defineIteratorMethods(t){["next","throw","return"].forEach((function(e){define(t,e,(function(t){return this._invoke(e,t)}))}))}function AsyncIterator(t,e){function invoke(r,o,i,a){var c=tryCatch(t[r],t,o);if("throw"!==c.type){var u=c.arg,h=u.value;return h&&"object"==typeof h&&n.call(h,"__await")?e.resolve(h.__await).then((function(t){invoke("next",t,i,a)}),(function(t){invoke("throw",t,i,a)})):e.resolve(h).then((function(t){u.value=t,i(u)}),(function(t){return invoke("throw",t,i,a)}))}a(c.arg)}var r;o(this,"_invoke",{value:function(t,n){function callInvokeWithMethodAndArg(){return new e((function(e,r){invoke(t,n,e,r)}))}return r=r?r.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}})}function makeInvokeMethod(e,r,n){var o=h;return function(i,a){if(o===f)throw Error("Generator is already running");if(o===s){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=maybeInvokeDelegate(c,n);if(u){if(u===y)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=s,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=f;var p=tryCatch(e,r,n);if("normal"===p.type){if(o=n.done?s:l,p.arg===y)continue;return{value:p.arg,done:n.done}}"throw"===p.type&&(o=s,n.method="throw",n.arg=p.arg)}}}function maybeInvokeDelegate(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,maybeInvokeDelegate(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a \'"+n+"\' method")),y;var i=tryCatch(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,y;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,y):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function pushTryEntry(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function resetTryEntry(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function Context(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(pushTryEntry,this),this.reset(!0)}function values(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function next(){for(;++o<e.length;)if(n.call(e,o))return next.value=e[o],next.done=!1,next;return next.value=t,next.done=!0,next};return i.next=i}}throw new TypeError(typeof e+" is not iterable")}return GeneratorFunction.prototype=GeneratorFunctionPrototype,o(g,"constructor",{value:GeneratorFunctionPrototype,configurable:!0}),o(GeneratorFunctionPrototype,"constructor",{value:GeneratorFunction,configurable:!0}),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===GeneratorFunction||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,GeneratorFunctionPrototype):(t.__proto__=GeneratorFunctionPrototype,define(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},e.awrap=function(t){return{__await:t}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,c,(function(){return this})),e.AsyncIterator=AsyncIterator,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new AsyncIterator(wrap(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},defineIteratorMethods(g),define(g,u,"Generator"),define(g,a,(function(){return this})),define(g,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function next(){for(;r.length;){var t=r.pop();if(t in e)return next.value=t,next.done=!1,next}return next.done=!0,next}},e.values=values,Context.prototype={constructor:Context,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(resetTryEntry),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function handle(n,o){return a.type="throw",a.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return handle("end");if(i.tryLoc<=this.prev){var c=n.call(i,"catchLoc"),u=n.call(i,"finallyLoc");if(c&&u){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0);if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,y):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),y},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),resetTryEntry(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;resetTryEntry(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:values(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},e}',{globals:["Object","Symbol","Error","TypeError","isNaN","Promise"],locals:{_regeneratorRuntime:["body.0.id","body.0.body.body.0.expression.left"]},exportBindingAssignments:["body.0.body.body.0.expression"],exportName:"_regeneratorRuntime",dependencies:{}}),set:s("7.0.0-beta.0",'function set(e,r,t,o){return set="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(e,r,t,o){var f,i=superPropBase(e,r);if(i){if((f=Object.getOwnPropertyDescriptor(i,r)).set)return f.set.call(o,t),!0;if(!f.writable)return!1}if(f=Object.getOwnPropertyDescriptor(o,r)){if(!f.writable)return!1;f.value=t,Object.defineProperty(o,r,f)}else defineProperty(o,r,t);return!0},set(e,r,t,o)}function _set(e,r,t,o,f){if(!set(e,r,t,o||e)&&f)throw new TypeError("failed to set property");return t}',{globals:["Reflect","Object","TypeError"],locals:{set:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.1.body.body.0.test.left.argument.callee","body.0.body.body.0.argument.expressions.0.left"],_set:["body.1.id"]},exportBindingAssignments:[],exportName:"_set",dependencies:{superPropBase:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.0.declarations.1.init.callee"],defineProperty:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.2.alternate.expression.callee"]}}),setFunctionName:s("7.23.6",'function setFunctionName(e,t,n){"symbol"==typeof t&&(t=(t=t.description)?"["+t+"]":"");try{Object.defineProperty(e,"name",{configurable:!0,value:n?n+" "+t:t})}catch(e){}return e}',{globals:["Object"],locals:{setFunctionName:["body.0.id"]},exportBindingAssignments:[],exportName:"setFunctionName",dependencies:{}}),setPrototypeOf:s("7.0.0-beta.0","function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}",{globals:["Object"],locals:{_setPrototypeOf:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_setPrototypeOf",dependencies:{}}),skipFirstGeneratorNext:s("7.0.0-beta.0","function _skipFirstGeneratorNext(t){return function(){var r=t.apply(this,arguments);return r.next(),r}}",{globals:[],locals:{_skipFirstGeneratorNext:["body.0.id"]},exportBindingAssignments:[],exportName:"_skipFirstGeneratorNext",dependencies:{}}),slicedToArray:s("7.0.0-beta.0","function _slicedToArray(r,e){return arrayWithHoles(r)||iterableToArrayLimit(r,e)||unsupportedIterableToArray(r,e)||nonIterableRest()}",{globals:[],locals:{_slicedToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_slicedToArray",dependencies:{arrayWithHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArrayLimit:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableRest:["body.0.body.body.0.argument.right.callee"]}}),superPropBase:s("7.0.0-beta.0","function _superPropBase(t,o){for(;!{}.hasOwnProperty.call(t,o)&&null!==(t=getPrototypeOf(t)););return t}",{globals:[],locals:{_superPropBase:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropBase",dependencies:{getPrototypeOf:["body.0.body.body.0.test.right.right.right.callee"]}}),superPropGet:s("7.25.0",'function _superPropGet(t,o,e,r){var p=get(getPrototypeOf(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t)}:p}',{globals:[],locals:{_superPropGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropGet",dependencies:{get:["body.0.body.body.0.declarations.0.init.callee"],getPrototypeOf:["body.0.body.body.0.declarations.0.init.arguments.0.callee"]}}),superPropSet:s("7.25.0","function _superPropSet(t,e,o,r,p,f){return set(getPrototypeOf(f?t.prototype:t),e,o,r,p)}",{globals:[],locals:{_superPropSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropSet",dependencies:{set:["body.0.body.body.0.argument.callee"],getPrototypeOf:["body.0.body.body.0.argument.arguments.0.callee"]}}),taggedTemplateLiteral:s("7.0.0-beta.0","function _taggedTemplateLiteral(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}",{globals:["Object"],locals:{_taggedTemplateLiteral:["body.0.id"]},exportBindingAssignments:[],exportName:"_taggedTemplateLiteral",dependencies:{}}),taggedTemplateLiteralLoose:s("7.0.0-beta.0","function _taggedTemplateLiteralLoose(e,t){return t||(t=e.slice(0)),e.raw=t,e}",{globals:[],locals:{_taggedTemplateLiteralLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_taggedTemplateLiteralLoose",dependencies:{}}),tdz:s("7.5.5",'function _tdzError(e){throw new ReferenceError(e+" is not defined - temporal dead zone")}',{globals:["ReferenceError"],locals:{_tdzError:["body.0.id"]},exportBindingAssignments:[],exportName:"_tdzError",dependencies:{}}),temporalRef:s("7.0.0-beta.0","function _temporalRef(r,e){return r===undef?err(e):r}",{globals:[],locals:{_temporalRef:["body.0.id"]},exportBindingAssignments:[],exportName:"_temporalRef",dependencies:{temporalUndefined:["body.0.body.body.0.argument.test.right"],tdz:["body.0.body.body.0.argument.consequent.callee"]}}),temporalUndefined:s("7.0.0-beta.0","function _temporalUndefined(){}",{globals:[],locals:{_temporalUndefined:["body.0.id"]},exportBindingAssignments:[],exportName:"_temporalUndefined",dependencies:{}}),toArray:s("7.0.0-beta.0","function _toArray(r){return arrayWithHoles(r)||iterableToArray(r)||unsupportedIterableToArray(r)||nonIterableRest()}",{globals:[],locals:{_toArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_toArray",dependencies:{arrayWithHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArray:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableRest:["body.0.body.body.0.argument.right.callee"]}}),toConsumableArray:s("7.0.0-beta.0","function _toConsumableArray(r){return arrayWithoutHoles(r)||iterableToArray(r)||unsupportedIterableToArray(r)||nonIterableSpread()}",{globals:[],locals:{_toConsumableArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_toConsumableArray",dependencies:{arrayWithoutHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArray:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableSpread:["body.0.body.body.0.argument.right.callee"]}}),toPrimitive:s("7.1.5",'function toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}',{globals:["Symbol","TypeError","String","Number"],locals:{toPrimitive:["body.0.id"]},exportBindingAssignments:[],exportName:"toPrimitive",dependencies:{}}),toPropertyKey:s("7.1.5",'function toPropertyKey(t){var i=toPrimitive(t,"string");return"symbol"==typeof i?i:i+""}',{globals:[],locals:{toPropertyKey:["body.0.id"]},exportBindingAssignments:[],exportName:"toPropertyKey",dependencies:{toPrimitive:["body.0.body.body.0.declarations.0.init.callee"]}}),toSetter:s("7.24.0",'function _toSetter(t,e,n){e||(e=[]);var r=e.length++;return Object.defineProperty({},"_",{set:function(o){e[r]=o,t.apply(n,e)}})}',{globals:["Object"],locals:{_toSetter:["body.0.id"]},exportBindingAssignments:[],exportName:"_toSetter",dependencies:{}}),typeof:s("7.0.0-beta.0",'function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}',{globals:["Symbol"],locals:{_typeof:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_typeof",dependencies:{}}),unsupportedIterableToArray:s("7.9.0",'function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?arrayLikeToArray(r,a):void 0}}',{globals:["Array"],locals:{_unsupportedIterableToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_unsupportedIterableToArray",dependencies:{arrayLikeToArray:["body.0.body.body.0.consequent.body.0.consequent.argument.callee","body.0.body.body.0.consequent.body.2.argument.expressions.1.alternate.consequent.callee"]}}),usingCtx:s("7.23.9",'function _usingCtx(){var r="function"==typeof SuppressedError?SuppressedError:function(r,e){var n=Error();return n.name="SuppressedError",n.error=r,n.suppressed=e,n},e={},n=[];function using(r,e){if(null!=e){if(Object(e)!==e)throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(r)var o=e[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(void 0===o&&(o=e[Symbol.dispose||Symbol.for("Symbol.dispose")],r))var t=o;if("function"!=typeof o)throw new TypeError("Object is not disposable.");t&&(o=function(){try{t.call(e)}catch(r){return Promise.reject(r)}}),n.push({v:e,d:o,a:r})}else r&&n.push({d:e,a:r});return e}return{e:e,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var o,t=this.e,s=0;function next(){for(;o=n.pop();)try{if(!o.a&&1===s)return s=0,n.push(o),Promise.resolve().then(next);if(o.d){var r=o.d.call(o.v);if(o.a)return s|=2,Promise.resolve(r).then(next,err)}else s|=1}catch(r){return err(r)}if(1===s)return t!==e?Promise.reject(t):Promise.resolve();if(t!==e)throw t}function err(n){return t=t!==e?new r(n,t):n,next()}return next()}}}',{globals:["SuppressedError","Error","Object","TypeError","Symbol","Promise"],locals:{_usingCtx:["body.0.id"]},exportBindingAssignments:[],exportName:"_usingCtx",dependencies:{}}),wrapAsyncGenerator:s("7.0.0-beta.0",'function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function AsyncGenerator(e){var r,t;function resume(r,t){try{var n=e[r](t),o=n.value,u=o instanceof OverloadYield;Promise.resolve(u?o.v:o).then((function(t){if(u){var i="return"===r?"return":"next";if(!o.k||t.done)return resume(i,t);t=e[i](t).value}settle(n.done?"return":"normal",t)}),(function(e){resume("throw",e)}))}catch(e){settle("throw",e)}}function settle(e,n){switch(e){case"return":r.resolve({value:n,done:!0});break;case"throw":r.reject(n);break;default:r.resolve({value:n,done:!1})}(r=r.next)?resume(r.key,r.arg):t=null}this._invoke=function(e,n){return new Promise((function(o,u){var i={key:e,arg:n,resolve:o,reject:u,next:null};t?t=t.next=i:(r=t=i,resume(e,n))}))},"function"!=typeof e.return&&(this.return=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype.throw=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype.return=function(e){return this._invoke("return",e)};',{globals:["Promise","Symbol"],locals:{_wrapAsyncGenerator:["body.0.id"],AsyncGenerator:["body.1.id","body.0.body.body.0.argument.body.body.0.argument.callee","body.2.expression.expressions.0.left.object.object","body.2.expression.expressions.1.left.object.object","body.2.expression.expressions.2.left.object.object","body.2.expression.expressions.3.left.object.object"]},exportBindingAssignments:[],exportName:"_wrapAsyncGenerator",dependencies:{OverloadYield:["body.1.body.body.1.body.body.0.block.body.0.declarations.2.init.right"]}}),wrapNativeSuper:s("7.0.0-beta.0",'function _wrapNativeSuper(t){var r="function"==typeof Map?new Map:void 0;return _wrapNativeSuper=function(t){if(null===t||!isNativeFunction(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,Wrapper)}function Wrapper(){return construct(t,arguments,getPrototypeOf(this).constructor)}return Wrapper.prototype=Object.create(t.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),setPrototypeOf(Wrapper,t)},_wrapNativeSuper(t)}',{globals:["Map","TypeError","Object"],locals:{_wrapNativeSuper:["body.0.id","body.0.body.body.1.argument.expressions.1.callee","body.0.body.body.1.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.1.argument.expressions.0"],exportName:"_wrapNativeSuper",dependencies:{getPrototypeOf:["body.0.body.body.1.argument.expressions.0.right.body.body.3.body.body.0.argument.arguments.2.object.callee"],setPrototypeOf:["body.0.body.body.1.argument.expressions.0.right.body.body.4.argument.expressions.1.callee"],isNativeFunction:["body.0.body.body.1.argument.expressions.0.right.body.body.0.test.right.argument.callee"],construct:["body.0.body.body.1.argument.expressions.0.right.body.body.3.body.body.0.argument.callee"]}}),wrapRegExp:s("7.19.0",'function _wrapRegExp(){_wrapRegExp=function(e,r){return new BabelRegExp(e,void 0,r)};var e=RegExp.prototype,r=new WeakMap;function BabelRegExp(e,t,p){var o=RegExp(e,t);return r.set(o,p||r.get(e)),setPrototypeOf(o,BabelRegExp.prototype)}function buildGroups(e,t){var p=r.get(t);return Object.keys(p).reduce((function(r,t){var o=p[t];if("number"==typeof o)r[t]=e[o];else{for(var i=0;void 0===e[o[i]]&&i+1<o.length;)i++;r[t]=e[o[i]]}return r}),Object.create(null))}return inherits(BabelRegExp,RegExp),BabelRegExp.prototype.exec=function(r){var t=e.exec.call(this,r);if(t){t.groups=buildGroups(t,this);var p=t.indices;p&&(p.groups=buildGroups(p,this))}return t},BabelRegExp.prototype[Symbol.replace]=function(t,p){if("string"==typeof p){var o=r.get(this);return e[Symbol.replace].call(this,t,p.replace(/\\$<([^>]+)>/g,(function(e,r){var t=o[r];return"$"+(Array.isArray(t)?t.join("$"):t)})))}if("function"==typeof p){var i=this;return e[Symbol.replace].call(this,t,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(buildGroups(e,i)),p.apply(this,e)}))}return e[Symbol.replace].call(this,t,p)},_wrapRegExp.apply(this,arguments)}',{globals:["RegExp","WeakMap","Object","Symbol","Array"],locals:{_wrapRegExp:["body.0.id","body.0.body.body.4.argument.expressions.3.callee.object","body.0.body.body.0.expression.left"]},exportBindingAssignments:["body.0.body.body.0.expression"],exportName:"_wrapRegExp",dependencies:{setPrototypeOf:["body.0.body.body.2.body.body.1.argument.expressions.1.callee"],inherits:["body.0.body.body.4.argument.expressions.0.callee"]}}),writeOnlyError:s("7.12.13","function _writeOnlyError(r){throw new TypeError('\"'+r+'\" is write-only')}",{globals:["TypeError"],locals:{_writeOnlyError:["body.0.id"]},exportBindingAssignments:[],exportName:"_writeOnlyError",dependencies:{}})};Object.assign(i,{AwaitValue:s("7.0.0-beta.0","function _AwaitValue(t){this.wrapped=t}",{globals:[],locals:{_AwaitValue:["body.0.id"]},exportBindingAssignments:[],exportName:"_AwaitValue",dependencies:{}}),applyDecs:s("7.17.8",'function old_createMetadataMethodsForProperty(e,t,a,r){return{getMetadata:function(o){old_assertNotFinished(r,"getMetadata"),old_assertMetadataKey(o);var i=e[o];if(void 0!==i)if(1===t){var n=i.public;if(void 0!==n)return n[a]}else if(2===t){var l=i.private;if(void 0!==l)return l.get(a)}else if(Object.hasOwnProperty.call(i,"constructor"))return i.constructor},setMetadata:function(o,i){old_assertNotFinished(r,"setMetadata"),old_assertMetadataKey(o);var n=e[o];if(void 0===n&&(n=e[o]={}),1===t){var l=n.public;void 0===l&&(l=n.public={}),l[a]=i}else if(2===t){var s=n.priv;void 0===s&&(s=n.private=new Map),s.set(a,i)}else n.constructor=i}}}function old_convertMetadataMapToFinal(e,t){var a=e[Symbol.metadata||Symbol.for("Symbol.metadata")],r=Object.getOwnPropertySymbols(t);if(0!==r.length){for(var o=0;o<r.length;o++){var i=r[o],n=t[i],l=a?a[i]:null,s=n.public,c=l?l.public:null;s&&c&&Object.setPrototypeOf(s,c);var d=n.private;if(d){var u=Array.from(d.values()),f=l?l.private:null;f&&(u=u.concat(f)),n.private=u}l&&Object.setPrototypeOf(n,l)}a&&Object.setPrototypeOf(t,a),e[Symbol.metadata||Symbol.for("Symbol.metadata")]=t}}function old_createAddInitializerMethod(e,t){return function(a){old_assertNotFinished(t,"addInitializer"),old_assertCallable(a,"An initializer"),e.push(a)}}function old_memberDec(e,t,a,r,o,i,n,l,s){var c;switch(i){case 1:c="accessor";break;case 2:c="method";break;case 3:c="getter";break;case 4:c="setter";break;default:c="field"}var d,u,f={kind:c,name:l?"#"+t:toPropertyKey(t),isStatic:n,isPrivate:l},p={v:!1};if(0!==i&&(f.addInitializer=old_createAddInitializerMethod(o,p)),l){d=2,u=Symbol(t);var v={};0===i?(v.get=a.get,v.set=a.set):2===i?v.get=function(){return a.value}:(1!==i&&3!==i||(v.get=function(){return a.get.call(this)}),1!==i&&4!==i||(v.set=function(e){a.set.call(this,e)})),f.access=v}else d=1,u=t;try{return e(s,Object.assign(f,old_createMetadataMethodsForProperty(r,d,u,p)))}finally{p.v=!0}}function old_assertNotFinished(e,t){if(e.v)throw Error("attempted to call "+t+" after decoration was finished")}function old_assertMetadataKey(e){if("symbol"!=typeof e)throw new TypeError("Metadata keys must be symbols, received: "+e)}function old_assertCallable(e,t){if("function"!=typeof e)throw new TypeError(t+" must be a function")}function old_assertValidReturnValue(e,t){var a=typeof t;if(1===e){if("object"!==a||null===t)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");void 0!==t.get&&old_assertCallable(t.get,"accessor.get"),void 0!==t.set&&old_assertCallable(t.set,"accessor.set"),void 0!==t.init&&old_assertCallable(t.init,"accessor.init"),void 0!==t.initializer&&old_assertCallable(t.initializer,"accessor.initializer")}else if("function"!==a)throw new TypeError((0===e?"field":10===e?"class":"method")+" decorators must return a function or void 0")}function old_getInit(e){var t;return null==(t=e.init)&&(t=e.initializer)&&void 0!==console&&console.warn(".initializer has been renamed to .init as of March 2022"),t}function old_applyMemberDec(e,t,a,r,o,i,n,l,s){var c,d,u,f,p,v,y,h=a[0];if(n?(0===o||1===o?(c={get:a[3],set:a[4]},u="get"):3===o?(c={get:a[3]},u="get"):4===o?(c={set:a[3]},u="set"):c={value:a[3]},0!==o&&(1===o&&setFunctionName(a[4],"#"+r,"set"),setFunctionName(a[3],"#"+r,u))):0!==o&&(c=Object.getOwnPropertyDescriptor(t,r)),1===o?f={get:c.get,set:c.set}:2===o?f=c.value:3===o?f=c.get:4===o&&(f=c.set),"function"==typeof h)void 0!==(p=old_memberDec(h,r,c,l,s,o,i,n,f))&&(old_assertValidReturnValue(o,p),0===o?d=p:1===o?(d=old_getInit(p),v=p.get||f.get,y=p.set||f.set,f={get:v,set:y}):f=p);else for(var m=h.length-1;m>=0;m--){var b;void 0!==(p=old_memberDec(h[m],r,c,l,s,o,i,n,f))&&(old_assertValidReturnValue(o,p),0===o?b=p:1===o?(b=old_getInit(p),v=p.get||f.get,y=p.set||f.set,f={get:v,set:y}):f=p,void 0!==b&&(void 0===d?d=b:"function"==typeof d?d=[d,b]:d.push(b)))}if(0===o||1===o){if(void 0===d)d=function(e,t){return t};else if("function"!=typeof d){var g=d;d=function(e,t){for(var a=t,r=0;r<g.length;r++)a=g[r].call(e,a);return a}}else{var _=d;d=function(e,t){return _.call(e,t)}}e.push(d)}0!==o&&(1===o?(c.get=f.get,c.set=f.set):2===o?c.value=f:3===o?c.get=f:4===o&&(c.set=f),n?1===o?(e.push((function(e,t){return f.get.call(e,t)})),e.push((function(e,t){return f.set.call(e,t)}))):2===o?e.push(f):e.push((function(e,t){return f.call(e,t)})):Object.defineProperty(t,r,c))}function old_applyMemberDecs(e,t,a,r,o){for(var i,n,l=new Map,s=new Map,c=0;c<o.length;c++){var d=o[c];if(Array.isArray(d)){var u,f,p,v=d[1],y=d[2],h=d.length>3,m=v>=5;if(m?(u=t,f=r,0!=(v-=5)&&(p=n=n||[])):(u=t.prototype,f=a,0!==v&&(p=i=i||[])),0!==v&&!h){var b=m?s:l,g=b.get(y)||0;if(!0===g||3===g&&4!==v||4===g&&3!==v)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+y);!g&&v>2?b.set(y,v):b.set(y,!0)}old_applyMemberDec(e,u,d,y,v,m,h,f,p)}}old_pushInitializers(e,i),old_pushInitializers(e,n)}function old_pushInitializers(e,t){t&&e.push((function(e){for(var a=0;a<t.length;a++)t[a].call(e);return e}))}function old_applyClassDecs(e,t,a,r){if(r.length>0){for(var o=[],i=t,n=t.name,l=r.length-1;l>=0;l--){var s={v:!1};try{var c=Object.assign({kind:"class",name:n,addInitializer:old_createAddInitializerMethod(o,s)},old_createMetadataMethodsForProperty(a,0,n,s)),d=r[l](i,c)}finally{s.v=!0}void 0!==d&&(old_assertValidReturnValue(10,d),i=d)}e.push(i,(function(){for(var e=0;e<o.length;e++)o[e].call(i)}))}}function applyDecs(e,t,a){var r=[],o={},i={};return old_applyMemberDecs(r,e,i,o,t),old_convertMetadataMapToFinal(e.prototype,i),old_applyClassDecs(r,e,o,a),old_convertMetadataMapToFinal(e,o),r}',{globals:["Object","Map","Symbol","Array","Error","TypeError","console"],locals:{old_createMetadataMethodsForProperty:["body.0.id","body.3.body.body.4.block.body.0.argument.arguments.1.arguments.1.callee","body.12.body.body.0.consequent.body.0.body.body.1.block.body.0.declarations.0.init.arguments.1.callee"],old_convertMetadataMapToFinal:["body.1.id","body.13.body.body.1.argument.expressions.1.callee","body.13.body.body.1.argument.expressions.3.callee"],old_createAddInitializerMethod:["body.2.id","body.3.body.body.3.test.expressions.0.right.right.callee","body.12.body.body.0.consequent.body.0.body.body.1.block.body.0.declarations.0.init.arguments.0.properties.2.value.callee"],old_memberDec:["body.3.id","body.9.body.body.1.consequent.expression.left.right.right.callee","body.9.body.body.1.alternate.body.body.1.expression.left.right.right.callee"],old_assertNotFinished:["body.4.id","body.0.body.body.0.argument.properties.0.value.body.body.0.expression.expressions.0.callee","body.0.body.body.0.argument.properties.1.value.body.body.0.expression.expressions.0.callee","body.2.body.body.0.argument.body.body.0.expression.expressions.0.callee"],old_assertMetadataKey:["body.5.id","body.0.body.body.0.argument.properties.0.value.body.body.0.expression.expressions.1.callee","body.0.body.body.0.argument.properties.1.value.body.body.0.expression.expressions.1.callee"],old_assertCallable:["body.6.id","body.2.body.body.0.argument.body.body.0.expression.expressions.1.callee","body.7.body.body.1.consequent.body.1.expression.expressions.0.right.callee","body.7.body.body.1.consequent.body.1.expression.expressions.1.right.callee","body.7.body.body.1.consequent.body.1.expression.expressions.2.right.callee","body.7.body.body.1.consequent.body.1.expression.expressions.3.right.callee"],old_assertValidReturnValue:["body.7.id","body.9.body.body.1.consequent.expression.right.expressions.0.callee","body.9.body.body.1.alternate.body.body.1.expression.right.expressions.0.callee","body.12.body.body.0.consequent.body.0.body.body.2.expression.right.expressions.0.callee"],old_getInit:["body.8.id","body.9.body.body.1.consequent.expression.right.expressions.1.alternate.consequent.expressions.0.right.callee","body.9.body.body.1.alternate.body.body.1.expression.right.expressions.1.alternate.consequent.expressions.0.right.callee"],old_applyMemberDec:["body.9.id","body.10.body.body.0.body.body.1.consequent.body.2.expression.callee"],old_applyMemberDecs:["body.10.id","body.13.body.body.1.argument.expressions.0.callee"],old_pushInitializers:["body.11.id","body.10.body.body.1.expression.expressions.0.callee","body.10.body.body.1.expression.expressions.1.callee"],old_applyClassDecs:["body.12.id","body.13.body.body.1.argument.expressions.2.callee"],applyDecs:["body.13.id"]},exportBindingAssignments:[],exportName:"applyDecs",dependencies:{setFunctionName:["body.9.body.body.1.test.expressions.0.consequent.expressions.1.right.expressions.0.right.callee","body.9.body.body.1.test.expressions.0.consequent.expressions.1.right.expressions.1.callee"],toPropertyKey:["body.3.body.body.2.declarations.2.init.properties.1.value.alternate.callee"]}}),applyDecs2203:s("7.19.0",'function applyDecs2203Factory(){function createAddInitializerMethod(e,t){return function(r){!function(e,t){if(e.v)throw Error("attempted to call addInitializer after decoration was finished")}(t),assertCallable(r,"An initializer"),e.push(r)}}function memberDec(e,t,r,a,n,i,s,o){var c;switch(n){case 1:c="accessor";break;case 2:c="method";break;case 3:c="getter";break;case 4:c="setter";break;default:c="field"}var l,u,f={kind:c,name:s?"#"+t:t,static:i,private:s},p={v:!1};0!==n&&(f.addInitializer=createAddInitializerMethod(a,p)),0===n?s?(l=r.get,u=r.set):(l=function(){return this[t]},u=function(e){this[t]=e}):2===n?l=function(){return r.value}:(1!==n&&3!==n||(l=function(){return r.get.call(this)}),1!==n&&4!==n||(u=function(e){r.set.call(this,e)})),f.access=l&&u?{get:l,set:u}:l?{get:l}:{set:u};try{return e(o,f)}finally{p.v=!0}}function assertCallable(e,t){if("function"!=typeof e)throw new TypeError(t+" must be a function")}function assertValidReturnValue(e,t){var r=typeof t;if(1===e){if("object"!==r||null===t)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");void 0!==t.get&&assertCallable(t.get,"accessor.get"),void 0!==t.set&&assertCallable(t.set,"accessor.set"),void 0!==t.init&&assertCallable(t.init,"accessor.init")}else if("function"!==r)throw new TypeError((0===e?"field":10===e?"class":"method")+" decorators must return a function or void 0")}function applyMemberDec(e,t,r,a,n,i,s,o){var c,l,u,f,p,d,h=r[0];if(s?c=0===n||1===n?{get:r[3],set:r[4]}:3===n?{get:r[3]}:4===n?{set:r[3]}:{value:r[3]}:0!==n&&(c=Object.getOwnPropertyDescriptor(t,a)),1===n?u={get:c.get,set:c.set}:2===n?u=c.value:3===n?u=c.get:4===n&&(u=c.set),"function"==typeof h)void 0!==(f=memberDec(h,a,c,o,n,i,s,u))&&(assertValidReturnValue(n,f),0===n?l=f:1===n?(l=f.init,p=f.get||u.get,d=f.set||u.set,u={get:p,set:d}):u=f);else for(var v=h.length-1;v>=0;v--){var g;void 0!==(f=memberDec(h[v],a,c,o,n,i,s,u))&&(assertValidReturnValue(n,f),0===n?g=f:1===n?(g=f.init,p=f.get||u.get,d=f.set||u.set,u={get:p,set:d}):u=f,void 0!==g&&(void 0===l?l=g:"function"==typeof l?l=[l,g]:l.push(g)))}if(0===n||1===n){if(void 0===l)l=function(e,t){return t};else if("function"!=typeof l){var y=l;l=function(e,t){for(var r=t,a=0;a<y.length;a++)r=y[a].call(e,r);return r}}else{var m=l;l=function(e,t){return m.call(e,t)}}e.push(l)}0!==n&&(1===n?(c.get=u.get,c.set=u.set):2===n?c.value=u:3===n?c.get=u:4===n&&(c.set=u),s?1===n?(e.push((function(e,t){return u.get.call(e,t)})),e.push((function(e,t){return u.set.call(e,t)}))):2===n?e.push(u):e.push((function(e,t){return u.call(e,t)})):Object.defineProperty(t,a,c))}function pushInitializers(e,t){t&&e.push((function(e){for(var r=0;r<t.length;r++)t[r].call(e);return e}))}return function(e,t,r){var a=[];return function(e,t,r){for(var a,n,i=new Map,s=new Map,o=0;o<r.length;o++){var c=r[o];if(Array.isArray(c)){var l,u,f=c[1],p=c[2],d=c.length>3,h=f>=5;if(h?(l=t,0!=(f-=5)&&(u=n=n||[])):(l=t.prototype,0!==f&&(u=a=a||[])),0!==f&&!d){var v=h?s:i,g=v.get(p)||0;if(!0===g||3===g&&4!==f||4===g&&3!==f)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+p);!g&&f>2?v.set(p,f):v.set(p,!0)}applyMemberDec(e,l,c,p,f,h,d,u)}}pushInitializers(e,a),pushInitializers(e,n)}(a,e,t),function(e,t,r){if(r.length>0){for(var a=[],n=t,i=t.name,s=r.length-1;s>=0;s--){var o={v:!1};try{var c=r[s](n,{kind:"class",name:i,addInitializer:createAddInitializerMethod(a,o)})}finally{o.v=!0}void 0!==c&&(assertValidReturnValue(10,c),n=c)}e.push(n,(function(){for(var e=0;e<a.length;e++)a[e].call(n)}))}}(a,e,r),a}}var applyDecs2203Impl;function applyDecs2203(e,t,r){return(applyDecs2203Impl=applyDecs2203Impl||applyDecs2203Factory())(e,t,r)}',{globals:["Error","TypeError","Object","Map","Array"],locals:{applyDecs2203Factory:["body.0.id","body.2.body.body.0.argument.callee.right.right.callee"],applyDecs2203Impl:["body.1.declarations.0.id","body.2.body.body.0.argument.callee.right.left","body.2.body.body.0.argument.callee.left"],applyDecs2203:["body.2.id"]},exportBindingAssignments:[],exportName:"applyDecs2203",dependencies:{}}),applyDecs2203R:s("7.20.0",'function applyDecs2203RFactory(){function createAddInitializerMethod(e,t){return function(r){!function(e,t){if(e.v)throw Error("attempted to call addInitializer after decoration was finished")}(t),assertCallable(r,"An initializer"),e.push(r)}}function memberDec(e,t,r,n,a,i,o,s){var c;switch(a){case 1:c="accessor";break;case 2:c="method";break;case 3:c="getter";break;case 4:c="setter";break;default:c="field"}var l,u,f={kind:c,name:o?"#"+t:toPropertyKey(t),static:i,private:o},p={v:!1};0!==a&&(f.addInitializer=createAddInitializerMethod(n,p)),0===a?o?(l=r.get,u=r.set):(l=function(){return this[t]},u=function(e){this[t]=e}):2===a?l=function(){return r.value}:(1!==a&&3!==a||(l=function(){return r.get.call(this)}),1!==a&&4!==a||(u=function(e){r.set.call(this,e)})),f.access=l&&u?{get:l,set:u}:l?{get:l}:{set:u};try{return e(s,f)}finally{p.v=!0}}function assertCallable(e,t){if("function"!=typeof e)throw new TypeError(t+" must be a function")}function assertValidReturnValue(e,t){var r=typeof t;if(1===e){if("object"!==r||null===t)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");void 0!==t.get&&assertCallable(t.get,"accessor.get"),void 0!==t.set&&assertCallable(t.set,"accessor.set"),void 0!==t.init&&assertCallable(t.init,"accessor.init")}else if("function"!==r)throw new TypeError((0===e?"field":10===e?"class":"method")+" decorators must return a function or void 0")}function applyMemberDec(e,t,r,n,a,i,o,s){var c,l,u,f,p,d,h,v=r[0];if(o?(0===a||1===a?(c={get:r[3],set:r[4]},u="get"):3===a?(c={get:r[3]},u="get"):4===a?(c={set:r[3]},u="set"):c={value:r[3]},0!==a&&(1===a&&setFunctionName(r[4],"#"+n,"set"),setFunctionName(r[3],"#"+n,u))):0!==a&&(c=Object.getOwnPropertyDescriptor(t,n)),1===a?f={get:c.get,set:c.set}:2===a?f=c.value:3===a?f=c.get:4===a&&(f=c.set),"function"==typeof v)void 0!==(p=memberDec(v,n,c,s,a,i,o,f))&&(assertValidReturnValue(a,p),0===a?l=p:1===a?(l=p.init,d=p.get||f.get,h=p.set||f.set,f={get:d,set:h}):f=p);else for(var g=v.length-1;g>=0;g--){var y;void 0!==(p=memberDec(v[g],n,c,s,a,i,o,f))&&(assertValidReturnValue(a,p),0===a?y=p:1===a?(y=p.init,d=p.get||f.get,h=p.set||f.set,f={get:d,set:h}):f=p,void 0!==y&&(void 0===l?l=y:"function"==typeof l?l=[l,y]:l.push(y)))}if(0===a||1===a){if(void 0===l)l=function(e,t){return t};else if("function"!=typeof l){var m=l;l=function(e,t){for(var r=t,n=0;n<m.length;n++)r=m[n].call(e,r);return r}}else{var b=l;l=function(e,t){return b.call(e,t)}}e.push(l)}0!==a&&(1===a?(c.get=f.get,c.set=f.set):2===a?c.value=f:3===a?c.get=f:4===a&&(c.set=f),o?1===a?(e.push((function(e,t){return f.get.call(e,t)})),e.push((function(e,t){return f.set.call(e,t)}))):2===a?e.push(f):e.push((function(e,t){return f.call(e,t)})):Object.defineProperty(t,n,c))}function applyMemberDecs(e,t){for(var r,n,a=[],i=new Map,o=new Map,s=0;s<t.length;s++){var c=t[s];if(Array.isArray(c)){var l,u,f=c[1],p=c[2],d=c.length>3,h=f>=5;if(h?(l=e,0!=(f-=5)&&(u=n=n||[])):(l=e.prototype,0!==f&&(u=r=r||[])),0!==f&&!d){var v=h?o:i,g=v.get(p)||0;if(!0===g||3===g&&4!==f||4===g&&3!==f)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+p);!g&&f>2?v.set(p,f):v.set(p,!0)}applyMemberDec(a,l,c,p,f,h,d,u)}}return pushInitializers(a,r),pushInitializers(a,n),a}function pushInitializers(e,t){t&&e.push((function(e){for(var r=0;r<t.length;r++)t[r].call(e);return e}))}return function(e,t,r){return{e:applyMemberDecs(e,t),get c(){return function(e,t){if(t.length>0){for(var r=[],n=e,a=e.name,i=t.length-1;i>=0;i--){var o={v:!1};try{var s=t[i](n,{kind:"class",name:a,addInitializer:createAddInitializerMethod(r,o)})}finally{o.v=!0}void 0!==s&&(assertValidReturnValue(10,s),n=s)}return[n,function(){for(var e=0;e<r.length;e++)r[e].call(n)}]}}(e,r)}}}}function applyDecs2203R(e,t,r){return(applyDecs2203R=applyDecs2203RFactory())(e,t,r)}',{globals:["Error","TypeError","Object","Map","Array"],locals:{applyDecs2203RFactory:["body.0.id","body.1.body.body.0.argument.callee.right.callee"],applyDecs2203R:["body.1.id","body.1.body.body.0.argument.callee.left"]},exportBindingAssignments:["body.1.body.body.0.argument.callee"],exportName:"applyDecs2203R",dependencies:{setFunctionName:["body.0.body.body.4.body.body.1.test.expressions.0.consequent.expressions.1.right.expressions.0.right.callee","body.0.body.body.4.body.body.1.test.expressions.0.consequent.expressions.1.right.expressions.1.callee"],toPropertyKey:["body.0.body.body.1.body.body.2.declarations.2.init.properties.1.value.alternate.callee"]}}),applyDecs2301:s("7.21.0",'function applyDecs2301Factory(){function createAddInitializerMethod(e,t){return function(r){!function(e,t){if(e.v)throw Error("attempted to call addInitializer after decoration was finished")}(t),assertCallable(r,"An initializer"),e.push(r)}}function assertInstanceIfPrivate(e,t){if(!e(t))throw new TypeError("Attempted to access private element on non-instance")}function memberDec(e,t,r,n,a,i,s,o,c){var u;switch(a){case 1:u="accessor";break;case 2:u="method";break;case 3:u="getter";break;case 4:u="setter";break;default:u="field"}var l,f,p={kind:u,name:s?"#"+t:toPropertyKey(t),static:i,private:s},d={v:!1};if(0!==a&&(p.addInitializer=createAddInitializerMethod(n,d)),s||0!==a&&2!==a)if(2===a)l=function(e){return assertInstanceIfPrivate(c,e),r.value};else{var h=0===a||1===a;(h||3===a)&&(l=s?function(e){return assertInstanceIfPrivate(c,e),r.get.call(e)}:function(e){return r.get.call(e)}),(h||4===a)&&(f=s?function(e,t){assertInstanceIfPrivate(c,e),r.set.call(e,t)}:function(e,t){r.set.call(e,t)})}else l=function(e){return e[t]},0===a&&(f=function(e,r){e[t]=r});var v=s?c.bind():function(e){return t in e};p.access=l&&f?{get:l,set:f,has:v}:l?{get:l,has:v}:{set:f,has:v};try{return e(o,p)}finally{d.v=!0}}function assertCallable(e,t){if("function"!=typeof e)throw new TypeError(t+" must be a function")}function assertValidReturnValue(e,t){var r=typeof t;if(1===e){if("object"!==r||null===t)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");void 0!==t.get&&assertCallable(t.get,"accessor.get"),void 0!==t.set&&assertCallable(t.set,"accessor.set"),void 0!==t.init&&assertCallable(t.init,"accessor.init")}else if("function"!==r)throw new TypeError((0===e?"field":10===e?"class":"method")+" decorators must return a function or void 0")}function curryThis2(e){return function(t){e(this,t)}}function applyMemberDec(e,t,r,n,a,i,s,o,c){var u,l,f,p,d,h,v,y,g=r[0];if(s?(0===a||1===a?(u={get:(d=r[3],function(){return d(this)}),set:curryThis2(r[4])},f="get"):3===a?(u={get:r[3]},f="get"):4===a?(u={set:r[3]},f="set"):u={value:r[3]},0!==a&&(1===a&&setFunctionName(u.set,"#"+n,"set"),setFunctionName(u[f||"value"],"#"+n,f))):0!==a&&(u=Object.getOwnPropertyDescriptor(t,n)),1===a?p={get:u.get,set:u.set}:2===a?p=u.value:3===a?p=u.get:4===a&&(p=u.set),"function"==typeof g)void 0!==(h=memberDec(g,n,u,o,a,i,s,p,c))&&(assertValidReturnValue(a,h),0===a?l=h:1===a?(l=h.init,v=h.get||p.get,y=h.set||p.set,p={get:v,set:y}):p=h);else for(var m=g.length-1;m>=0;m--){var b;void 0!==(h=memberDec(g[m],n,u,o,a,i,s,p,c))&&(assertValidReturnValue(a,h),0===a?b=h:1===a?(b=h.init,v=h.get||p.get,y=h.set||p.set,p={get:v,set:y}):p=h,void 0!==b&&(void 0===l?l=b:"function"==typeof l?l=[l,b]:l.push(b)))}if(0===a||1===a){if(void 0===l)l=function(e,t){return t};else if("function"!=typeof l){var I=l;l=function(e,t){for(var r=t,n=0;n<I.length;n++)r=I[n].call(e,r);return r}}else{var w=l;l=function(e,t){return w.call(e,t)}}e.push(l)}0!==a&&(1===a?(u.get=p.get,u.set=p.set):2===a?u.value=p:3===a?u.get=p:4===a&&(u.set=p),s?1===a?(e.push((function(e,t){return p.get.call(e,t)})),e.push((function(e,t){return p.set.call(e,t)}))):2===a?e.push(p):e.push((function(e,t){return p.call(e,t)})):Object.defineProperty(t,n,u))}function applyMemberDecs(e,t,r){for(var n,a,i,s=[],o=new Map,c=new Map,u=0;u<t.length;u++){var l=t[u];if(Array.isArray(l)){var f,p,d=l[1],h=l[2],v=l.length>3,y=d>=5,g=r;if(y?(f=e,0!=(d-=5)&&(p=a=a||[]),v&&!i&&(i=function(t){return checkInRHS(t)===e}),g=i):(f=e.prototype,0!==d&&(p=n=n||[])),0!==d&&!v){var m=y?c:o,b=m.get(h)||0;if(!0===b||3===b&&4!==d||4===b&&3!==d)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+h);!b&&d>2?m.set(h,d):m.set(h,!0)}applyMemberDec(s,f,l,h,d,y,v,p,g)}}return pushInitializers(s,n),pushInitializers(s,a),s}function pushInitializers(e,t){t&&e.push((function(e){for(var r=0;r<t.length;r++)t[r].call(e);return e}))}return function(e,t,r,n){return{e:applyMemberDecs(e,t,n),get c(){return function(e,t){if(t.length>0){for(var r=[],n=e,a=e.name,i=t.length-1;i>=0;i--){var s={v:!1};try{var o=t[i](n,{kind:"class",name:a,addInitializer:createAddInitializerMethod(r,s)})}finally{s.v=!0}void 0!==o&&(assertValidReturnValue(10,o),n=o)}return[n,function(){for(var e=0;e<r.length;e++)r[e].call(n)}]}}(e,r)}}}}function applyDecs2301(e,t,r,n){return(applyDecs2301=applyDecs2301Factory())(e,t,r,n)}',{globals:["Error","TypeError","Object","Map","Array"],locals:{applyDecs2301Factory:["body.0.id","body.1.body.body.0.argument.callee.right.callee"],applyDecs2301:["body.1.id","body.1.body.body.0.argument.callee.left"]},exportBindingAssignments:["body.1.body.body.0.argument.callee"],exportName:"applyDecs2301",dependencies:{checkInRHS:["body.0.body.body.7.body.body.0.body.body.1.consequent.body.1.test.expressions.0.consequent.expressions.2.right.right.body.body.0.argument.left.callee"],setFunctionName:["body.0.body.body.6.body.body.1.test.expressions.0.consequent.expressions.1.right.expressions.0.right.callee","body.0.body.body.6.body.body.1.test.expressions.0.consequent.expressions.1.right.expressions.1.callee"],toPropertyKey:["body.0.body.body.2.body.body.2.declarations.2.init.properties.1.value.alternate.callee"]}}),applyDecs2305:s("7.21.0",'function applyDecs2305(e,t,r,n,o,a){function i(e,t,r){return function(n,o){return r&&r(n),e[t].call(n,o)}}function c(e,t){for(var r=0;r<e.length;r++)e[r].call(t);return t}function s(e,t,r,n){if("function"!=typeof e&&(n||void 0!==e))throw new TypeError(t+" must "+(r||"be")+" a function"+(n?"":" or undefined"));return e}function applyDec(e,t,r,n,o,a,c,u,l,f,p,d,h){function m(e){if(!h(e))throw new TypeError("Attempted to access private element on non-instance")}var y,v=t[0],g=t[3],b=!u;if(!b){r||Array.isArray(v)||(v=[v]);var w={},S=[],A=3===o?"get":4===o||d?"set":"value";f?(p||d?w={get:setFunctionName((function(){return g(this)}),n,"get"),set:function(e){t[4](this,e)}}:w[A]=g,p||setFunctionName(w[A],n,2===o?"":A)):p||(w=Object.getOwnPropertyDescriptor(e,n))}for(var P=e,j=v.length-1;j>=0;j-=r?2:1){var D=v[j],E=r?v[j-1]:void 0,I={},O={kind:["field","accessor","method","getter","setter","class"][o],name:n,metadata:a,addInitializer:function(e,t){if(e.v)throw Error("attempted to call addInitializer after decoration was finished");s(t,"An initializer","be",!0),c.push(t)}.bind(null,I)};try{if(b)(y=s(D.call(E,P,O),"class decorators","return"))&&(P=y);else{var k,F;O.static=l,O.private=f,f?2===o?k=function(e){return m(e),w.value}:(o<4&&(k=i(w,"get",m)),3!==o&&(F=i(w,"set",m))):(k=function(e){return e[n]},(o<2||4===o)&&(F=function(e,t){e[n]=t}));var N=O.access={has:f?h.bind():function(e){return n in e}};if(k&&(N.get=k),F&&(N.set=F),P=D.call(E,d?{get:w.get,set:w.set}:w[A],O),d){if("object"==typeof P&&P)(y=s(P.get,"accessor.get"))&&(w.get=y),(y=s(P.set,"accessor.set"))&&(w.set=y),(y=s(P.init,"accessor.init"))&&S.push(y);else if(void 0!==P)throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0")}else s(P,(p?"field":"method")+" decorators","return")&&(p?S.push(P):w[A]=P)}}finally{I.v=!0}}return(p||d)&&u.push((function(e,t){for(var r=S.length-1;r>=0;r--)t=S[r].call(e,t);return t})),p||b||(f?d?u.push(i(w,"get"),i(w,"set")):u.push(2===o?w[A]:i.call.bind(w[A])):Object.defineProperty(e,n,w)),P}function u(e,t){return Object.defineProperty(e,Symbol.metadata||Symbol.for("Symbol.metadata"),{configurable:!0,enumerable:!0,value:t})}if(arguments.length>=6)var l=a[Symbol.metadata||Symbol.for("Symbol.metadata")];var f=Object.create(null==l?null:l),p=function(e,t,r,n){var o,a,i=[],s=function(t){return checkInRHS(t)===e},u=new Map;function l(e){e&&i.push(c.bind(null,e))}for(var f=0;f<t.length;f++){var p=t[f];if(Array.isArray(p)){var d=p[1],h=p[2],m=p.length>3,y=16&d,v=!!(8&d),g=0==(d&=7),b=h+"/"+v;if(!g&&!m){var w=u.get(b);if(!0===w||3===w&&4!==d||4===w&&3!==d)throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+h);u.set(b,!(d>2)||d)}applyDec(v?e:e.prototype,p,y,m?"#"+h:toPropertyKey(h),d,n,v?a=a||[]:o=o||[],i,v,m,g,1===d,v&&m?s:r)}}return l(o),l(a),i}(e,t,o,f);return r.length||u(e,f),{e:p,get c(){var t=[];return r.length&&[u(applyDec(e,[r],n,e.name,5,f,t),f),c.bind(null,t,e)]}}}',{globals:["TypeError","Array","Object","Error","Symbol","Map"],locals:{applyDecs2305:["body.0.id"]},exportBindingAssignments:[],exportName:"applyDecs2305",dependencies:{checkInRHS:["body.0.body.body.6.declarations.1.init.callee.body.body.0.declarations.3.init.body.body.0.argument.left.callee"],setFunctionName:["body.0.body.body.3.body.body.2.consequent.body.2.expression.consequent.expressions.0.consequent.right.properties.0.value.callee","body.0.body.body.3.body.body.2.consequent.body.2.expression.consequent.expressions.1.right.callee"],toPropertyKey:["body.0.body.body.6.declarations.1.init.callee.body.body.2.body.body.1.consequent.body.2.expression.arguments.3.alternate.callee"]}}),classApplyDescriptorDestructureSet:s("7.13.10",'function _classApplyDescriptorDestructureSet(e,t){if(t.set)return"__destrObj"in t||(t.__destrObj={set value(r){t.set.call(e,r)}}),t.__destrObj;if(!t.writable)throw new TypeError("attempted to set read only private field");return t}',{globals:["TypeError"],locals:{_classApplyDescriptorDestructureSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classApplyDescriptorDestructureSet",dependencies:{}}),classApplyDescriptorGet:s("7.13.10","function _classApplyDescriptorGet(e,t){return t.get?t.get.call(e):t.value}",{globals:[],locals:{_classApplyDescriptorGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classApplyDescriptorGet",dependencies:{}}),classApplyDescriptorSet:s("7.13.10",'function _classApplyDescriptorSet(e,t,l){if(t.set)t.set.call(e,l);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=l}}',{globals:["TypeError"],locals:{_classApplyDescriptorSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classApplyDescriptorSet",dependencies:{}}),classCheckPrivateStaticAccess:s("7.13.10","function _classCheckPrivateStaticAccess(s,a,r){return assertClassBrand(a,s,r)}",{globals:[],locals:{_classCheckPrivateStaticAccess:["body.0.id"]},exportBindingAssignments:[],exportName:"_classCheckPrivateStaticAccess",dependencies:{assertClassBrand:["body.0.body.body.0.argument.callee"]}}),classCheckPrivateStaticFieldDescriptor:s("7.13.10",'function _classCheckPrivateStaticFieldDescriptor(t,e){if(void 0===t)throw new TypeError("attempted to "+e+" private static field before its declaration")}',{globals:["TypeError"],locals:{_classCheckPrivateStaticFieldDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_classCheckPrivateStaticFieldDescriptor",dependencies:{}}),classExtractFieldDescriptor:s("7.13.10","function _classExtractFieldDescriptor(e,t){return classPrivateFieldGet2(t,e)}",{globals:[],locals:{_classExtractFieldDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_classExtractFieldDescriptor",dependencies:{classPrivateFieldGet2:["body.0.body.body.0.argument.callee"]}}),classPrivateFieldDestructureSet:s("7.4.4","function _classPrivateFieldDestructureSet(e,t){var r=classPrivateFieldGet2(t,e);return classApplyDescriptorDestructureSet(e,r)}",{globals:[],locals:{_classPrivateFieldDestructureSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldDestructureSet",dependencies:{classApplyDescriptorDestructureSet:["body.0.body.body.1.argument.callee"],classPrivateFieldGet2:["body.0.body.body.0.declarations.0.init.callee"]}}),classPrivateFieldGet:s("7.0.0-beta.0","function _classPrivateFieldGet(e,t){var r=classPrivateFieldGet2(t,e);return classApplyDescriptorGet(e,r)}",{globals:[],locals:{_classPrivateFieldGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldGet",dependencies:{classApplyDescriptorGet:["body.0.body.body.1.argument.callee"],classPrivateFieldGet2:["body.0.body.body.0.declarations.0.init.callee"]}}),classPrivateFieldSet:s("7.0.0-beta.0","function _classPrivateFieldSet(e,t,r){var s=classPrivateFieldGet2(t,e);return classApplyDescriptorSet(e,s,r),r}",{globals:[],locals:{_classPrivateFieldSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateFieldSet",dependencies:{classApplyDescriptorSet:["body.0.body.body.1.argument.expressions.0.callee"],classPrivateFieldGet2:["body.0.body.body.0.declarations.0.init.callee"]}}),classPrivateMethodGet:s("7.1.6","function _classPrivateMethodGet(s,a,r){return assertClassBrand(a,s),r}",{globals:[],locals:{_classPrivateMethodGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateMethodGet",dependencies:{assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"]}}),classPrivateMethodSet:s("7.1.6",'function _classPrivateMethodSet(){throw new TypeError("attempted to reassign private method")}',{globals:["TypeError"],locals:{_classPrivateMethodSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classPrivateMethodSet",dependencies:{}}),classStaticPrivateFieldDestructureSet:s("7.13.10",'function _classStaticPrivateFieldDestructureSet(t,r,s){return assertClassBrand(r,t),classCheckPrivateStaticFieldDescriptor(s,"set"),classApplyDescriptorDestructureSet(t,s)}',{globals:[],locals:{_classStaticPrivateFieldDestructureSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateFieldDestructureSet",dependencies:{classApplyDescriptorDestructureSet:["body.0.body.body.0.argument.expressions.2.callee"],assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"],classCheckPrivateStaticFieldDescriptor:["body.0.body.body.0.argument.expressions.1.callee"]}}),classStaticPrivateFieldSpecGet:s("7.0.2",'function _classStaticPrivateFieldSpecGet(t,s,r){return assertClassBrand(s,t),classCheckPrivateStaticFieldDescriptor(r,"get"),classApplyDescriptorGet(t,r)}',{globals:[],locals:{_classStaticPrivateFieldSpecGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateFieldSpecGet",dependencies:{classApplyDescriptorGet:["body.0.body.body.0.argument.expressions.2.callee"],assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"],classCheckPrivateStaticFieldDescriptor:["body.0.body.body.0.argument.expressions.1.callee"]}}),classStaticPrivateFieldSpecSet:s("7.0.2",'function _classStaticPrivateFieldSpecSet(s,t,r,e){return assertClassBrand(t,s),classCheckPrivateStaticFieldDescriptor(r,"set"),classApplyDescriptorSet(s,r,e),e}',{globals:[],locals:{_classStaticPrivateFieldSpecSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateFieldSpecSet",dependencies:{classApplyDescriptorSet:["body.0.body.body.0.argument.expressions.2.callee"],assertClassBrand:["body.0.body.body.0.argument.expressions.0.callee"],classCheckPrivateStaticFieldDescriptor:["body.0.body.body.0.argument.expressions.1.callee"]}}),classStaticPrivateMethodSet:s("7.3.2",'function _classStaticPrivateMethodSet(){throw new TypeError("attempted to set read only static private field")}',{globals:["TypeError"],locals:{_classStaticPrivateMethodSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_classStaticPrivateMethodSet",dependencies:{}}),defineEnumerableProperties:s("7.0.0-beta.0",'function _defineEnumerableProperties(e,r){for(var t in r){var n=r[t];n.configurable=n.enumerable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,t,n)}if(Object.getOwnPropertySymbols)for(var a=Object.getOwnPropertySymbols(r),b=0;b<a.length;b++){var i=a[b];(n=r[i]).configurable=n.enumerable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,i,n)}return e}',{globals:["Object"],locals:{_defineEnumerableProperties:["body.0.id"]},exportBindingAssignments:[],exportName:"_defineEnumerableProperties",dependencies:{}}),dispose:s("7.22.0",'function dispose_SuppressedError(r,e){return"undefined"!=typeof SuppressedError?dispose_SuppressedError=SuppressedError:(dispose_SuppressedError=function(r,e){this.suppressed=e,this.error=r,this.stack=Error().stack},dispose_SuppressedError.prototype=Object.create(Error.prototype,{constructor:{value:dispose_SuppressedError,writable:!0,configurable:!0}})),new dispose_SuppressedError(r,e)}function _dispose(r,e,s){function next(){for(;r.length>0;)try{var o=r.pop(),p=o.d.call(o.v);if(o.a)return Promise.resolve(p).then(next,err)}catch(r){return err(r)}if(s)throw e}function err(r){return e=s?new dispose_SuppressedError(e,r):r,s=!0,next()}return next()}',{globals:["SuppressedError","Error","Object","Promise"],locals:{dispose_SuppressedError:["body.0.id","body.0.body.body.0.argument.expressions.0.alternate.expressions.1.left.object","body.0.body.body.0.argument.expressions.0.alternate.expressions.1.right.arguments.1.properties.0.value.properties.0.value","body.0.body.body.0.argument.expressions.1.callee","body.1.body.body.1.body.body.0.argument.expressions.0.right.consequent.callee","body.0.body.body.0.argument.expressions.0.consequent.left","body.0.body.body.0.argument.expressions.0.alternate.expressions.0.left"],_dispose:["body.1.id"]},exportBindingAssignments:[],exportName:"_dispose",dependencies:{}}),objectSpread:s("7.0.0-beta.0",'function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?Object(arguments[r]):{},o=Object.keys(t);"function"==typeof Object.getOwnPropertySymbols&&o.push.apply(o,Object.getOwnPropertySymbols(t).filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),o.forEach((function(r){defineProperty(e,r,t[r])}))}return e}',{globals:["Object"],locals:{_objectSpread:["body.0.id"]},exportBindingAssignments:[],exportName:"_objectSpread",dependencies:{defineProperty:["body.0.body.body.0.body.body.1.expression.expressions.1.arguments.0.body.body.0.expression.callee"]}}),using:s("7.22.0",'function _using(o,n,e){if(null==n)return n;if(Object(n)!==n)throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(e)var r=n[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(null==r&&(r=n[Symbol.dispose||Symbol.for("Symbol.dispose")]),"function"!=typeof r)throw new TypeError("Property [Symbol.dispose] is not a function.");return o.push({v:n,d:r,a:e}),n}',{globals:["Object","TypeError","Symbol"],locals:{_using:["body.0.id"]},exportBindingAssignments:[],exportName:"_using",dependencies:{}})})},9897:(e,t,r)=>{"use strict";var n=r(5158),s=r(7596);const i=(0,s.defineAliasedType)("Flow"),a=e=>{const t="DeclareClass"===e;i(e,{builder:["id","typeParameters","extends","body"],visitor:["id","typeParameters","extends",...t?["mixins","implements"]:[],"body"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({id:(0,s.validateType)("Identifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterDeclaration"),extends:(0,s.validateOptional)((0,s.arrayOfType)("InterfaceExtends"))},t?{mixins:(0,s.validateOptional)((0,s.arrayOfType)("InterfaceExtends")),implements:(0,s.validateOptional)((0,s.arrayOfType)("ClassImplements"))}:{},{body:(0,s.validateType)("ObjectTypeAnnotation")})})};i("AnyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["FlowType"],fields:{elementType:(0,s.validateType)("FlowType")}}),i("BooleanTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("BooleanLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("NullLiteralTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("ClassImplements",{visitor:["id","typeParameters"],fields:{id:(0,s.validateType)("Identifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterInstantiation")}}),a("DeclareClass"),i("DeclareFunction",{builder:["id"],visitor:["id","predicate"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier"),predicate:(0,s.validateOptionalType)("DeclaredPredicate")}}),a("DeclareInterface"),i("DeclareModule",{builder:["id","body","kind"],visitor:["id","body"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier","StringLiteral"),body:(0,s.validateType)("BlockStatement"),kind:(0,s.validateOptional)((0,s.assertOneOf)("CommonJS","ES"))}}),i("DeclareModuleExports",{visitor:["typeAnnotation"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{typeAnnotation:(0,s.validateType)("TypeAnnotation")}}),i("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterDeclaration"),right:(0,s.validateType)("FlowType")}}),i("DeclareOpaqueType",{visitor:["id","typeParameters","supertype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterDeclaration"),supertype:(0,s.validateOptionalType)("FlowType"),impltype:(0,s.validateOptionalType)("FlowType")}}),i("DeclareVariable",{visitor:["id"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier")}}),i("DeclareExportDeclaration",{visitor:["declaration","specifiers","source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({declaration:(0,s.validateOptionalType)("Flow"),specifiers:(0,s.validateOptional)((0,s.arrayOfType)("ExportSpecifier","ExportNamespaceSpecifier")),source:(0,s.validateOptionalType)("StringLiteral"),default:(0,s.validateOptional)((0,s.assertValueType)("boolean"))},n.importAttributes)}),i("DeclareExportAllDeclaration",{visitor:["source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({source:(0,s.validateType)("StringLiteral"),exportKind:(0,s.validateOptional)((0,s.assertOneOf)("type","value"))},n.importAttributes)}),i("DeclaredPredicate",{visitor:["value"],aliases:["FlowPredicate"],fields:{value:(0,s.validateType)("Flow")}}),i("ExistsTypeAnnotation",{aliases:["FlowType"]}),i("FunctionTypeAnnotation",{builder:["typeParameters","params","rest","returnType"],visitor:["typeParameters","this","params","rest","returnType"],aliases:["FlowType"],fields:{typeParameters:(0,s.validateOptionalType)("TypeParameterDeclaration"),params:(0,s.validateArrayOfType)("FunctionTypeParam"),rest:(0,s.validateOptionalType)("FunctionTypeParam"),this:(0,s.validateOptionalType)("FunctionTypeParam"),returnType:(0,s.validateType)("FlowType")}}),i("FunctionTypeParam",{visitor:["name","typeAnnotation"],fields:{name:(0,s.validateOptionalType)("Identifier"),typeAnnotation:(0,s.validateType)("FlowType"),optional:(0,s.validateOptional)((0,s.assertValueType)("boolean"))}}),i("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["FlowType"],fields:{id:(0,s.validateType)("Identifier","QualifiedTypeIdentifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterInstantiation")}}),i("InferredPredicate",{aliases:["FlowPredicate"]}),i("InterfaceExtends",{visitor:["id","typeParameters"],fields:{id:(0,s.validateType)("Identifier","QualifiedTypeIdentifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterInstantiation")}}),a("InterfaceDeclaration"),i("InterfaceTypeAnnotation",{visitor:["extends","body"],aliases:["FlowType"],fields:{extends:(0,s.validateOptional)((0,s.arrayOfType)("InterfaceExtends")),body:(0,s.validateType)("ObjectTypeAnnotation")}}),i("IntersectionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:(0,s.validate)((0,s.arrayOfType)("FlowType"))}}),i("MixedTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("EmptyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["FlowType"],fields:{typeAnnotation:(0,s.validateType)("FlowType")}}),i("NumberLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:(0,s.validate)((0,s.assertValueType)("number"))}}),i("NumberTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties","internalSlots"],aliases:["FlowType"],builder:["properties","indexers","callProperties","internalSlots","exact"],fields:{properties:(0,s.validate)((0,s.arrayOfType)("ObjectTypeProperty","ObjectTypeSpreadProperty")),indexers:{validate:(0,s.arrayOfType)("ObjectTypeIndexer"),optional:!0,default:[]},callProperties:{validate:(0,s.arrayOfType)("ObjectTypeCallProperty"),optional:!0,default:[]},internalSlots:{validate:(0,s.arrayOfType)("ObjectTypeInternalSlot"),optional:!0,default:[]},exact:{validate:(0,s.assertValueType)("boolean"),default:!1},inexact:(0,s.validateOptional)((0,s.assertValueType)("boolean"))}}),i("ObjectTypeInternalSlot",{visitor:["id","value"],builder:["id","value","optional","static","method"],aliases:["UserWhitespacable"],fields:{id:(0,s.validateType)("Identifier"),value:(0,s.validateType)("FlowType"),optional:(0,s.validate)((0,s.assertValueType)("boolean")),static:(0,s.validate)((0,s.assertValueType)("boolean")),method:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("ObjectTypeCallProperty",{visitor:["value"],aliases:["UserWhitespacable"],fields:{value:(0,s.validateType)("FlowType"),static:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("ObjectTypeIndexer",{visitor:["variance","id","key","value"],builder:["id","key","value","variance"],aliases:["UserWhitespacable"],fields:{id:(0,s.validateOptionalType)("Identifier"),key:(0,s.validateType)("FlowType"),value:(0,s.validateType)("FlowType"),static:(0,s.validate)((0,s.assertValueType)("boolean")),variance:(0,s.validateOptionalType)("Variance")}}),i("ObjectTypeProperty",{visitor:["key","value","variance"],aliases:["UserWhitespacable"],fields:{key:(0,s.validateType)("Identifier","StringLiteral"),value:(0,s.validateType)("FlowType"),kind:(0,s.validate)((0,s.assertOneOf)("init","get","set")),static:(0,s.validate)((0,s.assertValueType)("boolean")),proto:(0,s.validate)((0,s.assertValueType)("boolean")),optional:(0,s.validate)((0,s.assertValueType)("boolean")),variance:(0,s.validateOptionalType)("Variance"),method:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("ObjectTypeSpreadProperty",{visitor:["argument"],aliases:["UserWhitespacable"],fields:{argument:(0,s.validateType)("FlowType")}}),i("OpaqueType",{visitor:["id","typeParameters","supertype","impltype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterDeclaration"),supertype:(0,s.validateOptionalType)("FlowType"),impltype:(0,s.validateType)("FlowType")}}),i("QualifiedTypeIdentifier",{visitor:["qualification","id"],builder:["id","qualification"],fields:{id:(0,s.validateType)("Identifier"),qualification:(0,s.validateType)("Identifier","QualifiedTypeIdentifier")}}),i("StringLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:(0,s.validate)((0,s.assertValueType)("string"))}}),i("StringTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("SymbolTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("ThisTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("TupleTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:(0,s.validate)((0,s.arrayOfType)("FlowType"))}}),i("TypeofTypeAnnotation",{visitor:["argument"],aliases:["FlowType"],fields:{argument:(0,s.validateType)("FlowType")}}),i("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:(0,s.validateType)("Identifier"),typeParameters:(0,s.validateOptionalType)("TypeParameterDeclaration"),right:(0,s.validateType)("FlowType")}}),i("TypeAnnotation",{visitor:["typeAnnotation"],fields:{typeAnnotation:(0,s.validateType)("FlowType")}}),i("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["ExpressionWrapper","Expression"],fields:{expression:(0,s.validateType)("Expression"),typeAnnotation:(0,s.validateType)("TypeAnnotation")}}),i("TypeParameter",{visitor:["bound","default","variance"],fields:{name:(0,s.validate)((0,s.assertValueType)("string")),bound:(0,s.validateOptionalType)("TypeAnnotation"),default:(0,s.validateOptionalType)("FlowType"),variance:(0,s.validateOptionalType)("Variance")}}),i("TypeParameterDeclaration",{visitor:["params"],fields:{params:(0,s.validate)((0,s.arrayOfType)("TypeParameter"))}}),i("TypeParameterInstantiation",{visitor:["params"],fields:{params:(0,s.validate)((0,s.arrayOfType)("FlowType"))}}),i("UnionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:(0,s.validate)((0,s.arrayOfType)("FlowType"))}}),i("Variance",{builder:["kind"],fields:{kind:(0,s.validate)((0,s.assertOneOf)("minus","plus"))}}),i("VoidTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),i("EnumDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:{id:(0,s.validateType)("Identifier"),body:(0,s.validateType)("EnumBooleanBody","EnumNumberBody","EnumStringBody","EnumSymbolBody")}}),i("EnumBooleanBody",{aliases:["EnumBody"],visitor:["members"],fields:{explicitType:(0,s.validate)((0,s.assertValueType)("boolean")),members:(0,s.validateArrayOfType)("EnumBooleanMember"),hasUnknownMembers:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("EnumNumberBody",{aliases:["EnumBody"],visitor:["members"],fields:{explicitType:(0,s.validate)((0,s.assertValueType)("boolean")),members:(0,s.validateArrayOfType)("EnumNumberMember"),hasUnknownMembers:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("EnumStringBody",{aliases:["EnumBody"],visitor:["members"],fields:{explicitType:(0,s.validate)((0,s.assertValueType)("boolean")),members:(0,s.validateArrayOfType)("EnumStringMember","EnumDefaultedMember"),hasUnknownMembers:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("EnumSymbolBody",{aliases:["EnumBody"],visitor:["members"],fields:{members:(0,s.validateArrayOfType)("EnumDefaultedMember"),hasUnknownMembers:(0,s.validate)((0,s.assertValueType)("boolean"))}}),i("EnumBooleanMember",{aliases:["EnumMember"],builder:["id"],visitor:["id","init"],fields:{id:(0,s.validateType)("Identifier"),init:(0,s.validateType)("BooleanLiteral")}}),i("EnumNumberMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:(0,s.validateType)("Identifier"),init:(0,s.validateType)("NumericLiteral")}}),i("EnumStringMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:(0,s.validateType)("Identifier"),init:(0,s.validateType)("StringLiteral")}}),i("EnumDefaultedMember",{aliases:["EnumMember"],visitor:["id"],fields:{id:(0,s.validateType)("Identifier")}}),i("IndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:(0,s.validateType)("FlowType"),indexType:(0,s.validateType)("FlowType")}}),i("OptionalIndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:(0,s.validateType)("FlowType"),indexType:(0,s.validateType)("FlowType"),optional:(0,s.validate)((0,s.assertValueType)("boolean"))}})},9923:(e,t)=>{"use strict";function r(e,t){for(const r of Object.keys(t)){const n=t[r];void 0!==n&&(e[r]=n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.isIterableIterator=function(e){return!!e&&"function"==typeof e.next&&"function"==typeof e[Symbol.iterator]},t.mergeOptions=function(e,t){for(const n of Object.keys(t))if("parserOpts"!==n&&"generatorOpts"!==n&&"assumptions"!==n||!t[n]){const r=t[n];void 0!==r&&(e[n]=r)}else{const s=t[n];r(e[n]||(e[n]={}),s)}}},9937:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ArrayExpression=w,t.AssignmentExpression=function(){return this.get("right").getTypeAnnotation()},t.BinaryExpression=function(e){const t=e.operator;if(l.includes(t))return b();if(a.includes(t))return f();if("+"===t){const e=this.get("right"),t=this.get("left");return t.isBaseType("number")&&e.isBaseType("number")?b():t.isBaseType("string")||e.isBaseType("string")?v():x([v(),b()])}},t.BooleanLiteral=function(){return f()},t.CallExpression=function(){const{callee:e}=this.node;return I(e)?d(v()):O(e)||N(e)||E(e,{name:"Array"})?d(u()):k(e)?d(T([v(),u()])):_(this.get("callee"))},t.ConditionalExpression=function(){const e=[this.get("consequent").getTypeAnnotation(),this.get("alternate").getTypeAnnotation()];return(0,i.createUnionType)(e)},t.ClassDeclaration=t.ClassExpression=t.FunctionDeclaration=t.ArrowFunctionExpression=t.FunctionExpression=function(){return m(y("Function"))},Object.defineProperty(t,"Identifier",{enumerable:!0,get:function(){return s.default}}),t.LogicalExpression=function(){const e=[this.get("left").getTypeAnnotation(),this.get("right").getTypeAnnotation()];return(0,i.createUnionType)(e)},t.NewExpression=function(e){if("Identifier"===e.callee.type)return m(e.callee)},t.NullLiteral=function(){return g()},t.NumericLiteral=function(){return b()},t.ObjectExpression=function(){return m(y("Object"))},t.ParenthesizedExpression=function(){return this.get("expression").getTypeAnnotation()},t.RegExpLiteral=function(){return m(y("RegExp"))},t.RestElement=C,t.SequenceExpression=function(){return this.get("expressions").pop().getTypeAnnotation()},t.StringLiteral=function(){return v()},t.TSAsExpression=A,t.TSNonNullExpression=function(){return this.get("expression").getTypeAnnotation()},t.TaggedTemplateExpression=function(){return _(this.get("tag"))},t.TemplateLiteral=function(){return v()},t.TypeCastExpression=P,t.UnaryExpression=function(e){const t=e.operator;return"void"===t?S():c.includes(t)?b():p.includes(t)?v():o.includes(t)?f():void 0},t.UpdateExpression=function(e){const t=e.operator;if("++"===t||"--"===t)return b()},t.VariableDeclarator=function(){if(this.get("id").isIdentifier())return this.get("init").getTypeAnnotation()};var n=r(2352),s=r(354),i=r(3141);const{BOOLEAN_BINARY_OPERATORS:a,BOOLEAN_UNARY_OPERATORS:o,NUMBER_BINARY_OPERATORS:l,NUMBER_UNARY_OPERATORS:c,STRING_UNARY_OPERATORS:p,anyTypeAnnotation:u,arrayTypeAnnotation:d,booleanTypeAnnotation:f,buildMatchMemberExpression:h,genericTypeAnnotation:m,identifier:y,nullLiteralTypeAnnotation:g,numberTypeAnnotation:b,stringTypeAnnotation:v,tupleTypeAnnotation:T,unionTypeAnnotation:x,voidTypeAnnotation:S,isIdentifier:E}=n;function P(e){return e.typeAnnotation}function A(e){return e.typeAnnotation}function w(){return m(y("Array"))}function C(){return w()}P.validParent=!0,A.validParent=!0,C.validParent=!0;const O=h("Array.from"),I=h("Object.keys"),N=h("Object.values"),k=h("Object.entries");function _(e){if((e=e.resolve()).isFunction()){const{node:t}=e;if(t.async)return t.generator?m(y("AsyncIterator")):m(y("Promise"));if(t.generator)return m(y("Iterator"));if(e.node.returnType)return e.node.returnType}}},9957:(e,t,r)=>{"use strict";var n=Function.prototype.call,s=Object.prototype.hasOwnProperty,i=r(6743);e.exports=i.call(n,s)},9971:()=>{},9990:(e,t,r)=>{"use strict";function n(){const e=r(3878);return n=function(){return e},e}Object.defineProperty(t,"__esModule",{value:!0}),t.createCachedDescriptors=function(e,t,r){const{plugins:n,presets:s,passPerPreset:i}=t;return{options:p(t,e),plugins:n?()=>h(n,e)(r):()=>c([]),presets:s?()=>d(s,e)(r)(!!i):()=>c([])}},t.createDescriptor=T,t.createUncachedDescriptors=function(e,t,r){return{options:p(t,e),plugins:(0,s.once)((()=>b(t.plugins||[],e,r))),presets:(0,s.once)((()=>g(t.presets||[],e,r,!!t.passPerPreset)))}};var s=r(8873),i=r(682),a=r(6140),o=r(1310),l=r(3917);function*c(e){return e}function p(e,t){return"string"==typeof e.browserslistConfigFile&&(e.browserslistConfigFile=(0,l.resolveBrowserslistConfigFile)(e.browserslistConfigFile,t)),e}const u=new WeakMap,d=(0,o.makeWeakCacheSync)(((e,t)=>{const r=t.using((e=>e));return(0,o.makeStrongCacheSync)((t=>(0,o.makeStrongCache)((function*(n){return(yield*g(e,r,t,n)).map((e=>y(u,e)))}))))})),f=new WeakMap,h=(0,o.makeWeakCacheSync)(((e,t)=>{const r=t.using((e=>e));return(0,o.makeStrongCache)((function*(t){return(yield*b(e,r,t)).map((e=>y(f,e)))}))})),m={};function y(e,t){const{value:r,options:n=m}=t;if(!1===n)return t;let s=e.get(r);s||(s=new WeakMap,e.set(r,s));let i=s.get(n);if(i||(i=[],s.set(n,i)),!i.includes(t)){const e=i.filter((e=>{return n=t,(r=e).name===n.name&&r.value===n.value&&r.options===n.options&&r.dirname===n.dirname&&r.alias===n.alias&&r.ownPass===n.ownPass&&(null==(s=r.file)?void 0:s.request)===(null==(i=n.file)?void 0:i.request)&&(null==(a=r.file)?void 0:a.resolved)===(null==(o=n.file)?void 0:o.resolved);var r,n,s,i,a,o}));if(e.length>0)return e[0];i.push(t)}return t}function*g(e,t,r,n){return yield*v("preset",e,t,r,n)}function*b(e,t,r){return yield*v("plugin",e,t,r)}function*v(e,t,r,s,i){const a=yield*n().all(t.map(((t,n)=>T(t,r,{type:e,alias:`${s}$${n}`,ownPass:!!i}))));return function(e){const t=new Map;for(const r of e){if("function"!=typeof r.value)continue;let n=t.get(r.value);if(n||(n=new Set,t.set(r.value,n)),n.has(r.name)){const t=e.filter((e=>e.value===r.value));throw new Error(["Duplicate plugin/preset detected.","If you'd like to use two separate instances of a plugin,","they need separate names, e.g.",""," plugins: ["," ['some-plugin', {}],"," ['some-plugin', {}, 'some unique name'],"," ]","","Duplicates detected are:",`${JSON.stringify(t,null,2)}`].join("\n"))}n.add(r.name)}}(a),a}function*T(e,t,{type:r,alias:n,ownPass:s}){const o=(0,a.getItemDescriptor)(e);if(o)return o;let l,c,p,u=e;Array.isArray(u)&&(3===u.length?[u,c,l]=u:[u,c]=u);let d=null;if("string"==typeof u){if("string"!=typeof r)throw new Error("To resolve a string-based item, the type of item must be given");const e="plugin"===r?i.loadPlugin:i.loadPreset,n=u;({filepath:d,value:u}=yield*e(u,t)),p={request:n,resolved:d}}if(!u)throw new Error(`Unexpected falsy value: ${String(u)}`);if("object"==typeof u&&u.__esModule){if(!u.default)throw new Error("Must export a default export when using ES6 modules.");u=u.default}if("object"!=typeof u&&"function"!=typeof u)throw new Error(`Unsupported format: ${typeof u}. Expected an object or a function.`);if(null!==d&&"object"==typeof u&&u)throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${d}`);return{name:l,alias:d||n,value:u,options:c,dirname:t,ownPass:s,file:p}}}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var n={};return(()=>{"use strict";r.d(n,{default:()=>T});var e=r(2172),t=r(2352),s={EES_JAVASCRIPT:"eesJavascript",EES_JSPL:"eesJSPL",PRIVATE_TAG:"@private",NAME_TAG:"@name",FUNCTION_TAG:"@function",FUNC_TAG:"@func",MEMBEROF_TAG:"@memberof",PARAM_TAG:"@param",ARG_TAG:"@arg",ARGUMENT_TAG:"@argument",RETURN_TAG:"@return",RETURNS_TAG:"@returns",THIS_TAG:"@this",THIS_REFERENCE:"thisReference",ERROR_HANDLER_TAG:"@errorHandler",ARGS:"args",TYPE:"type",NAME:"name",DESC:"description",ID:"id",DISPLAY_NAME:"displayName",IMPL:"impl",STRING_TYPE:"STRING",STRING_ARRAY_TYPE:"STRING[]",NUMBER_TYPE:"NUMBER",NUMBER_ARRAY_TYPE:"NUMBER[]",BOOLEAN_TYPE:"BOOLEAN",BOOLEAN_ARRAY_TYPE:"BOOLEAN[]",DATE_TYPE:"DATE",DATE_ARRAY_TYPE:"DATE[]",V2_ARRAY_TYPE:"ARRAY",ARRAY_TYPE:"OPTIONS",OBJECT_TYPE:"OBJECT",PANEL_TYPE:"PANEL",SCOPE_TYPE:"SCOPE",PROMISE_TYPE:"PROMISE",IS_ERROR_HANDLER:"isErrorHandler",IS_MANDATORY:"isMandatory",DEFAULT_TYPE:["STRING","NUMBER","BOOLEAN","DATE","OPTIONS"].join("|"),V2_DEFAULT_TYPE:["STRING","NUMBER","BOOLEAN","DATE","ARRAY","OBJECT"].join("|"),FUNCTION_TYPE_VARIABLE:5,OBJECT_TYPE_VARIABLE:6},i=r(6416);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function o(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,o=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){o=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(o)throw i}}}}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function c(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,u(n.key),n)}}function p(e,t,r){return(t=u(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e){var t=function(e){if("object"!=a(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=a(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==a(t)?t:t+""}var d=function(){function r(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,r),p(this,"patternPrivate",new RegExp("".concat(s.PRIVATE_TAG,"[\\s]*[\\n]*"))),p(this,"patternName",new RegExp("(?:".concat(s.NAME_TAG,"|").concat(s.FUNC_TAG,"|").concat(s.FUNCTION_TAG,")\\s+([^\\n]+)"),"s")),p(this,"patternParam",new RegExp("(?:".concat(s.PARAM_TAG,"|").concat(s.ARGUMENT_TAG,"|").concat(s.ARG_TAG,")[\\s]+"),"g")),p(this,"patternReturn",new RegExp("(?:".concat(s.RETURN_TAG,"|").concat(s.RETURNS_TAG,")[\\s]+"))),p(this,"patternThis",new RegExp("(?:".concat(s.THIS_TAG,")[\\s]+"))),p(this,"patternErrorHandler",new RegExp("(?:".concat(s.ERROR_HANDLER_TAG,")[\\s]+"))),p(this,"patternType",/(?:\{([^}]+)?\})?(\\s+[^\\s]+)?(\\s+.*)?/),p(this,"paramPatternTypeNew",/(?:(\{([^}]+)(?:=(\[.*?\]|[^}]*))?\})\s*)?(\[?([^\s\]]+)(?:=([^}\s]*))?\]?)(\s*.*)?$/),p(this,"patternDesc",/^\s*\*+\s*([\s\S]*?)(?=\s*\*+\s*@|$)/),this.typesMap=new Map,this.initializeTypesMap()}return n=r,l=[{key:"getInstance",value:function(){return r.instance||(r.instance=new r),r.instance}}],(a=[{key:"initializeTypesMap",value:function(){this.typesMap.set("string",s.STRING_TYPE),this.typesMap.set("number",s.NUMBER_TYPE),this.typesMap.set("boolean",s.BOOLEAN_TYPE),this.typesMap.set("date",s.DATE_TYPE),this.typesMap.set("scope",s.SCOPE_TYPE),this.typesMap.set("promise",s.PROMISE_TYPE),this.typesMap.set("options",s.V2_ARRAY_TYPE),this.typesMap.set("array",s.V2_ARRAY_TYPE),this.typesMap.set("object",s.OBJECT_TYPE),this.typesMap.set("string[]",s.STRING_ARRAY_TYPE),this.typesMap.set("number[]",s.NUMBER_ARRAY_TYPE),this.typesMap.set("boolean[]",s.BOOLEAN_ARRAY_TYPE),this.typesMap.set("date[]",s.DATE_ARRAY_TYPE)}},{key:"parse",value:function(t){var r=this,n=(0,e.parse)(t,{sourceType:"unambiguous"}),s=[];return(0,i.traverse)(n,{FunctionDeclaration:function(e){return r.handleFunctionDeclaration(e,s)},VariableDeclarator:function(e){return r.handleVariableDeclarator(e,s)},AssignmentExpression:function(e){return r.handleAssignmentExpression(e,s)}}),{customFunction:s}}},{key:"extractStaticImports",value:function(t){try{var r=(0,e.parse)(t,{sourceType:"unambiguous",plugins:["importAssertions"]}),n=[];return(0,i.traverse)(r,{ImportDeclaration:function(e){var t=e.node.source.value;if("string"==typeof t){var r=t.startsWith("./")||t.startsWith("../")||t.startsWith("/"),s=!(t.endsWith(".json")||t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".less")||t.endsWith(".svg")||t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif"));!t.includes("node_modules")&&t.match(/^[@a-zA-Z]/),r&&s&&n.push(t)}}}),n}catch(e){return console.error("Error extracting static imports:",e),[]}}},{key:"handleFunctionDeclaration",value:function(e,t){if(this.isTopLevelFunction(e)&&this.hasIdentifierName(e.node.id)){var r=this.getJsDocComment(e.node),n=this.parseFunction(e.node,e.node.id.name,r);n&&t.push(n)}}},{key:"handleVariableDeclarator",value:function(e,t){if(this.isTopLevelVariable(e)&&e.node.init&&this.isFunctionExpression(e.node.init)&&this.hasIdentifierName(e.node.id)){var r=e.get("init").node,n=this.getJsDocComment(e.parentPath.node),s=this.parseFunction(r,e.node.id.name,n);s&&t.push(s)}}},{key:"handleAssignmentExpression",value:function(e,t){if(this.isTopLevelAssignment(e)&&this.isFunctionExpression(e.node.right)&&this.hasIdentifierName(e.node.left)){var r=e.get("right").node,n=this.getJsDocComment(e.parentPath.node),s=this.parseFunction(r,e.node.left.name,n);s&&t.push(s)}}},{key:"hasIdentifierName",value:function(e){return!!e&&t.isIdentifier(e)&&!!e.name}},{key:"isTopLevelFunction",value:function(e){var t;return"Program"===e.parent.type&&void 0!==(null===(t=e.node.id)||void 0===t?void 0:t.name)}},{key:"isTopLevelVariable",value:function(e){return"Program"===e.parentPath.parent.type&&t.isIdentifier(e.node.id)&&void 0!==e.node.id.name}},{key:"isTopLevelAssignment",value:function(e){return"Program"===e.parentPath.parent.type&&t.isIdentifier(e.node.left)&&void 0!==e.node.left.name}},{key:"isFunctionExpression",value:function(e){return"FunctionExpression"===(null==e?void 0:e.type)||"ArrowFunctionExpression"===(null==e?void 0:e.type)}},{key:"getJsDocComment",value:function(e){var t;return null===(t=e.leadingComments)||void 0===t||null===(t=t.slice().reverse().find((function(e){return"CommentBlock"===e.type&&e.value.startsWith("*")})))||void 0===t?void 0:t.value.trim()}},{key:"parseFunction",value:function(e,r,n){var i=this;this.functionNode=e;var a=!!e.async,o=!!e.generator,l=!!n&&this.patternPrivate.test(n);if(!(a||o||l)){var c=r,p=r,u=this.getReturnType(),d={id:c,displayName:p,args:e.params.map((function(e){if("AssignmentPattern"===e.type){if(t.isIdentifier(e.left))return{name:e.left.name,description:e.left.name,type:i.getDefaultParamType(),isMandatory:!1};throw new Error("".concat(e.left.type," is not allowed in AssignmentPattern for param. Only Identifier is allowed"))}if("Identifier"===e.type)return{name:e.name,description:e.name,type:i.getDefaultParamType(),isMandatory:!0};throw new Error("".concat(e.type," is not allowed. Only Identifier or AssignmentPattern is allowed for param"))})),type:u,description:"",impl:""};return n&&this.parseJSDoc(d,n),this.parseImpl(d),d.hasOwnProperty(s.THIS_REFERENCE)&&delete d.thisReference,d}}},{key:"parseJSDoc",value:function(e,t){t&&(this.parseName(e,t),this.parseParams(e,t),this.parseReturn(e,t),this.parseDesc(e,t),this.parseErrorHandlerTag(e,t),this.parseThisTag(e,t),this.parseMemberOf(e,t))}},{key:"parseName",value:function(e,t){var r=t.split("\n").map((function(e){return e.replace(/^\s*\*+\s*/,"").trim()})).join("\n"),n=this.patternName.exec(r);if(n){var s=n[1].split(/\s+/),i=s[0],a=s.slice(1).join(" ")||i;e.id=i,e.displayName=a.trim()?a.trim():i}}},{key:"parseParams",value:function(e,t){var r=this.functionNode.params.length;if(r>0){var n,s=0;for(this.patternParam.lastIndex=0;null!==(n=this.patternParam.exec(t));){var i=t.indexOf(" ",n.index),a=t.indexOf("\n",i),o=t.substring(i,a>-1?a:t.length);this.parseParamWithOptional(e,o.trim(),s)&&s++}s<r&&this.getParamNames(e)}}},{key:"parseParamWithOptional",value:function(e,t,r){t=t.trim();var n=e.args||[],s={},i=this.paramPatternTypeNew.exec(t),a=r,o=!0;if(i){var l,c,p=null===(l=i[2])||void 0===l?void 0:l.trim();if(p&&"*"!==p){if(p.includes("=")){var u=p.split("=");p=u[0],o=!1}s.type=this.getParamType(p)}else s.type=this.getDefaultParamType();var d=null===(c=i[5])||void 0===c?void 0:c.trim();if(d){var f,h;if(null!==(f=i[4])&&void 0!==f&&f.startsWith("[")&&(o=!1),d.includes("=")){var m=d.split("=");d=m[0]}a=this.findIndex(d),s.name=d;var y=null===(h=i[7])||void 0===h?void 0:h.trim();if(y&&y.includes("-")){var g=y.indexOf("-");y=y.substring(g+1).trim()}s.description=y||d}}if(-1!==a){s.isMandatory=o;for(var b={type:"",name:"",description:"",isMandatory:!0};a>=n.length;)n.push(b);n[a]=s}return-1!==a}},{key:"getParamNames",value:function(e){for(var t=e.args||[],r=0;r<t.length;r++)t[r]&&0!==Object.keys(t[r]).length||this.parseParamWithOptional(e,"{*} "+t[r],r)}},{key:"getParamType",value:function(e){var t,r,n=o(e.toLowerCase().split("|"));try{for(n.s();!(r=n.n()).done;){var i=r.value;this.typesMap.has(i)&&(t=t?[t,this.typesMap.get(i)].join("|"):this.typesMap.get(i)||"",s.OBJECT_TYPE.toLowerCase()===i&&(t+="|AFCOMPONENT"))}}catch(e){n.e(e)}finally{n.f()}return t||(t=this.getDefaultParamType()),t}},{key:"getDefaultParamType",value:function(){return s.V2_DEFAULT_TYPE}},{key:"findIndex",value:function(e){for(var r=this.functionNode.params,n=0;n<r.length;n++){var s=r[n];if(!("Identifier"===s.type||"AssignmentPattern"===s.type&&t.isIdentifier(s.left)))throw new Error("".concat(s.type," is not allowed. Only Identifier or AssignmentPattern is allowed for param"));if("Identifier"===s.type&&s.name===e||"AssignmentPattern"===s.type&&t.isIdentifier(s.left)&&s.left.name===e)return n}return-1}},{key:"parseReturn",value:function(e,t){var r=this.patternReturn.exec(t);if(r){var n=t.indexOf(" ",r.index),s=t.indexOf("\n",n),i=t.substring(n,s>-1?s:t.length);this.parseReturnHelper(e,i.trim())}else this.parseReturnHelper(e,"{*}")}},{key:"parseReturnHelper",value:function(e,t){t=t.trim();var r=s.V2_DEFAULT_TYPE,n=this.patternType.exec(t);n&&(r=this.getReturnType(n[1],t),s.OBJECT_TYPE.toLowerCase()!==r&&s.V2_ARRAY_TYPE!==r||(r+="|PANEL")),e.type=r}},{key:"getReturnType",value:function(e,t){var r;if(e&&"*"!==e){var n,i=o(e.toLowerCase().split("|"));try{for(i.s();!(n=i.n()).done;){var a=n.value;if(this.typesMap.has(a))r=r?[r,this.typesMap.get(a)].join("|"):this.typesMap.get(a)||"";else if(t){for(var l=t.indexOf("{")+1,c=[],p=1;l<t.length&&p>0;l++){var u=t.charAt(l);"}"===u&&(p-=1),"{"===u&&(p+=1),p>0&&c.push(u)}r=r?[r,c.join("").toUpperCase()].join("|"):c.join("").toUpperCase()}}}catch(e){i.e(e)}finally{i.f()}}return r||(r=s.V2_DEFAULT_TYPE),r}},{key:"parseDesc",value:function(e,t){var r=this.patternDesc.exec(t);r&&(e.description=r[1].trim().split("\n").map((function(e){return e.replace(/^\s*\*+\s*/,"").trim()})).filter((function(e){return e.length>0})).join(" "))}},{key:"parseErrorHandlerTag",value:function(e,t){this.patternErrorHandler.exec(t)&&(e.isErrorHandler=!0)}},{key:"parseThisTag",value:function(e,t){var r=this.patternThis.exec(t);if(r){var n=t.indexOf("\n",r.index);if(n>-1){var i=t.substring(r.index+s.THIS_TAG.length,n);e.thisReference=i.trim()}}}},{key:"parseImpl",value:function(e){var t=this.functionNode.params.length,r=[],n=e.args||[],i=this.needsFieldContext(e);r.push(i?"$0.apply(this, [":"$0(");for(var a=t,o=0;o<a;o++){var l=n[o],c=l.type;l.name,c===s.SCOPE_TYPE?o+1===a?(n.splice(o,1),a--,o--,","===r[r.length-1]&&r.pop()):(l.type=this.getDefaultParamType(),r.push("$".concat(o+1))):r.push("$".concat(o+1)),o!==a-1&&r.push(",")}r.push(i?"])":")"),e.impl=r.join("")}},{key:"needsFieldContext",value:function(e){var t;return"currentcomponent"===(null==e||null===(t=e.thisReference)||void 0===t?void 0:t.toLowerCase())}},{key:"parseMemberOf",value:function(e,t){var r=t.indexOf(s.MEMBEROF_TAG);if(-1!==r){var n=r+s.MEMBEROF_TAG.length,i=t.indexOf("\n",n),a=t.substring(n,-1===i?void 0:i).trim();if(a){var o=e.id||"";e.id="".concat(a,".").concat(o)}}}}])&&c(n.prototype,a),l&&c(n,l),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,a,l}();function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}function h(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return m(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?m(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,o=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){o=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(o)throw i}}}}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function y(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,b(n.key),n)}}function g(e,t,r){return(t=b(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function b(e){var t=function(e){if("object"!=f(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=f(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==f(t)?t:t+""}var v=function(){function r(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,r),g(this,"patternPrivate",new RegExp("".concat(s.PRIVATE_TAG,"[\\s]*[\\n]*"))),g(this,"patternName",new RegExp("(?:".concat(s.NAME_TAG,"|").concat(s.FUNC_TAG,"|").concat(s.FUNCTION_TAG,")\\s+([^\\n]+)"),"s")),g(this,"patternParam",new RegExp("(?:".concat(s.PARAM_TAG,"|").concat(s.ARGUMENT_TAG,"|").concat(s.ARG_TAG,")[\\s]+"),"g")),g(this,"patternReturn",new RegExp("(?:".concat(s.RETURN_TAG,"|").concat(s.RETURNS_TAG,")[\\s]+"))),g(this,"patternThis",new RegExp("(?:".concat(s.THIS_TAG,")[\\s]+"))),g(this,"patternErrorHandler",new RegExp("(?:".concat(s.ERROR_HANDLER_TAG,")[\\s]+"))),g(this,"patternType",/(?:\{([^}]+)?\})?(\\s+[^\\s]+)?(\\s+.*)?/),g(this,"paramPatternTypeNew",/(?:(\{([^}]+)(?:=(\[.*?\]|[^}]*))?\})\s*)?(\[?([^\s\]]+)(?:=([^}\s]*))?\]?)(\s*.*)?$/),g(this,"patternDesc",/^\s*\*+\s*([\s\S]*?)(?=\s*\*+\s*@|$)/),this.typesMap=new Map,this.initializeTypesMap()}return n=r,o=[{key:"getInstance",value:function(){return r.instance||(r.instance=new r),r.instance}}],(a=[{key:"initializeTypesMap",value:function(){this.typesMap.set("string",s.STRING_TYPE),this.typesMap.set("number",s.NUMBER_TYPE),this.typesMap.set("boolean",s.BOOLEAN_TYPE),this.typesMap.set("date",s.DATE_TYPE),this.typesMap.set("scope",s.SCOPE_TYPE),this.typesMap.set("options",s.ARRAY_TYPE),this.typesMap.set("array",s.ARRAY_TYPE)}},{key:"parse",value:function(t){var r=this,n=(0,e.parse)(t,{sourceType:"unambiguous"}),s=[];return(0,i.traverse)(n,{FunctionDeclaration:function(e){return r.handleFunctionDeclaration(e,s)},VariableDeclarator:function(e){return r.handleVariableDeclarator(e,s)},AssignmentExpression:function(e){return r.handleAssignmentExpression(e,s)}}),{customFunction:s}}},{key:"extractStaticImports",value:function(t){try{var r=(0,e.parse)(t,{sourceType:"unambiguous",plugins:["importAssertions"]}),n=[];return(0,i.traverse)(r,{ImportDeclaration:function(e){var t=e.node.source.value;if("string"==typeof t){var r=t.startsWith("./")||t.startsWith("../")||t.startsWith("/"),s=!(t.endsWith(".json")||t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".less")||t.endsWith(".svg")||t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif"));r&&s&&n.push(t)}}}),n}catch(e){return console.error("Error extracting static imports:",e),[]}}},{key:"handleFunctionDeclaration",value:function(e,t){if(this.isTopLevelFunction(e)&&this.hasIdentifierName(e.node.id)){var r=this.getJsDocComment(e.node),n=this.parseFunction(e.node,e.node.id.name,r);n&&t.push(n)}}},{key:"handleVariableDeclarator",value:function(e,t){if(this.isTopLevelVariable(e)&&e.node.init&&this.isFunctionExpression(e.node.init)&&this.hasIdentifierName(e.node.id)){var r=e.get("init").node,n=this.getJsDocComment(e.parentPath.node),s=this.parseFunction(r,e.node.id.name,n);s&&t.push(s)}}},{key:"handleAssignmentExpression",value:function(e,r){if(this.isTopLevelAssignment(e)&&this.isFunctionExpression(e.node.right)){var n,s=e.get("right").node,i=this.getJsDocComment(e.parentPath.node);if(t.isIdentifier(e.node.left)?n=e.node.left.name:t.isMemberExpression(e.node.left)&&t.isIdentifier(e.node.left.property)&&(n=e.node.left.property.name),n){var a=this.parseFunction(s,n,i);a&&r.push(a)}}}},{key:"hasIdentifierName",value:function(e){return!!e&&t.isIdentifier(e)&&!!e.name}},{key:"isTopLevelFunction",value:function(e){var t;return"Program"===e.parent.type&&void 0!==(null===(t=e.node.id)||void 0===t?void 0:t.name)}},{key:"isTopLevelVariable",value:function(e){return"Program"===e.parentPath.parent.type&&t.isIdentifier(e.node.id)&&void 0!==e.node.id.name}},{key:"isTopLevelAssignment",value:function(e){return!("Program"!==e.parentPath.parent.type||!(t.isIdentifier(e.node.left)&&void 0!==e.node.left.name||t.isMemberExpression(e.node.left)&&t.isIdentifier(e.node.left.property)))}},{key:"isFunctionExpression",value:function(e){return"FunctionExpression"===(null==e?void 0:e.type)||"ArrowFunctionExpression"===(null==e?void 0:e.type)}},{key:"getJsDocComment",value:function(e){var t;return null===(t=e.leadingComments)||void 0===t||null===(t=t.slice().reverse().find((function(e){return"CommentBlock"===e.type&&e.value.startsWith("*")})))||void 0===t?void 0:t.value.trim()}},{key:"parseFunction",value:function(e,r,n){var i=this;this.functionNode=e;var a=!!e.async,o=!!e.generator,l=!!n&&this.patternPrivate.test(n);if(!(a||o||l)){var c=r,p=r,u=this.getReturnType(),d={id:c,displayName:p,args:e.params.map((function(e){if("AssignmentPattern"===e.type){if(t.isIdentifier(e.left))return{name:e.left.name,description:e.left.name,type:i.getDefaultParamType(),isMandatory:!1};throw new Error("".concat(e.left.type," is not allowed in AssignmentPattern for param. Only Identifier is allowed"))}if("Identifier"===e.type)return{name:e.name,description:e.name,type:i.getDefaultParamType(),isMandatory:!0};throw new Error("".concat(e.type," is not allowed. Only Identifier or AssignmentPattern is allowed for param"))})),type:u,description:"",impl:""};return n&&this.parseJSDoc(d,n),this.parseImpl(d),d.hasOwnProperty(s.THIS_REFERENCE)&&delete d.thisReference,d}}},{key:"parseJSDoc",value:function(e,t){t&&(this.parseName(e,t),this.parseParams(e,t),this.parseReturn(e,t),this.parseDesc(e,t),this.parseErrorHandlerTag(e,t),this.parseThisTag(e,t),this.parseMemberOf(e,t))}},{key:"parseName",value:function(e,t){var r=t.split("\n").map((function(e){return e.replace(/^\s*\*+\s*/,"").trim()})).join("\n"),n=this.patternName.exec(r);if(n){var s=n[1].split(/\s+/),i=s[0],a=s.slice(1).join(" ")||i;e.id=i,e.displayName=a.trim()?a.trim():i}}},{key:"parseParams",value:function(e,t){var r=this.functionNode.params.length;if(r>0){var n,s=0;for(this.patternParam.lastIndex=0;null!==(n=this.patternParam.exec(t));){var i=t.indexOf(" ",n.index),a=t.indexOf("\n",i),o=t.substring(i,a>-1?a:t.length);this.parseParamWithOptional(e,o.trim(),s)&&s++}s<r&&this.getParamNames(e)}}},{key:"parseParamWithOptional",value:function(e,t,r){t=t.trim();var n=e.args||[],s={},i=this.paramPatternTypeNew.exec(t),a=r,o=!0;if(i){var l,c,p=null===(l=i[2])||void 0===l?void 0:l.trim();if(p&&"*"!==p){if(p.includes("=")){var u=p.split("=");p=u[0],o=!1}s.type=this.getParamType(p)}else s.type=this.getDefaultParamType();var d=null===(c=i[5])||void 0===c?void 0:c.trim();if(d){var f,h;if(null!==(f=i[4])&&void 0!==f&&f.startsWith("[")&&(o=!1),d.includes("=")){var m=d.split("=");d=m[0]}a=this.findIndex(d),s.name=d;var y=null===(h=i[7])||void 0===h?void 0:h.trim();if(y&&y.includes("-")){var g=y.indexOf("-");y=y.substring(g+1).trim()}s.description=y||d}}if(-1!==a){s.isMandatory=o;for(var b={type:"",name:"",description:"",isMandatory:!0};a>=n.length;)n.push(b);n[a]=s}return-1!==a}},{key:"getParamNames",value:function(e){for(var t=e.args||[],r=0;r<t.length;r++)t[r]&&0!==Object.keys(t[r]).length||this.parseParamWithOptional(e,"{*} "+t[r],r)}},{key:"getParamType",value:function(e){var t,r,n=h(e.toLowerCase().split("|"));try{for(n.s();!(r=n.n()).done;){var s=r.value;this.typesMap.has(s)&&(t=t?[t,this.typesMap.get(s)].join("|"):this.typesMap.get(s)||"")}}catch(e){n.e(e)}finally{n.f()}return t||(t=this.getDefaultParamType()),t}},{key:"getDefaultParamType",value:function(){return s.DEFAULT_TYPE}},{key:"findIndex",value:function(e){for(var r=this.functionNode.params,n=0;n<r.length;n++){var s=r[n];if(!("Identifier"===s.type||"AssignmentPattern"===s.type&&t.isIdentifier(s.left)))throw new Error("".concat(s.type," is not allowed. Only Identifier or AssignmentPattern is allowed for param"));if("Identifier"===s.type&&s.name===e||"AssignmentPattern"===s.type&&t.isIdentifier(s.left)&&s.left.name===e)return n}return-1}},{key:"parseReturn",value:function(e,t){var r=this.patternReturn.exec(t);if(r){var n=t.indexOf(" ",r.index),s=t.indexOf("\n",n),i=t.substring(n,s>-1?s:t.length);this.parseReturnHelper(e,i.trim())}else this.parseReturnHelper(e,"{*}")}},{key:"parseReturnHelper",value:function(e,t){t=t.trim();var r=s.DEFAULT_TYPE,n=this.patternType.exec(t);n&&(r=this.getReturnType(n[1],t)),e.type=r}},{key:"getReturnType",value:function(e,t){var r;if(e&&"*"!==e){var n,i=h(e.toLowerCase().split("|"));try{for(i.s();!(n=i.n()).done;){var a=n.value;this.typesMap.has(a)&&(r=r?[r,this.typesMap.get(a)].join("|"):this.typesMap.get(a)||"")}}catch(e){i.e(e)}finally{i.f()}}return r||(r=s.DEFAULT_TYPE),r}},{key:"parseDesc",value:function(e,t){var r=this.patternDesc.exec(t);r&&(e.description=r[1].trim().split("\n").map((function(e){return e.replace(/^\s*\*+\s*/,"").trim()})).filter((function(e){return e.length>0})).join(" "))}},{key:"parseErrorHandlerTag",value:function(e,t){this.patternErrorHandler.exec(t)&&(e.isErrorHandler=!0)}},{key:"parseThisTag",value:function(e,t){var r=this.patternThis.exec(t);if(r){var n=t.indexOf("\n",r.index);if(n>-1){var i=t.substring(r.index+s.THIS_TAG.length,n);e.thisReference=i.trim()}}}},{key:"parseImpl",value:function(e){var t=this.functionNode.params.length,r=[],n=e.args||[],i=this.needsFieldContext(e);r.push(i?"$0.apply(this, [":"$0(");for(var a=t,o=0;o<a;o++)n[o].type===s.SCOPE_TYPE?(r.push("guidelib.model.util.CommonUtils._getScope(this)"),n.splice(o,1),a--,o--):r.push("$".concat(o+1)),o!==a-1&&r.push(",");r.push(i?"])":")"),e.impl=r.join("")}},{key:"needsFieldContext",value:function(e){var t;return"currentcomponent"===(null==e||null===(t=e.thisReference)||void 0===t?void 0:t.toLowerCase())}},{key:"parseMemberOf",value:function(e,t){var r=t.indexOf(s.MEMBEROF_TAG);if(-1!==r){var n=r+s.MEMBEROF_TAG.length,i=t.indexOf("\n",n),a=t.substring(n,-1===i?void 0:i).trim();if(a){var o=e.id||"";e.id="".concat(a,".").concat(o)}}}}])&&y(n.prototype,a),o&&y(n,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,a,o}();const T=d.getInstance();v.getInstance()})(),n.default})())); -//# sourceMappingURL=custom-function-parser.js.map \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/AFJSONFormulaMerger.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/AFJSONFormulaMerger.js deleted file mode 100644 index cdd5081c..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/AFJSONFormulaMerger.js +++ /dev/null @@ -1,65 +0,0 @@ -/************************************************************************* - * ADOBE CONFIDENTIAL - * ___________________ - * - * Copyright 2022 Adobe Systems Incorporated - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Adobe Systems Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Adobe Systems Incorporated and its - * suppliers and are protected by all applicable intellectual property - * laws, including trade secret and copyright laws. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Adobe Systems Incorporated. - **************************************************************************/ -(function (_) { - var RuntimeUtil = guidelib.RuntimeUtil; - - /** - * Events that require variableAssignment and Merge with || operator - * @type {string[]} - */ - var events = ["Value Commit", "Click", "Initialize"] - - var afScriptMerger = guidelib.author.AFJSONFormulaMerger = { - /** - * Each element Script Array is of the type - * { - * field : <field_name> - * event : <event> - * modelName : <modelName> - * content : <script_content> - * } - * @param scriptArray - */ - mergeScript : function (scriptArray) { - var fields = {}; - scriptArray.forEach(function (script) { - var field = script.field, - eventName = script.event; - var isEvent = events.indexOf(eventName) > -1 || (eventName && eventName.startsWith("custom:")); - fields[field] = fields[field] || {}; - fields[field][eventName] = fields[field][eventName] || - { - content : (isEvent ? [] : "") - }; - var currentContent = fields[field][eventName].content - if (isEvent) { - if ("Value Commit" === eventName) { - script.content = script.content.map(function(scriptLine) { - return "if(contains($event.payload.changes[].propertyName, 'value'), "+scriptLine+", {})"; - }); - } - fields[field][eventName].content = currentContent.concat(script.content) - } else { - fields[field][eventName].content = currentContent ? - currentContent + " || " + script.content : script.content - } - }, this); - return fields; - } - }; -}(fd._)); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/AFJSONFormulaTransformer.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/AFJSONFormulaTransformer.js deleted file mode 100644 index f6dcb08e..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/AFJSONFormulaTransformer.js +++ /dev/null @@ -1,1720 +0,0 @@ -/************************************************************************* - * ADOBE CONFIDENTIAL - * ___________________ - * - * Copyright 2022 Adobe Systems Incorporated - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Adobe Systems Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Adobe Systems Incorporated and its - * suppliers and are protected by all applicable intellectual property - * laws, including trade secret and copyright laws. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Adobe Systems Incorporated. - **************************************************************************/ -(function ($, _) { - var RuntimeUtil = guidelib.RuntimeUtil, - RETRY_REQUEST_HANDLER_FT = 'FT_FORMS-19810'; - customTransformer = guidelib.author.AFJSONFormulaTransformer = expeditor.rb.ToJsonFormulaTransformer.extend({ - reset : function () { - this.script = ""; - this.currentEvent = { - name : null, - field : null, - model : null, - otherEvents: null - }; - this.blockStatements = {} - this.stringConcatenation = false; - }, - - setEvent(event) { - this.currentEvent = event; - }, - - writeTab : function () { - this.write(RuntimeUtil.SCRIPT_INDENT); - }, - - _getRelativeName : function (fieldToCheck, currentField) { - var relativeName; - - if (fieldToCheck === currentField) { - return '$field' - } else { - var parentOfField = fieldToCheck.split(".").slice(0, -1).join(".") - if (parentOfField.startsWith(currentField)) { - // current field is a parent/ancestor of the field, it will be in the context - // todo: check for sibling having same name as child - relativeName = fieldToCheck.substring(currentField.length + 1); - } else { - var parentOfCurrentField = currentField.split(".").slice(0, -1).join("."); - if (parentOfCurrentField === parentOfField) { - relativeName = fieldToCheck.split(".").slice(-1)[0]; - } else { - relativeName = fieldToCheck; //.replace(/^guide/, "$form") - } - } - } - - return relativeName; - }, - - enterSTATEMENT : function (model) { - this.currentEvent.model = { - nodeName : model.choiceModel.nodeName - }; - }, - - exitSTATEMENT : function (model) { - - }, - - enterSCRIPTMODEL : function (model) { - this.reset(); - this.newScript(); - if (model.script) { - this.currentEvent.field = model.script.field; - this.currentEvent.name = model.script.event; - this.currentEvent.model = { - nodeName : model.nodeName, - version : model.version - }; - this.script = model.script.content; - } - }, - - enterEVENT_SCRIPTS : function (model) { - var condition = model.items[0]; - var conditionEvent = RuntimeUtil.getEventFromCondition(condition) || RuntimeUtil.DEFAULT_EVENT; - var field = RuntimeUtil.setCurrentEventField(condition); - if (field) { - this.currentEvent.field = field; - } - this.currentEvent.name = RuntimeUtil.eventToEventName[conditionEvent]; - if (!RuntimeUtil.isConditionOnlyAnEvent(condition)) { - this.currentEvent.hasCondition = true; - condition.accept(this) - this.currentEvent.condition = this.script; - model.items[2].accept(this) - - if (model.items.length > 4) { - var previousIfConditionStatement = this.script; - this.currentEvent.condition = '!('+this.currentEvent.condition+')'; - model.items[4].accept(this); - - const mergedScript = []; - for (var i = 0; i < previousIfConditionStatement.length; i++) { - mergedScript.push(previousIfConditionStatement[i]); - } - for (var i = 0; i < this.script.length; i++) { - mergedScript.push(this.script[i]); - } - this.script = mergedScript; - } - return true; - } else { - this.currentEvent.hasCondition = false; - } - }, - enterEVENT_AND_COMPARISON : function (model) { - if (!this.currentEvent.field) { - var field; - if (Granite.Toggles.isEnabled('FT_FORMS-19582') && model.items[0].nodeName === "EVENT_AND_COMPARISON_LEFT_HAND_EXPRESSION") { - field = model.items[0].choiceModel.getValue().id; - } else { - field = model.items[0].getValue().id; - } - this.currentEvent.field = field; - } - if (this.currentEvent.hasCondition) { - return this.enterCOMPARISON_EXPRESSION(model); - } - return false; - }, - - enterBINARY_EVENT_CONDITION : function (model) { - this.write("("); - }, - - exitBINARY_EVENT_CONDITION : function (model) { - this.write(")"); - }, - - /** - * Returns the transformed script(s) having the following signature - * { - * field : <field name>, - * event : <event name>, - * content : <transformed script content> - * } - * @returns {{field: null, event: null, model: null, content: string}} - */ - getScript : function () { - return { - field : this.currentEvent.field, - event : this.currentEvent.name, - model : this.currentEvent.model, - content : this.script, - otherEvents : this.currentEvent.otherEvents - }; - }, - - _findEventFromEventName : function(eventName) { - for (var key in RuntimeUtil.eventToEventName) { - if (RuntimeUtil.eventToEventName[key] === eventName) { - return key; - } - } - if (eventName && eventName.startsWith('custom:')) { - return eventName; - } - return null; - }, - - enterCOMPONENT : function (model) { - var val = model.getValue(); - var addValueOperator = true; - if (val) { - var fieldName, - fieldId = val.id; - var metadata = val.metadata; - if (!_.isUndefined(metadata) && metadata.source === "fdm") { - var bindRef = "/" + fieldId.replace(/\./g, '/'); - if (!_.isNull(RuntimeUtil.bindRefToAFNameMap)) { - fieldName = RuntimeUtil.bindRefToAFNameMap[bindRef]; - } - //If FDM field is AF bound - if (!_.isUndefined(fieldName)) { - var shortName = this._getRelativeName(fieldName, this.currentEvent.field); - this.write(shortName); - } else { - this.write("guidelib.util.GuideUtil.getValueForBindRefField(\"" + bindRef + "\")"); - } - } else { - var shortName = this._getRelativeName(fieldId, this.currentEvent.field); - // As click and initialize events are allowed in binary condition, so set first condition to true - var eventName = this.currentEvent.name; - if ((Granite.Toggles.isEnabled('FT_FORMS-17090') || Granite.Toggles.isEnabled('FT_FORMS-21266')) && eventName !== 'Value Commit' && this._findEventFromEventName(eventName) && this.currentEvent.field === fieldId && val.metadata && val.metadata.isFirstField) { - this.write("true()"); - // In case of click and initialize, for first field true() will be added and $value should be avoided - addValueOperator = false; - } else { - this.write(shortName); - } - if (expeditor.Utils.isPrimitive(val.type) && addValueOperator) { - this.write(".$value"); - } - } - } - }, - - enterVALUE_FIELD : function (model) { - var val = this._getComponentName(model); - if (val != null) { - this.write(val); - } - }, - - _getComponentName : function (model) { - var val = model.getValue(); - if (val) { - return this._getRelativeName(val.id, this.currentEvent.field); - } - return null; - }, - - enterAFCOMPONENT : function (model) { - var val = this._getComponentName(model); - if (val != null) { - this.write(val); - } - }, - - enterPANEL : function (model) { - var val = this._getComponentName(model); - if (val != null) { - this.write(val); - } - }, - - enterTOOLBAR_BUTTON : function (model) { - var val = model.getValue(); - if (val) { - var shortName = this._getRelativeName(val.id, this.currentEvent.field); - this.write(shortName); - } - }, - - enterEVENT : function (model) { - var event = model.choiceModel.nodeName; - if (event === "is clicked") { - this.currentEvent.name = "Click"; - } else { - this.currentEvent.name = "Initialize"; - } - }, - - _exitBlockStatementsTransformer : function (model) { - var _self = this; - function withCondition(str) { - var result; - if (_self.currentEvent.condition) { - if(typeof str === 'string') { - result = "if(" + _self.currentEvent.condition + ", " + str + ", {})"; - } else { - result = str.map(function (statement) { - return "if(" + _self.currentEvent.condition + ", " + statement + ", {})"; - }); - } - } else { - result = str; - } - return typeof result === 'string' ? [result] : result; - } - - if (Granite.Toggles.isEnabled("FT_FORMS-21359")) { - // Process constraint messages - merge multiple constraintMessage entries into arrays - Object.keys(this.blockStatements).forEach(function(fieldName) { - var props = _self.blockStatements[fieldName]; - var constraintMessages = []; - var otherProps = []; - - // Separate constraint messages from other properties - props.forEach(function(prop) { - if (typeof prop === 'string' && prop.startsWith('constraintMessage :')) { - // Extract the constraint object part - var constraintPart = prop.substring(prop.indexOf('{')); - constraintMessages.push(constraintPart); - } else { - otherProps.push(prop); - } - }); - - // If we have constraint messages, merge them into a single array - if (constraintMessages.length > 0) { - var constraintArray = "constraintMessage : [" + constraintMessages.join(", ") + "]"; - otherProps.push(constraintArray); - } - - _self.blockStatements[fieldName] = otherProps; - }); - } - - this.script = Object.entries(this.blockStatements).flatMap(function (arg) { - var fieldName = arg[0]; - var props = arg[1]; - var updates = "{" + props.join(", ") + "}" - if (fieldName === "$field") { - return withCondition(updates) - } else if (fieldName === "$GLOBAL") { - return withCondition(props) - } else { - return withCondition("dispatchEvent(" + fieldName + ", 'custom:setProperty', " + updates + ")") - } - }); - return true; - }, - - enterBLOCK_STATEMENTS : function (model) { - if (this.currentEvent.hasCondition) { - this.blockStatements = {} - } - }, - - exitBLOCK_STATEMENTS : function (model) { - return this._exitBlockStatementsTransformer(model); - }, - - enterWSDL_BLOCK_STATEMENTS : function (model) { - if (this.currentEvent.hasCondition) { - this.blockStatements = {} - } - }, - - exitWSDL_BLOCK_STATEMENTS : function (model) { - return this._exitBlockStatementsTransformer(model); - }, - - _setProperty : function (model, update) { - var fieldName = typeof model === 'string' ? model : this._getComponentName(model) - if (fieldName) { - this.blockStatements[fieldName] = this.blockStatements[fieldName] || []; - this.blockStatements[fieldName].push(update) - } - return true; - }, - - enterHIDE_STATEMENT : function (model) { - return this._setProperty(model.items[0], "visible : false()") - }, - - enterSHOW_STATEMENT : function (model) { - return this._setProperty(model.items[0], "visible : true()") - }, - - enterENABLE_STATEMENT : function (model) { - return this._setProperty(model.items[0], "enabled : true()") - }, - - enterDISABLE_STATEMENT : function (model) { - return this._setProperty(model.items[0], "enabled : false()") - }, - - _writeCondition : function (model, statementFn) { - var always = model == null; - if (!always) { - this.write("if ("); - model.accept(this); - this.writeLn(") {"); - } - if (typeof statementFn === 'function') { - statementFn.call(); - } - if (!always) { - this.writeLn(""); - this.writeLn("}"); - } - }, - - /** - * Write a If Else Condition with condition being the conditionModel and value being the code inside the - * if block. If value is instance of Model, that will be transformed into a script otherwise the value - * will be written as string - * @param conditionModel condition for the if block - * @param value {String|BaseModel} - * @param elseModel {String} - * @member AFTransformer - * @private - */ - _writeIfElseCondition : function (conditionModel, value, elseModel) { - var always = conditionModel.choiceModel === null; - if (!always) { - this.write("if("); - conditionModel.accept(this); - this.write(',') - } - if (typeof value === "string") { - this.write(value); - } else if (value instanceof expeditor.model.BaseModel) { - value.accept(this); - } - if (!always) { - if (typeof elseModel === "string") { - this.write(","); - this.write(elseModel); - } - this.write(")"); - } - }, - - enterCALC_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Calculate"; - this._writeIfElseCondition(model.items[4], model.items[2], '$field') - return true; - }, - - enterCLEAR_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Calculate"; - this._writeIfElseCondition(model.items[2], 'null()', '$field') - return true; - }, - - enterVALUE_COMMIT_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Value Commit"; - this.write("if ("); - this.write("this.value"); - model.items[1].choiceModel.accept(this); - model.items[2].choiceModel.accept(this); - this.writeLn(") {"); - model.items[4].accept(this); - this.writeLn(""); - this.writeLn("}"); - return true; - }, - - enterSUMMARY_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Summary"; - var self = this; - this._writeCondition(model.items[4].choiceModel, function () { - model.items[2].accept(self); - }); - return true; - }, - - enterEXPRESSION : function (model) { - this.needsValue = true; - }, - - exitEXPRESSION : function (model) { - this.needsValue = false; - }, - - enterSTRING_LITERAL : function (model) { - if (model && model.getValue() !== null) { - return this._super.apply(this, arguments); - } - }, - - enterEVENT_PAYLOAD : function (model) { - if (model && model.getValue()) { - var key = model.getValue(); - // when there is encryption on, we need to return payload only, body is only for WSDL request - if (this.ctx && this.ctx._apiIntegrationJson && this.ctx._apiIntegrationJson.encryptionRequired) { - this.write('toObject($event.payload)' + (key.startsWith("[*]") ? key : ("." + key))); - } else { - if (key === 'invokeServiceResponse.rawPayloadBody') { - this.write('toObject($event.payload).body'); - } else { - this.write('toObject($event.payload.body)' + (key.startsWith("[*]") ? key : ("." + key))); - } - } - } - }, - - enterNUMERIC_LITERAL : function (model) { - return this._super.apply(this, arguments); - }, - - enterDATE_LITERAL : function (model) { - return this._super.apply(this, arguments); - }, - - enterCONCAT : function (model) { - this.write(' & ') - }, - - /** - * This will enable to handle null values of the component. - * Otherwise, null when used with string is casted to "null". - * @param model - * @returns {boolean} - * @private - */ - _isPlusOperator : function (model) { - var operator = expeditor.Utils.getOrElse(model.get(1), "choiceModel.nodeName", null); - return operator === 'PLUS'; - }, - - enterCONDITIONORALWAYS : function (model) { - if (!model.choiceModel) { - this.write("true"); - } - }, - - _handleBooleanProperty : function (model, retVal, toggle, event, property) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = event; - var conditionModel = model.items[2]; - if (toggle) { - var hasCondition = conditionModel.choiceModel !== null; - if (hasCondition) { - if (retVal === "false()") { - this.write("!(") - } - conditionModel.accept(this); - if (retVal === "false()") { - this.write(")") - } - } else { - this.write(retVal) - } - } else { - this._writeIfElseCondition(model.items[2], retVal, "$field.$" + property); - } - return true - }, - - enterVISIBLE_EXPRESSION : function (model) { - return this._handleBooleanProperty(model, "false()", - model.items[4].choiceModel.nodeName === "Show", "Visibility", "visible") - }, - - enterSHOW_EXPRESSION : function (model) { - return this._handleBooleanProperty(model, "true()", - model.items[4].choiceModel.nodeName === "Hide", "Visibility", "visible") - }, - - enterACCESS_EXPRESSION : function (model) { - return this._handleBooleanProperty(model, "true()", - model.items[4].choiceModel.nodeName === "Disable", "Enabled", "enabled"); - }, - - enterDISABLE_EXPRESSION : function (model) { - return this._handleBooleanProperty(model, "false()", - model.items[4].choiceModel.nodeName === "Enable", "Enabled", "enabled"); - }, - - enterVALIDATE_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Validate"; - model.items[3].accept(this); - return true; - }, - - enterFORMAT_EXPRESSION : function (model) { - if(Granite.Toggles.isEnabled("FT_FORMS-13193")) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Format"; - model.items[3].accept(this); - return true; - } - }, - - _handleHasSelected : function (model) { - var operator = expeditor.Utils.getOrElse(model.get(1), "choiceModel.nodeName", null); - if (operator === "HAS_SELECTED") { - var input = [model.get(0), model.get(2)]; - this._writeFunction('contains', input); - return true; - } - }, - - _handleIsValidNotValidSelected : function (model) { - if (Granite.Toggles.isEnabled('FT_FORMS-17090')) { - var operator = expeditor.Utils.getOrElse(model.get(1), "choiceModel.nodeName", null); - if (operator === "IS_VALID" || operator === "IS_NOT_VALID") { - this.write('validate('); - var item = model.items[0]; - if (item.nodeName === 'EVENT_AND_COMPARISON_LEFT_HAND_EXPRESSION') { - item = item.choiceModel; - } - var id = item.getValue().id; - this.write(id); - if (operator === "IS_VALID") { - this.write(').length==0'); - } else { - this.write(').length!=0'); - } - return true; - } - return false; - } - return false; - - }, - - enterHAS_SELECTED : function () { - // override default implementation - }, - - enterCOMPARISON_EXPRESSION : function (model) { - return this._super.apply(this, arguments) - || this._handleHasSelected(model) || this._handleIsValidNotValidSelected(model); - }, - - enterCOMPLETION_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Completion"; - model.items[2].accept(this); - this.writeLn(";"); - return true; - }, - - enterOPTIONS_EXPRESSION : function (model) { - this.currentEvent.field = model.items[0].getValue().id; - this.currentEvent.name = "Options"; - var self = this; - this._writeCondition(model.items[4].choiceModel, function () { - model.items[2].accept(self); - }); - return true; - }, - - enterNAVIGATION_EXPRESSION : function (model) { - this.currentEvent.name = "Navigation"; - var self = this; - this._writeCondition(model.items[2].choiceModel, function () { - model.items[0].accept(self); - }); - return true; - }, - /** - * Method to generate a indented string representation of json object - */ - _stringify : function (indentation, varName, jsonObj, quote) { - var out = "var " + varName + " = " + JSON.stringify(jsonObj, null, RuntimeUtil.SCRIPT_INDENT.length); - return out.split('\n').map(function (line) { - return indentation + line; - }).join('\n'); - }, - - enterWSDL_OPTIONS_EXPRESSION : function (model) { - var val = model.getValue(); - - if (val == null) { - return; - } - - var indent = this.currentEvent.hasCondition ? RuntimeUtil.SCRIPT_INDENT : ""; - this._writeWsdlInfo(val, indent); - - /* inputs */ - this._writeWsdlInput(val, indent); - var savedValue = val.outputModel.saveValue; - var displayValue = val.outputModel.displayValue; - - if (savedValue && !displayValue) { - displayValue = savedValue; - } - - this.writeLn(indent + "var outputs={"); - this.writeLn(indent + RuntimeUtil.SCRIPT_INDENT + "savedValue:'" + savedValue + "',"); - this.writeLn(indent + RuntimeUtil.SCRIPT_INDENT + "displayedValue:'" + displayValue + "',"); - this.writeLn(indent + RuntimeUtil.SCRIPT_INDENT + "field:this"); - this.writeLn(indent + "};"); - - this.write(indent + "guidelib.dataIntegrationUtils.setOptionsFromService(operationInfo, inputs, outputs);"); - }, - - enterWSDL_VALUE_EXPRESSION : function (model) { - var val = model.getValue(); - if (val == null) { - return; - } - var indent = this.currentEvent.hasCondition ? RuntimeUtil.SCRIPT_INDENT : ""; - this._writeWsdlInfo(val, indent); - - /* inputs */ - this._writeWsdlInput(val, indent); - var value = val.outputModel.value; - - this.writeLn(indent + "var outputs={"); - this.writeLn(indent + RuntimeUtil.SCRIPT_INDENT + "value:'" + value + "',"); - this.writeLn(indent + RuntimeUtil.SCRIPT_INDENT + "field:this"); - this.writeLn(indent + "};"); - - this.write(indent + "guidelib.dataIntegrationUtils.setValueFromService(operationInfo, inputs, outputs);"); - }, - - _writeWsdlInfo : function (val, indent) { - /* wsdlInfo */ - var wsdlInfoString = this._stringify(indent, "operationInfo", val.wsdlInfo); - if (wsdlInfoString && wsdlInfoString.length > indent.length) { - wsdlInfoString = wsdlInfoString.substring(indent.length); - } - this.writeLn(wsdlInfoString + ";"); - }, - - /** - * Method to update an object with a key value pair with the key a dot seperated location within the object - * @private - */ - _updateObject: function(object, key, value) { - var parts = key.split('.'); - var ref = object; - for(var i = 0; i < parts.length - 1; i++) { - // Check if the current property exists and is an object - // If not (e.g., it's a string like 'null()'), replace it with an empty object - if (!ref[parts[i]] || typeof ref[parts[i]] !== 'object') { - ref[parts[i]] = {}; - } - ref = ref[parts[i]]; - } - // Only set the value if we're setting a nested property OR if the existing value is not an object - // This prevents overwriting an object that already has nested properties - // Example scenario: - // Step 1: _updateObject(obj, "abc.def", "value1") - // Result: {abc: {def: "value1"}} - // Step 2: _updateObject(obj, "abc", "null()") - // Without protection: {abc: "null()"} - nested data lost! - // With protection: {abc: {def: "value1"}} - preserved! - var finalKey = parts[parts.length - 1]; - if (parts.length > 1 || !ref[finalKey] || typeof ref[finalKey] !== 'object' || Object.keys(ref[finalKey]).length === 0) { - ref[finalKey] = value; - } - }, - - _getWsdlInput : function (val, apiIntegrationJson) { - var input = "" - var header = ""; - var self = this; - if (val.inputModel) { - var inputObj = {}; - var headerObj = {}; - var pathParams = {}; - var inputMapping = apiIntegrationJson.inputMapping || []; - var contentType = apiIntegrationJson.contentType || "application/json"; - if (!apiIntegrationJson.executeAtClient) { // todo: this is done since we need to call "af.apiintegration" servlet - contentType = "application/x-www-form-urlencoded"; - } - self._updateObject(headerObj, "Content-Type", "'" + contentType + "'"); - - // First pass - collect all entries and track keys with non-null values - var entries = []; - var keysWithValues = new Set(); - - Object.entries(val.inputModel).forEach(function (entry) { - var key = entry[0]; - var value = entry[1]; - var valueToBeWritten = ""; - var isValueComponent = false; - if (value && value.choice) { - var transformer = new customTransformer(); - transformer.setContext(self.ctx); - transformer.setEvent({ - field: self.currentEvent.field - }); - var copyModel = expeditor.Utils.ModelFactory.fromJson(value, self.ctx).choiceModel; - copyModel.accept(transformer); - if(copyModel.nodeName === 'COMPONENT' || copyModel.nodeName === 'AFCOMPONENT') { - isValueComponent = true; - } - valueToBeWritten = transformer.script; - } - var mapping = inputMapping.find(function (map) { - return map.apiKey === key; - }); - - if (valueToBeWritten && mapping) { - var isMappingArrayType = false; - var arrayTypes = ['ARRAY', 'STRING[]', 'NUMBER[]', 'BOOLEAN[]']; - if (_.includes(arrayTypes, mapping.type.trim().toUpperCase())) { - isMappingArrayType = true; - } - valueToBeWritten = isMappingArrayType ? RuntimeUtil.modifyRepeatablePanelFieldId(valueToBeWritten) : valueToBeWritten; - if (isValueComponent && ('OBJECT' === mapping.type.trim().toUpperCase() || 'ARRAY' === mapping.type.trim().toUpperCase())) { - valueToBeWritten = valueToBeWritten.endsWith(".$value") ? valueToBeWritten : valueToBeWritten + ".$value"; - } - } - - var newValue = (valueToBeWritten ? valueToBeWritten : (mapping && mapping.defaultValue ? (mapping.type === 'string' ? "'" + mapping.defaultValue + "'" : mapping.defaultValue) : "null()")); - - if (newValue !== "null()") { - keysWithValues.add(key); - } - - entries.push({ - key: key, - newValue: newValue, - mapping: mapping - }); - }); - - // Build skip set for API integration - skip nested keys if parent has value - var skipKeys = new Set(); - if (inputMapping && inputMapping.length > 0) { - keysWithValues.forEach(function(keyWithValue) { - entries.forEach(function(entry) { - if (entry.key.indexOf(keyWithValue + '.') === 0) { - skipKeys.add(entry.key); - } - }); - }); - } - - // Second pass - apply values - entries.forEach(function(entry) { - var key = entry.key; - var newValue = entry.newValue; - var mapping = entry.mapping; - - if (newValue.length > 0 && newValue !== "null()") { - if (mapping) { // API integration only - if (mapping.in === "header") { - self._updateObject(headerObj, key, newValue); - } else if (mapping.in === "path") { - pathParams[key] = newValue; - } else { - // Skip nested keys if parent has value - if (!skipKeys.has(key)) { - self._updateObject(inputObj, key, newValue); - } - } - } else { // FDM integration - self._updateObject(inputObj, key, newValue); - } - } - }); - - // Handle path parameters in URL if they exist - if (Object.keys(pathParams).length > 0 && apiIntegrationJson.url) { - var urlParts = apiIntegrationJson.url.split(/[{}]/); - var newUrl = urlParts.map(function(part, index) { - // Even indices are regular URL parts, odd indices are parameters - if (index % 2 === 0) { - return part ? "'" + part + "'" : ""; - } else { - // Check if this parameter exists in our pathParams - var paramValue = pathParams[part]; - return paramValue || "{" + part + "}"; - } - }).filter(function(part) { - return part !== ""; - }).join(' & '); - - apiIntegrationJson.url = newUrl; - } - - // now serialize this into a json-formula multi-dict - function serialize(obj) { - if (typeof obj !== "object") { - return obj; - } - var result = Object.entries(obj).map(function (elem){ - // For now we are not checking if key itself contains double quotes or not because FDM doesn't send them in inputModel - // FDM itself converts xyz\"er to xyz_er, \"xyz\" to _xyz_ in input model when key has double quotes. - // If FDM starts supporting them then we will have to change here as well. - var key = '"' + elem[0] + '"'; - return key + ': ' + serialize(elem[1]); - }).join(','); - return "{" + result + "}"; - } - input = serialize(inputObj); - header = serialize(headerObj); - } - return { input: input, header: header }; - }, - - _getWsdlOutput : function (val, apiIntegrationJson) { - var output = []; - const self = this; - if (val.outputModel) { - Object.entries(val.outputModel).forEach(function(x) { - var key = x[1].id || x[0]; - var arg = x[1]; - if (arg !== "") { - var fieldId = expeditor.Utils.getOrElse(arg, "value.id", null); - if (fieldId !== null) { - var relativeName = self._getRelativeName(arg.value.id, self.currentEvent.field); - if (apiIntegrationJson && apiIntegrationJson.encryptionRequired) { - output.push("dispatchEvent(" + relativeName + ",'custom:setProperty', {value: toObject(decrypt($event.payload.body, $event.payload.originalRequest))" + (key.startsWith("[*]") ? key : ("." + key)) + "})") - } else { - output.push("dispatchEvent(" + relativeName + ",'custom:setProperty', {value: toObject($event.payload.body)" + (key.startsWith("[*]") ? key : ("." + key)) + "})") - } - } - } - }); - } - return output; - }, - - _getEnhancedWsdlOutput : function (successCallbacks, apiIntegrationJson) { - var self = this; - var output = []; - if(Granite.Toggles.isEnabled("FT_FORMS-11584")) { - for (var successCallback in successCallbacks) { - var model = successCallbacks[successCallback]; - if (model.items && model.items.length) { - var transformer = new customTransformer(); - this.ctx._apiIntegrationJson = apiIntegrationJson; - transformer.setContext(this.ctx); - transformer.setEvent({ - field: self.currentEvent.field - }) - model.accept(transformer); - var script = transformer.getScript(); - - script.content.forEach(function(scriptLine) { - output.push(scriptLine); - }); - } - } - } - return output; - }, - - _getEnhancedWsdlCustomError : function (failureCallbacks, apiIntegrationJson) { - var self = this; - var customError = []; - if(Granite.Toggles.isEnabled("FT_FORMS-11584")) { - for (failureCallback in failureCallbacks) { - var model = failureCallbacks[failureCallback]; - if (model.items && model.items.length) { - var transformer = new customTransformer(); - this.ctx._apiIntegrationJson = apiIntegrationJson; - transformer.setContext(this.ctx); - transformer.setEvent({ - field: self.currentEvent.field - }) - model.accept(transformer); - var script = transformer.getScript(); - script.content.forEach(function(scriptLine) { - customError.push(scriptLine); - }); - } - } - } - return customError; - }, - - _handleError : function (val, apiIntegrationJson) { - var output = []; - if (val.customErrorHandlerFunctionModel && val.customErrorHandlerFunctionModel.functionName) { - var funcId = val.customErrorHandlerFunctionModel.functionName.id; - - if (funcId === "defaultErrorHandler") { - if (apiIntegrationJson && apiIntegrationJson.encryptionRequired) { - output.push(funcId + "(toObject(decrypt($event.payload.body, $event.payload.originalRequest)), $event.payload.headers)"); - } else { - output.push(funcId + "(toObject($event.payload.body), $event.payload.headers)"); - } - } else { - if (apiIntegrationJson && apiIntegrationJson.encryptionRequired) { - output.push(funcId + "(toObject(decrypt($event.payload.body, $event.payload.originalRequest)), $event.payload.headers) && defaultErrorHandler(toObject(decrypt($event.payload.body, $event.payload.originalRequest)), $event.payload.headers)"); - } else { - output.push(funcId + "(toObject($event.payload.body), $event.payload.headers) && defaultErrorHandler(toObject($event.payload.body), $event.payload.headers)"); - } - } - } - return output; - }, - - enterCALLBACK : function (model) { - if(Granite.Toggles.isEnabled("FT_FORMS-13519")) { - if (model.items && model.items.length) { - this.script = []; - for (var i =0; i< model.items.length; i++) { - var transformer = new customTransformer(); - transformer.setContext(this.ctx); - transformer.setEvent({ - field: this.currentEvent.field - }) - model.items[i].accept(transformer); - var script = transformer.getScript(); - if (typeof script.otherEvents === 'object') { - this.currentEvent.otherEvents = this.currentEvent.otherEvents || {}; - var self = this; - Object.entries(script.otherEvents).forEach(function (e) { - if (e[0].length > 0) { - self.currentEvent.otherEvents[e[0]] = e[1] - } - }) - } - this.script = this.script.concat(script.content) - } - } - } - return true; - }, - - enterCONDITION_BLOCK_STATEMENTS: function (model) { - if (Granite.Toggles.isEnabled("FT_FORMS-13519")) { - this.blockStatements = {}; - var condition = model.items[1]; - this.currentEvent.hasCondition = true; - // create a new transformer for the condition - var transformer = new customTransformer(); - transformer.setContext(this.ctx); - transformer.setEvent({ - field: this.currentEvent.field - }) - condition.accept(transformer); - this.currentEvent.condition = transformer.getScript().content - return false; - } - return true; - }, - - enterWSDL_CALLBACK_STATEMENT: function (model) { - if (Granite.Toggles.isEnabled("FT_FORMS-11584")) { - this.blockStatements = {}; - var condition = model.items[1]; - this.currentEvent.hasCondition = true; - // create a new transformer for the condition - var transformer = new customTransformer(); - transformer.setContext(this.ctx); - transformer.setEvent({ - field: this.currentEvent.field - }) - condition.accept(transformer); - this.currentEvent.condition = transformer.getScript().content - return false; - } - return true; - }, - - exitCONDITION_BLOCK_STATEMENTS : function (model) { - if (Granite.Toggles.isEnabled("FT_FORMS-13519")) { - return this.exitBLOCK_STATEMENTS(model) - } - return true; - }, - - _createCallbackEvent: function (model, type) { - var callbackModel = model.callbacks[type] - if (callbackModel) { - var callbackEvent = "custom:" + - model.getFunctionName().id + "_" + - type + "_" + model.callbacks.id; - var transformer = new customTransformer(); - transformer.setContext(this.ctx); - transformer.setEvent({ - field: this.currentEvent.field - }); - callbackModel.accept(transformer) - return { - name: callbackEvent, - script: transformer.getScript() - } - } - return { - name :'', - script: '' - } - }, - - enterASYNC_FUNCTION_CALL : function (model) { - if (Granite.Toggles.isEnabled("FT_FORMS-13519")) { - var transformer = new customTransformer(); - transformer.setContext(this.ctx); - transformer.setEvent({ - field: this.currentEvent.field - }); - var copyModel = model.copy(); - copyModel.nodeName = 'FUNCTION_CALL'; - copyModel.accept(transformer); - var callbackEvents = [] - if (copyModel.callbacks) { - var self = this; - callbackEvents = ['success', 'failure'].reduce(function (acc, e) { - var evnt = self._createCallbackEvent(copyModel, e); - if(evnt.name) { - acc.otherEvents[evnt.name] = { - content: evnt.script.content - } - } - if (typeof evnt.script.otherEvents === 'object') { - Object.entries(evnt.script.otherEvents).forEach(function (e) { - if (e[0].length > 0) { - acc.otherEvents[e[0]] = e[1] - } - }) - } - acc.args += ",'" + evnt.name +"'" - return acc; - }, {args: '', otherEvents: this.currentEvent.otherEvents || {}}) - } - this.currentEvent.otherEvents = callbackEvents.otherEvents - var script = "awaitFn(" + transformer.script + callbackEvents.args + ")" - return this._setProperty('$GLOBAL', script) - } - }, - - enterWSDL_STATEMENT : function (model) { - const getAFPath = function() { - return guidelib.RuntimeUtil.formPath - } - var val = model.getValue(); - if (val == null) { - return; - } - var url = "'" + getAFPath() +".af.dermis'"; - var wsdlInfo = val.wsdlInfo; - - if (wsdlInfo.type === 'api-integration') { - url = "'" + getAFPath() +".af.apiintegration'"; - } - - if (Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_9611) || Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_15407)) { - var form = model.ctx.getScope().findVarByType('FORM'); - if(form) { - var formProperties = expeditor.Utils.getOrElse(form[0], "props.options", null); - if (formProperties) { - var schemaRef = formProperties.schemaRef || ''; - var schemaType = formProperties.schemaType || ''; - - if(schemaType === 'connector') { - wsdlInfo.schemaRef = schemaRef; - wsdlInfo.schemaType = schemaType; - } - } - } - } - var apiIntegrationJson = {}; - if (wsdlInfo.type === 'api-integration') { - apiIntegrationJson = JSON.parse(wsdlInfo.inputJson); - } - - var wsdlInput = this._getWsdlInput(val, apiIntegrationJson), - input = wsdlInput.input, - header = wsdlInput.header; - - var data = [ - ['"operationName"', "'" + wsdlInfo.operationName + "'"], - ['"port"', wsdlInfo.port], - ['"soapActionURI"', "'" + wsdlInfo.soapActionURI + "'"], - ['"namespace"', "'" + wsdlInfo.namespace + "'"], - ['"input"', input.length > 0 ? "toString(" + input + ")" : ""], - ['"inputRoot"', "'" + wsdlInfo.inputRoot + "'"], - ['"inputAttr"', wsdlInfo.inputAttr ? "toString(" + wsdlInfo.inputAttr + ")" : ''], - ['"serviceEndPoint"', "'" + wsdlInfo.serviceEndPoint + "'"], - ['"functionToExecute"', "'invokeFDMOperation'"], - ['"apiVersion"', "'2'"], - ['"formDataModelId"', "'" + wsdlInfo.formDataModelId + "'"], - ['"runValidation"', "'" + wsdlInfo.runValidation + "'"], - ['"guideNodePath"', "'" + guidelib.RuntimeUtil.currentNodePath + "'"] - ]; - - if (wsdlInfo.type === 'api-integration') { - if(apiIntegrationJson.executeAtClient) { - if (input.length > 0) { - data = input; - } else { - data = []; - } - } - } - - if ('api-integration' !== wsdlInfo.type && - (Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_9611) || Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_15407))) { - data.push( - ['"schemaRef"', "'" + wsdlInfo.schemaRef + "'"], - ['"schemaType"', "'" + wsdlInfo.schemaType + "'"] - ); - } - - if (typeof data !== 'string') { - data = data.filter(function (obj) { - return obj[1] != null && obj[1].length > 0 && obj[1] !== "'undefined'" - }).map(function (d) { - return d[0] + ":" + d[1] - }).join(",") - } - var now = new Date().getTime() - var random = Math.random().toString().substring(2, 8); - var wsdlSuccessEventName = "custom:wsdlSuccess_" + random + '_' + now; - var wsdlErrorEventName = "custom:wsdlError_" + random + '_' + now; - var wsdlDecryptSuccessEventName = "custom:decryptSuccess_" + random + '_' + now; - var wsdlDecryptErrorEventName = "custom:decryptError_" + random + '_' + now; - this.currentEvent.otherEvents = this.currentEvent.otherEvents || {}; - - if (Granite.Toggles.isEnabled(guidelib.author.ConfigUpdater.FT_FORMS_11584)) { - if (apiIntegrationJson.encryptionRequired && apiIntegrationJson.publicKey) { - this.currentEvent.otherEvents[wsdlSuccessEventName] = { - content: "awaitFn(decrypt($event.payload.body, $event.payload.originalRequest), '" + wsdlDecryptSuccessEventName + "', '" + wsdlDecryptErrorEventName + "')" - } - this.currentEvent.otherEvents[wsdlDecryptSuccessEventName] = { - content: this._getEnhancedWsdlOutput(model.getCallback('success'), apiIntegrationJson) - } - // todo: handle decryption error lately - } else { - this.currentEvent.otherEvents[wsdlSuccessEventName] = { - content: this._getEnhancedWsdlOutput(model.getCallback('success'), apiIntegrationJson) - } - } - this.currentEvent.otherEvents[wsdlErrorEventName] = { - content: this._getEnhancedWsdlCustomError(model.getCallback('failure'), apiIntegrationJson) - } - } else { - this.currentEvent.otherEvents[wsdlSuccessEventName] = { - content: this._getWsdlOutput(val, apiIntegrationJson) - } - this.currentEvent.otherEvents[wsdlErrorEventName] = { - content: this._handleError(val, apiIntegrationJson) - } - } - if (wsdlInfo.type === 'api-integration') { - var finalUrl = url; - if (data.length > 0 && !data.startsWith("{") && !data.endsWith("}")) { - data = "{" + data + "}"; - } - if(apiIntegrationJson.executeAtClient && apiIntegrationJson.url) { - finalUrl = apiIntegrationJson.url; - } - // Helper function to properly format URL expression - function formatUrlExpr(url) { - - // Count single quotes to check if they're balanced - var quoteCount = (url.match(/'/g) || []).length; - - // If odd number of quotes, they're unbalanced - add closing quote - // example: 'https://example.com/abc - // example: https://example.com/abc' - if (quoteCount % 2 === 1) { - var startsWithQuote = url.startsWith("'"); - var endsWithQuote = url.endsWith("'"); - - if (startsWithQuote && !endsWithQuote) { - // Missing closing quote - add at end - return url + "'"; - - } else if (!startsWithQuote && endsWithQuote) { - // Missing opening quote - add at start - return "'" + url; - - } - } - - // If no quotes at all - // example: https://example.com/abc - if (quoteCount === 0) { - return "'" + url + "'"; - } - - // Even number of quotes (balanced) - leave as is - // example: 'https://example.com/abc/' & zip.$value - // example: 'https://example.com/abc/' & zip.$value & '.json' - return url; - } - - if (Granite.Toggles.isEnabled(RETRY_REQUEST_HANDLER_FT)) { - if (apiIntegrationJson.encryptionRequired && apiIntegrationJson.publicKey) { - var urlExpr = formatUrlExpr(finalUrl); - return this._setProperty('$GLOBAL', "awaitFn(retryHandler(requestWithRetry(externalize(" + urlExpr + "), '" + apiIntegrationJson.method + "', encrypt({body: " + data + ", headers: " + header + "}, '" + apiIntegrationJson.publicKey + "'), '" + wsdlSuccessEventName + "'," + "'" + wsdlErrorEventName + "')))") - } else { - var urlExpr = formatUrlExpr(finalUrl); - return this._setProperty('$GLOBAL', "awaitFn(retryHandler(requestWithRetry(externalize(" + urlExpr + "), '" + apiIntegrationJson.method + "', " + data + ", " + header + ", '" + wsdlSuccessEventName + "'," + "'" + wsdlErrorEventName + "')))") - } - } else { - if (apiIntegrationJson.encryptionRequired && apiIntegrationJson.publicKey) { - var urlExpr = formatUrlExpr(finalUrl); - return this._setProperty('$GLOBAL', "request(externalize(" + urlExpr + "),'" + apiIntegrationJson.method + "', encrypt({body: " + data + ", headers: " + header + "}, '" + apiIntegrationJson.publicKey + "'), '" + wsdlSuccessEventName + "'," + "'" + wsdlErrorEventName + "')") - } else { - var urlExpr = formatUrlExpr(finalUrl); - return this._setProperty('$GLOBAL', "request(externalize(" + urlExpr + "),'" + apiIntegrationJson.method + "', " + data + ", " + header + ", '" + wsdlSuccessEventName + "'," + "'" + wsdlErrorEventName + "')"); - } - } - } else { - if (Granite.Toggles.isEnabled(RETRY_REQUEST_HANDLER_FT)) { - return this._setProperty('$GLOBAL', "awaitFn(retryHandler(requestWithRetry(externalize(" + url + "), 'POST', {" + data +"}, {\"Content-Type\" : 'application/x-www-form-urlencoded'}, '" + wsdlSuccessEventName + "'," + "'" + wsdlErrorEventName + "')))"); - } else { - return this._setProperty('$GLOBAL', "request(externalize(" + url + "), 'POST', {" + data +"}, {\"Content-Type\" : 'application/x-www-form-urlencoded'}, '" + wsdlSuccessEventName + "'," + "'" + wsdlErrorEventName + "')"); - } - } - }, - - exitWSDL_STATEMENT : function (model) { - - }, - - enterSET_PROPERTY : function (model) { - var constraintMessageKeys = { - "minimumMessage": { - "type": "minimum" - }, - "maximumMessage": { - "type": "maximum" - } - }; - - var oldScript = this.script; - this.script = "" - model.items[2].accept(this) - var expression = this.script; - this.script = ""; - model.items[0].items[2].accept(this) - var fieldName = this.script; - this.script = ""; - model.items[0].items[0].accept(this) - var propName = this.script; - this.script = oldScript - if (propName.indexOf(".") > -1) { - var propParts = propName.split('.'); //assumption is that there is a single . only - this._setProperty(fieldName, propParts[0].substring(1) + " : {" + propParts[1] + " : " + expression + "}") - } else { - if (constraintMessageKeys[propName.substring(1)]) { - return this._setProperty(fieldName, "constraintMessage : { type : '" + constraintMessageKeys[propName.substring(1)].type + "', message : " + expression + "}") - } - return this._setProperty(fieldName, propName.substring(1) + " : " + expression) - } - }, - - enterSET_VALUE_STATEMENT : function (model) { - var oldScript = this.script; - this.script = "" - model.items[2].accept(this) - var expression = this.script; - this.script = oldScript; - if (Granite.Toggles.isEnabled('FT_FORMS-11584') && model.items[0] && model.items[0].getValue() && model.items[0].getValue().type === 'PANEL') { - // If panel is selected in Set Value, then need to call importData function - const id = model.items[0].getValue().id; - return this._setProperty('$GLOBAL', "importData(" + expression + ",'" + id + "')"); - } - return this._setProperty(model.items[0], 'value : ' + expression); - }, - - exitCLEAR_VALUE_STATEMENT : function (model) { - return this._setProperty(model.items[0], "value : `null`") - }, - - enterSAVE_FORM : function (model) { - var formId = ''; - var form = model.ctx.getScope().findVarByType('FORM'); - if (form && form[0] && form[0].props && form[0].props.options) { - formId = form[0].props.options.originalId || ''; - } - const path = "externalize('/adobe/forms/af/save/" + formId + "')"; - return this._setProperty('$GLOBAL', "saveForm(" + path + ")") - }, - - enterSUBMIT_FORM : function (model) { - return this._setProperty('$GLOBAL', "submitForm()") - }, - - enterRESET_FORM : function (model) { - if (model.value && model.value.id) { - var fieldId = model.value.id; - var shortName = this._getRelativeName(fieldId, this.currentEvent.field); - return this._setProperty('$GLOBAL', "dispatchEvent(" + shortName + ", 'reset')"); - } else { - return this._setProperty('$GLOBAL', "dispatchEvent('reset')"); - } - }, - - enterVALIDATE_FORM : function (model) { - if (model.value && model.value.id) { - var fieldId = model.value.id; - var shortName = this._getRelativeName(fieldId, this.currentEvent.field); - return this._setProperty('$GLOBAL', "validate(" + shortName + ")"); - } else { - return this._setProperty('$GLOBAL', "validate()"); - } - }, - - enterSET_FOCUS : function (model) { - var oldScript = this.script; - this.script = "" - model.items[1].accept(this) - var expression = this.script; - this.script = oldScript; - return this._setProperty('$GLOBAL', 'dispatchEvent(' + expression + ',\'focus\')'); - }, - - enterNAVIGATE_IN_PANEL : function (model) { - var oldScript = this.script; - this.script = "" - model.items[2].accept(this) - var expression = this.script; - this.script = oldScript; - var focusOption = model.items[0].choiceModel.nodeName; - focusOption = focusOption === 'NEXT_ITEM' ? 'nextItem' : 'previousItem'; - return this._setProperty('$GLOBAL', 'setFocus(' + expression + ",'" + focusOption + "')") - }, - - enterADD_INSTANCE : function (model) { - var fieldId = model.items[1].getValue().id; - var shortName = this._getRelativeName(fieldId, this.currentEvent.field); - if (Granite.Toggles.isEnabled('FT_FORMS-16466')) { - return this._setProperty('$GLOBAL', "addInstance(" + shortName + ", getRelativeInstanceIndex(" + fieldId +") + 1)"); - } - return this._setProperty('$GLOBAL', 'addInstance(' + shortName + ")"); - }, - - enterREMOVE_INSTANCE : function (model) { - var fieldId = model.items[1].getValue().id; - var shortName = this._getRelativeName(fieldId, this.currentEvent.field); - if (Granite.Toggles.isEnabled('FT_FORMS-16466')) { - return this._setProperty('$GLOBAL', "removeInstance(" + shortName + ", getRelativeInstanceIndex(" + fieldId +"))"); - } - return this._setProperty('$GLOBAL', 'removeInstance(' + shortName + ", length(" + shortName + ") - 1)"); - }, - - enterPRIMITIVE_VARIABLE : function (model) { - var val = model.getValue(); - if (val) { - this.write(this._getRelativeName(val.id, this.currentEvent.field)); - if (expeditor.Utils.isPrimitive(val.type)) { - this.write(".value"); - } - } - }, - - enterNAVIGATE_TO : function (model) { - var url = ""; - if(model.items[0].choiceModel.nodeName === "URL_LITERAL") { - url = "'"+model.items[0].choiceModel.getValue()+"'"; - } else { - var oldScript = this.script; - this.script = "" - model.items[0].accept(this) - url = this.script; - this.script = oldScript; - } - - var target = model.items[2]; - if (target != null) { - target = target.choiceModel.nodeName; - } else { - target = "SAME_TAB" - } - var _target; - switch(target) { - case 'SAME_TAB': - _target = '_self'; - break; - case 'NEW_TAB': - _target = '_blank' - break; - case 'NEW_WINDOW': - _target = '_newwindow'; - break; - default: - _target = '_self'; - break; - } - if (url != null) { - return this._setProperty('$GLOBAL', "navigateTo(" + url + ", '" + _target + "')") - } - }, - - enterDISPATCH_EVENT : function (model) { - var fieldId = model.items[2] && model.items[2].getValue() ? model.items[2].getValue().id : null; - var shortName = ''; - if (fieldId) { - shortName = this._getRelativeName(fieldId, this.currentEvent.field); - } - var eventName = model.items[0].value - if (Granite.Toggles.isEnabled('FT_FORMS-21264') && !eventName.startsWith('custom:')) { - eventName = 'custom:' + eventName; - } - if (shortName && '$globalForm' !== shortName) { - this._setProperty('$GLOBAL', 'dispatchEvent(' + shortName + ", '" + eventName + "')"); - } else { - this._setProperty('$GLOBAL', 'dispatchEvent(' + "'" + eventName + "')"); - } - return true; - }, - - enterFUNCTION_CALL : function (model) { - if (model.getFunctionName()) { - var funcDef = model.getFunctionName(), - impl = funcDef.impl, - self = this; - - if (funcDef.id === 'getEventPayload') { - var param = model.getParameter(0) - const paramChoice = param.getChoiceModel(); - if (param && paramChoice !== null) { - const paramType = paramChoice.nodeName; - if (paramType === 'STRING_LITERAL') { - this.write('$event.payload.' + paramChoice.value); - return; - } - } else { - this.write('$event.payload'); - return; - } - } else if (Granite.Toggles.isEnabled('FT_FORMS-11584') && model.getFunctionName() && model.getFunctionName().isErrorHandler) { - const funcId = funcDef.id; - if (funcId === 'defaultErrorHandler') { - self.write(funcId + "(toObject($event.payload.body), $event.payload.headers)"); - } else { - self.write(funcId + "(toObject($event.payload.body), $event.payload.headers) && defaultErrorHandler(toObject($event.payload.body), $event.payload.headers)"); - } - return this._setProperty('$GLOBAL', this.script); - } - var oldScript = this.script; - this.script = ""; - - /* Function Implementation is of the type $<NUM>($<NUM>, $<NUM>=$default) - * Currently any $<NUM> will be replaced by the transformation of <NUM> argument - * where 0th argument is the function id. - * $ not following a number will be replaced by $ only - * If the implementation wants to escape a $<NUM> we have to modify the regex - * below to - * /\\(?=\$)\$|\$([\d]+)|./g, - * And to escape, the user has to write $0($1, \\$3) - * - * Now also supports default values with syntax $<NUM>=defaultValue - */ - impl.replace(/\$([\d]+)(?:=([^,\)]+))?|./g, function (match, n1, defaultValue, offset) { - if (n1 && n1.length > 0) { - var num = +n1; - if (num === 0) { - self.write(funcDef.id); - } else { - if (model.getParameter(num - 1).getChoiceModel() == null || ((Granite.Toggles.isEnabled("FT_FORMS-19581")) && model.getParameter(num - 1).getChoiceModel() !== null && typeof model.getParameter(num - 1).getChoiceModel().getValue === 'function' && model.getParameter(num - 1).getChoiceModel().getValue() == null)) { - // means optional parameter is not set, use default if available - if (defaultValue) { - self.write(defaultValue); - } else { - self.write("undefined"); - } - } else { - if (Granite.Toggles.isEnabled("FT_FORMS-14303") && 'COMPONENT' === model.getParameter(num - 1).getChoiceModel().nodeName) { - var arrayTypes = ["NUMBER[]", "STRING[]", "BOOLEAN[]", "DATE[]", "ARRAY"]; - var fieldId = model.getParameter(num - 1).getChoiceModel().getValue().id; - - // Split the type string by '|' and check if any of the types are in arrayTypes using a for loop - var types = model.functionName.args[num - 1].type.split('|'); - var isArrayType = false; - for (var i = 0; i < types.length; i++) { - if (_.includes(arrayTypes, types[i].trim())) { - isArrayType = true; - break; - } - } - - if (isArrayType && expeditor.Utils.getOrElse(model.ctx.getScope().findVarById(fieldId), "element.metadata.isAncestorRepeatable", false)) { - var scriptTillNow = self.script; - self.script = ""; - model.getParameter(num - 1).accept(self); - self.script = scriptTillNow + RuntimeUtil.modifyRepeatablePanelFieldId(self.script); - } else { - if ('$globalForm' === fieldId && ('setVariable' === funcDef.id || 'getVariable' === funcDef.id)) { - self.write("undefined"); - } else { - model.getParameter(num - 1).accept(self); - } - } - } else if ('COMPONENT' === model.getParameter(num - 1).getChoiceModel().nodeName) { - var fieldId = model.getParameter(num - 1).getChoiceModel().getValue().id; - if ('$globalForm' === fieldId && ('setVariable' === funcDef.id || 'getVariable' === funcDef.id)) { - self.write("undefined"); - } else { - model.getParameter(num - 1).accept(self); - } - } else { - model.getParameter(num - 1).accept(self); - } - } - } - } else { - self.write(match); - } - }); - } - - if ('getParentNodeName' in model && typeof model.getParentNodeName === 'function' && ('BLOCK_STATEMENT' === model.getParentNodeName() || 'WSDL_BLOCK_STATEMENT' === model.getParentNodeName())) { - return this._setProperty('$GLOBAL', this.script) - } else { - this.script = oldScript + this.script; - } - }, - - enterSINGLE_TRIGGER_SCRIPTS : function(model) { - var oldScript = this.script; - if (model.items[0] && model.items[0].value) { - this.currentEvent.field = model.items[0].value.id; - } - if (model.items[1] && model.items[1].value) { - var eventName = model.items[1].value; - if (RuntimeUtil.eventToEventName.hasOwnProperty(eventName)) { - eventName = RuntimeUtil.eventToEventName[eventName]; - } else if (!eventName.startsWith('custom:')) { - eventName = 'custom:' + eventName; - } - this.currentEvent.name = eventName; - } - this.script = oldScript; - model.items[3].accept(this); - return true; - }, - - enterTRIGGER_EVENT_SCRIPTS : function (model) { - this.currentEvent.hasCondition = true; - if (model.items[0]) { - model.items[0].accept(this); - } - this.currentEvent.condition = this.script; - if (model.items[2]) { - model.items[2].accept(this); - } - if (model.items.length > 4) { - var previousIfConditionStatement = this.script; - this.currentEvent.condition = '!('+this.currentEvent.condition+')'; - model.items[4].accept(this); - - const mergedScript = []; - for (var i = 0; i < previousIfConditionStatement.length; i++) { - mergedScript.push(previousIfConditionStatement[i]); - } - for (var i = 0; i < this.script.length; i++) { - mergedScript.push(this.script[i]); - } - this.script = mergedScript; - } - return true; - }, - - enterUTM_PARAMETER: function (model) { - if (model && model.getValue()) { - this.write("getQueryParameter('" + model.getValue() + "')"); - } - return true; - }, - - enterQUERY_PARAMETER: function (model) { - if (model && model.getValue()) { - this.write("getQueryParameter('" + model.getValue() + "')"); - } - return true; - }, - - enterBROWSER_DETAILS: function (model) { - if (model && model.getValue()) { - this.write("getBrowserDetail('" + model.getValue() + "')"); - } - return true; - }, - - enterURL_DETAILS : function (model) { - if (model && model.getValue()) { - this.write("getURLDetail('" + model.getValue() + "')"); - } - return true; - }, - - enterGET_VARIABLE : function (model) { - var oldScript = this.script; - this.script = ""; - model.items[1].accept(this); - var variableName = this.script; - - this.script = ""; - model.items[3].accept(this); - var fieldId = this.script; - - this.script = oldScript; - - var shortName; - if (fieldId) { - shortName = this._getRelativeName(fieldId, this.currentEvent.field); - } - - if (shortName && '$globalForm' !== shortName) { - this.write("getVariable(" + variableName + ", " + shortName + ")"); - } else { - this.write("getVariable(" + variableName + ")"); - } - return true; - }, - - enterSET_VARIABLE : function (model) { - var oldScript = this.script; - this.script = ""; - model.items[1].accept(this); - var variableName = this.script; - - this.script = ""; - model.items[3].accept(this); - var variableValue = this.script; - - this.script = ""; - model.items[5].accept(this); - var fieldId = this.script; - - this.script = oldScript; - - var shortName; - if (fieldId) { - shortName = this._getRelativeName(fieldId, this.currentEvent.field); - } - - if (shortName && '$globalForm' !== shortName) { - this._setProperty('$GLOBAL', "setVariable(" + variableName + ", " + variableValue + ", " + shortName + ")"); - } else { - this._setProperty('$GLOBAL', "setVariable(" + variableName + ", " + variableValue + ")"); - } - return true; - }, - - enterWRITE_JSON_FORMULA : function (model) { - var oldScript = this.script; - this.script = ""; - model.items[0].accept(this); - var jsonFormula = this.script; - jsonFormula = jsonFormula.replace(/^['"]|['"]$/g, ''); - this.script = oldScript; - return this._setProperty('$GLOBAL', jsonFormula); - } - }); -}(jQuery, fd._)); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/FunctionsConfigV2.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/FunctionsConfigV2.js deleted file mode 100644 index 5cfd8a6b..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/FunctionsConfigV2.js +++ /dev/null @@ -1,976 +0,0 @@ -/************************************************************************* - * ADOBE CONFIDENTIAL - * ___________________ - * - * Copyright 2015 Adobe Systems Incorporated - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Adobe Systems Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Adobe Systems Incorporated and its - * suppliers and are protected by all applicable intellectual property - * laws, including trade secret and copyright laws. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Adobe Systems Incorporated. - **************************************************************************/ -(function (guidelib) { - - /* Change event listener for Contextual filtering of child fields based on the Panel/tableRow selected or vice-versa */ - guidelib.author.parameterChangeListener = function (parameters, index) { - if (parameters && parameters.length > 1) { - if (index == 0) { - /* Filter second argument form objects list to show only Child fields */ - var panelId = expeditor.Utils.getOrElse(parameters, "0.childComponent.model.value.id", null); - var fieldComponent = parameters[1].getChildOfType("COMPONENT"); - if (fieldComponent && typeof fieldComponent.setFilter === "function") { - var filter = function (variable) { - return !panelId || variable.parent == panelId; - }; - fieldComponent.setFilter.apply(fieldComponent, [filter]); - } - } else { - /* Filter first argument form objects list to show only Parent panel/tableRow */ - var fieldVal = expeditor.Utils.getOrElse(parameters, "1.childComponent.model.value", null); - var panelComponent = parameters[0].getChildOfType("COMPONENT"); - if (panelComponent && typeof panelComponent.setFilter === "function") { - var filter = function (variable) { - return !fieldVal || variable.id == fieldVal.parent; - }; - panelComponent.setFilter.apply(panelComponent, [filter]); - } - } - } - }; - - var functionsConfigJson = [ - { - "id": "abs", - "displayName": Granite.I18n.get("Absolute Value Of"), - "args": [ - { - "type": "NUMBER", - "name": "value", - "description": Granite.I18n.get("value"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the absolute value of the provided argument $value."), - "impl": "$0($1)" - }, - { - "id": "avg", - "displayName": Granite.I18n.get("Average Of"), - "args": [ - { - "type": "NUMBER[]", - "name": "elements", - "description": Granite.I18n.get("elements"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the average of the elements in the provided array. An empty array will produce a return value of null."), - "impl": "$0($1)" - }, - { - "id": "ceil", - "displayName": Granite.I18n.get("Ceil"), - "args": [ - { - "type": "NUMBER", - "name": "value", - "description": Granite.I18n.get("value"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the next highest integer value by rounding up if necessary."), - "impl": "$0($1)" - }, - { - "id": "contains", - "displayName": Granite.I18n.get("Contains"), - "args": [ - { - "type": "STRING[]|NUMBER[]|ARRAY|STRING", - "name": "subject", - "description": Granite.I18n.get("subject"), - isMandatory : true - }, - { - "type": "STRING|BOOLEAN|NUMBER|DATE", - "name": "search", - "description": Granite.I18n.get("search"), - isMandatory : true - } - ], - "type": "BOOLEAN", - "description": Granite.I18n.get("Returns true if the given $subject contains the provided $search string. If $subject is an array, this function returns true if one of the elements in the array is equal to the provided $search value. If the provided $subject is a string, this function returns true if the string contains the provided $search argument."), - "impl": "$0($1,$2)" - }, - { - "id": "endsWith", - "displayName": Granite.I18n.get("Ends With"), - "args": [ - { - "type": "STRING", - "name": "subject", - "description": Granite.I18n.get("subject"), - isMandatory : true - }, - { - "type": "STRING", - "name": "prefix", - "description": Granite.I18n.get("prefix"), - isMandatory : true - } - ], - "type": "BOOLEAN", - "description": Granite.I18n.get("Returns true if the $subject ends with the $prefix, otherwise this function returns false."), - "impl": "$0($1,$2)" - }, - { - "id": "floor", - "displayName": Granite.I18n.get("Floor"), - "args": [ - { - "type": "NUMBER", - "name": "value", - "description": Granite.I18n.get("value"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the next lowest integer value by rounding down if necessary."), - "impl": "$0($1)" - }, - { - "id": "length", - "displayName": Granite.I18n.get("Length"), - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|DATE[]|BOOLEAN[]|FILE[]|ARRAY|OBJECT|PANEL", - "name": "subject", - "description": Granite.I18n.get("subject"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the length of the given argument using the following types rules: string: returns the number of code points in the string array: returns the number of elements in the array object: returns the number of key-value pairs in the object: returns the number instances in panel"), - "impl": "$0($1)" - }, - { - "id": "max", - "displayName": Granite.I18n.get("Maximum"), - "args": [ - { - "type": "NUMBER[]|STRING[]", - "name": "collection", - "description": Granite.I18n.get("collection"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the highest found number in the provided array argument. An empty array will produce a return value of null."), - "impl": "$0($1)" - }, - // { - // "id": "maxBy", - // "displayName": "maxBy", - // "args": [ - // { - // "type": "ARRAY", - // "name": "elements", - // "description": "elements" - // }, - // { - // "type": "STRING|NUMBER|BOOLEAN|DATE|ARRAY|OBJECT", - // "name": "expr", - // "description": "expr" - // } - // ], - // "type": "STRING|NUMBER|BOOLEAN|DATE|ARRAY|OBJECT", - // "description": "Return the maximum element in an array using the expression expr as the comparison key. The entire maximum element is returned.", - // "impl": "$0($1,$2)" - // }, - { - "id": "startsWith", - "displayName": Granite.I18n.get("Starts With"), - "args": [ - { - "type": "STRING", - "name": "subject", - "description": Granite.I18n.get("subject"), - isMandatory : true - }, - { - "type": "STRING", - "name": "prefix", - "description": Granite.I18n.get("prefix"), - isMandatory : true - } - ], - "type": "BOOLEAN", - "description": Granite.I18n.get("Returns true if the $subject starts with the $prefix, otherwise this function returns false."), - "impl": "$0($1,$2)" - }, - { - "id": "defaultErrorHandler", - "displayName": Granite.I18n.get("Default Invoke Service Error Handler"), - "args": [ - { - "type": "OBJECT", - "name": "response", - "description": "response", - isMandatory : true - }, - { - "type": "OBJECT", - "name": "header", - "description": "header", - isMandatory : true - } - ], - "type": "ANY", - "isErrorHandler": true, - "description": Granite.I18n.get("Default Invoke Service Error Handler"), - "impl": "$0($1,$2)" - }, - { - "id": "sum", - "displayName": Granite.I18n.get("Sum"), - "args": [ - { - "type": "NUMBER[]", - "name": "collection", - "description": Granite.I18n.get("collection"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the sum of the provided array argument. An empty array will produce a return value of 0."), - "impl": "$0($1)" - }, - { - "id": "min", - "displayName": Granite.I18n.get("Minimum"), - "args": [ - { - "type": "NUMBER[]|STRING[]", - "name": "collection", - "description": Granite.I18n.get("collection"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns the lowest found number in the provided $collection argument."), - "impl": "$0($1)" - }, - // { - // "id": "minBy", - // "displayName": "minBy", - // "args": [ - // { - // "type": "ARRAY", - // "name": "elements", - // "description": "elements" - // }, - // { - // "type": "STRING|STRING[]|NUMBER|NUMBER[]|BOOLEAN|BOOLEAN[]|DATE|DATE[]|ARRAY", - // "name": "expr", - // "description": "expression that returns either a string or a number" - // } - // ], - // "type": "STRING|STRING[]|NUMBER|NUMBER[]|BOOLEAN|BOOLEAN[]|DATE|DATE[]|ARRAY", - // "description": "Return the minimum element in an array using the expression expr as the comparison key. The entire maximum element is returned.", - // "impl": "$0($1,$2)" - // }, - { - "id": "type", - "displayName": Granite.I18n.get("Type"), - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "subject", - "description": Granite.I18n.get("subject"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Returns the JavaScript type of the given $subject argument as a string value. The return value MUST be one of the following: number string boolean array object null"), - "impl": "$0($1)" - }, - { - "id": "keys", - "displayName": Granite.I18n.get("Keys"), - "args": [ - { - "type": "OBJECT", - "name": "obj", - "description": Granite.I18n.get("obj"), - isMandatory : true - } - ], - "type": "STRING[]", - "description": Granite.I18n.get("Returns an array containing the keys of the provided object. If the passed object is null, the value returned is an empty array"), - "impl": "$0($1)" - }, - { - "id": "values", - "displayName": Granite.I18n.get("Values"), - "args": [ - { - "type": "OBJECT", - "name": "obj", - "description": Granite.I18n.get("obj"), - isMandatory : true - } - ], - "type": "STRING[]|NUMBER[]|ARRAY", - "description": Granite.I18n.get("Returns the values of the provided object. Note that because JSON hashes are inheritently unordered, the values associated with the provided object obj are inheritently unordered."), - "impl": "$0($1)" - }, - { - "id": "sort", - "displayName": Granite.I18n.get("Sort"), - "args": [ - { - "type": "NUMBER[]|STRING[]", - "name": "list", - "description": Granite.I18n.get("list"), - isMandatory : true - } - ], - "type": "NUMBER[]|STRING[]", - "description": Granite.I18n.get("This function accepts an array $list argument and returns the sorted elements of the $list as an array. The array must be a list of strings or numbers. Sorting strings is based on code points. Locale is not taken into account."), - "impl": "$0($1)" - }, - // { - // "id": "sortBy", - // "displayName": "sortBy", - // "args": [ - // { - // "type": "ARRAY", - // "name": "elements", - // "description": "elements" - // }, - // { - // "type": "STRING|STRING[]|NUMBER|NUMBER[]|BOOLEAN|BOOLEAN[]|DATE|DATE[]|ARRAY", - // "name": "expr", - // "description": "expr" - // } - // ], - // "type": "ARRAY", - // "description": "Sort an array using an expression expr as the sort key. For each element in the array of elements, the expr expression is applied and the resulting value is used as the key used when sorting the elements. If the result of evaluating the expr against the current array element results in type other than a number or a string, a type error will occur.", - // "impl": "$0($1,$2)" - // }, - { - "id": "join", - "displayName": Granite.I18n.get("Join"), - "args": [ - { - "type": "STRING", - "name": "glue", - "description": Granite.I18n.get("glue"), - isMandatory : true - }, - { - "type": "STRING[]", - "name": "stringsarray", - "description": Granite.I18n.get("stringsarray"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Returns all of the elements from the provided $stringsarray array joined together using the $glue argument as a separator between each."), - "impl": "$0($1,$2)" - }, - { - "id": "reverse", - "displayName": Granite.I18n.get("Reverse"), - "args": [ - { - "type": "STRING|STRING[]|NUMBER[]|ARRAY", - "name": "argument", - "description": Granite.I18n.get("argument"), - isMandatory : true - } - ], - "type": "STRING|STRING[]|NUMBER[]|ARRAY", - "description": Granite.I18n.get("Reverses the order of the $argument."), - "impl": "$0($1)" - }, - { - "id": "toArray", - "displayName": Granite.I18n.get("Convert To Array"), - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|OBJECT", - "name": "arg", - "description": Granite.I18n.get("arg"), - isMandatory : true - } - ], - "type": "STRING[]|NUMBER[]|ARRAY|DATE[]|BOOLEAN[]", - "description": Granite.I18n.get("Converts the passed arg to an array array - Returns the passed in value. number/string/object/boolean - Returns a one element array containing the passed in argument."), - "impl": "$0($1)" - }, - { - "id": "_toString", //toString is a keyword in JavaScript leading to issues in exp-editor - "displayName": Granite.I18n.get("Convert To String"), - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "arg", - "description": Granite.I18n.get("arg"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Converts the passed arg to a string string - Returns the passed in value. number/array/object/boolean - The JSON encoded value of the object."), - "impl": "toString($1)" - }, - { - "id": "toNumber", - "displayName": Granite.I18n.get("Convert To Number"), - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "arg", - "description": Granite.I18n.get("arg"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Converts the passed arg to a number string - Returns the parsed number. number - Returns the passed in value. array - null object - null boolean - null null - null"), - "impl": "$0($1)" - }, - { - id: 'today', - type: 'DATE', - displayName: Granite.I18n.get('Get Current Date'), - args: [], - impl: "$0()", - description: Granite.I18n.get('Returns current date') - }, - /* - { - "id": "notNull", - "displayName": "notNull", - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "argument", - "description": "argument" - } - ], - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY", - "description": "Returns the first argument that does not resolve to null. This function accepts one or more arguments, and will evaluate them in order until a non null argument is encounted. If all arguments values resolve to null, then a value of null is returned.", - "impl": "$0($1)" - },*/ - // { - // "id": "zip", - // "displayName": "zip", - // "args": [ - // { - // "type": "STRING|NUMBER|BOOLEAN|DATE|ARRAY", - // "name": "arrays", - // "description": "array of arrays to zip together" - // } - // ], - // "type": "ARRAY", - // "description": "Returns a convolved (zipped) array containing grouped arrays of values from the array arguments from index 0, 1, 2, etc. This function accepts a variable number of arguments. The length of the returned array is equal to the length of the shortest array.", - // "impl": "$0($1)" - // } - /*{ - "id": "casefold", - "displayName": "casefold", - "args": [ - { - "type": "STRING", - "name": "input", - "description": "string to casefold" - } - ], - "type": "STRING", - "description": "Return a lower-case string using locale-specific mappings. e.g. Strings with German lowercase letter 'ß' can be compared to 'ss'", - "impl": "$0($1)" - },*/ - { - "id": "lower", - "displayName": Granite.I18n.get("To Lower Case"), - "args": [ - { - "type": "STRING", - "name": "input", - "description": Granite.I18n.get("input string"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Converts all the alphabetic characters in a string to lowercase. If the value is not a string it will be converted into string using the default toString method"), - "impl": "$0($1)" - }, - { - "id": "upper", - "displayName": Granite.I18n.get("To Upper Case"), - "args": [ - { - "type": "STRING", - "name": "input", - "description": Granite.I18n.get("input string"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Converts all the alphabetic characters in a string to uppercase. If the value is not a string it will be converted into string using the default toString method"), - "impl": "$0($1)" - }, - { - "id": "exp", - "displayName": Granite.I18n.get("Exponent of"), - "args": [ - { - "type": "NUMBER", - "name": "input", - "description": Granite.I18n.get("number"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Returns e (the base of natural logarithms) raised to a power x"), - "impl": "$0()" - }, - { - "id": "power", - "displayName": Granite.I18n.get("Power of"), - "args": [ - { - "type": "NUMBER", - "name": "a", - "description": Granite.I18n.get("a"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "x", - "description": Granite.I18n.get("x"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Computes `a` raised to a power `x`"), - "impl": "$0($1,$2)" - }, - { - "id": "mid", - "displayName": Granite.I18n.get("Substring Of"), - "args": [ - { - "type": "STRING|ARRAY", - "name": "subject", - "description": Granite.I18n.get("subject"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "startPos", - "description": Granite.I18n.get("startPos"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "length", - "description": Granite.I18n.get("length"), - isMandatory : true - } - ], - "type": "STRING|ARRAY|STRING[]|NUMBER[]|FILE[]|DATE[]|BOOLEAN[]", - "description": Granite.I18n.get("Returns extracted text, given an original text, starting position, and length. or in case of array, extracts a subset of the array from start till the length number of elements. Returns null"), - "impl": "$0($1,$2,$3)" - }, - { - "id": "mod", - "displayName": Granite.I18n.get("Modulo of"), - "args": [ - { - "type": "NUMBER", - "name": "dividend", - "description": Granite.I18n.get("dividend"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "divisor", - "description": Granite.I18n.get("divisor"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Return the remainder when one number is divided by another number."), - "impl": "$0($1,$2)" - }, - { - "id": "proper", - "displayName": Granite.I18n.get("To Uppercase First Letter"), - "args": [ - { - "type": "STRING", - "name": "text", - "description": Granite.I18n.get("text"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Return the input string with the first letter of each word converted to an uppercase letter and the rest of the letters in the word converted to lowercase."), - "impl": "$0($1)" - }, - { - "id": "rept", - "displayName": Granite.I18n.get("Repeat String"), - "args": [ - { - "type": "STRING", - "name": "text", - "description": Granite.I18n.get("text to repeat"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "count", - "description": Granite.I18n.get("number of times to repeat the text"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Return text repeated Count times. rept('x', 5) returns 'xxxxx'"), - "impl": "$0($1,$2)" - }, - { - "id": "replace", - "displayName": Granite.I18n.get("Replace"), - "args": [ - { - "type": "STRING", - "name": "text", - "description": Granite.I18n.get("original text"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "start", - "description": Granite.I18n.get("index in the original text from where to begin the replacement."), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "length", - "description": Granite.I18n.get("number of characters to be replaced"), - isMandatory : true - }, - { - "type": "STRING", - "name": "replacement", - "description": Granite.I18n.get("string to replace at the start index"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Returns text where an old text is substituted at a given start position and length, with a new text."), - "impl": "$0($1,$2,$3,$4)" - }, - { - "id": "round", - "displayName": Granite.I18n.get("Round"), - "args": [ - { - "type": "NUMBER", - "name": "num", - "description": Granite.I18n.get("number to round off"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "precision", - "description": Granite.I18n.get("number is rounded to the specified precision"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Round a number to a specified precision. If precision is not specified, round to the nearest integer"), - "impl": "$0($1,$2)" - }, - { - "id": "sqrt", - "displayName": Granite.I18n.get("Square Root Of"), - "args": [ - { - "type": "NUMBER", - "name": "num", - "description": Granite.I18n.get("number whose square root has to be calculated"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Return the square root of a number"), - "impl": "$0($1)" - }, - { - "id": "trim", - "displayName": Granite.I18n.get("Trim"), - "args": [ - { - "type": "STRING", - "name": "text", - "description": Granite.I18n.get("string to trim"), - isMandatory : true - } - ], - "type": "STRING", - "description": Granite.I18n.get("Remove leading and trailing spaces, and replace all internal multiple spaces with a single space."), - "impl": "$0($1)" - }, - { - "id": "trunc", - "displayName": Granite.I18n.get("Truncate a number"), - "args": [ - { - "type": "NUMBER", - "name": "numA", - "description": Granite.I18n.get("number to truncate"), - isMandatory : true - }, - { - "type": "NUMBER", - "name": "numB", - "description": Granite.I18n.get("number of digits to truncate the number to"), - isMandatory : true - } - ], - "type": "NUMBER", - "description": Granite.I18n.get("Truncate a number to a specified number of digits."), - "impl": "$0($1,$2)" - }, - { - "id": "split", - "displayName": Granite.I18n.get("Split a string into array"), - "args": [ - { - "type": "STRING", - "name": "string", - "description": Granite.I18n.get("string to split"), - isMandatory : true - }, - { - "type": "STRING", - "name": "separator", - "description": Granite.I18n.get("separator where the split should occur"), - isMandatory : true - } - ], - "type": "STRING[]", - "description": Granite.I18n.get("Split a string into an array, given a separator"), - "impl": "$0($1,$2)" - }, - { - "id": "unique", - "displayName": Granite.I18n.get("Unique Values Of"), - "args": [ - { - "type": "ARRAY", - "name": "input", - "description": Granite.I18n.get("input array"), - isMandatory : true - } - ], - "type": "ARRAY|STRING[]|NUMBER[]|DATE[]|BOOLEAN[]", - "description": Granite.I18n.get("Takes an array and returns unique elements within it"), - "impl": "$0($1)" - }, - { - id : '_validateForm', - type : 'BOOLEAN', - displayName : Granite.I18n.get('Validate Form'), - args : [], - impl : 'validate($form).length==0', - description : Granite.I18n.get('Validate Form') - } - ]; - - if (Granite.Toggles.isEnabled("FT_FORMS-13209")) { - functionsConfigJson.push({ - "id": "defaultSubmitSuccessHandler", - "displayName": Granite.I18n.get("Default Submit Form Success Handler"), - "args": [], - "type": "ANY", - "description": Granite.I18n.get("Default Submit Form Success Handler"), - "impl": "$0()" - }, - { - "id": "defaultSubmitErrorHandler", - "displayName": Granite.I18n.get("Default Submit Form Error Handler"), - "args": [ - { - "type": "STRING", - "name": "defaultSubmitErrorMessage", - "description": Granite.I18n.get("Localized error message"), - isMandatory : true - } - ], - "type": "ANY", - "description": Granite.I18n.get("Default Submit Form Error Handler"), - "impl": "$0($1)" - }); - } - - if (Granite.Toggles.isEnabled("FT_FORMS-13519")) { - functionsConfigJson.push({ - id : 'getEventPayload', - type : 'STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|DATE[]|BOOLEAN[]|FILE[]|ARRAY|OBJECT', - displayName : Granite.I18n.get('Get Event Payload'), - args : [{ - "type": "STRING", - "name": "input", - "description": Granite.I18n.get("input param"), - isMandatory : false - }], - impl : '$event.payload.$1', - description : Granite.I18n.get('Get Event Payload') - }); - } - - if (Granite.Toggles.isEnabled("FT_FORMS-19884")) { - functionsConfigJson.push({ - id: "setVariable", - displayName: Granite.I18n.get("Set Variable Value"), - args: [ - { - type: "STRING", - name: "variableName", - description: Granite.I18n.get("Name of the variable (supports dot notation e.g. 'address.city')"), - isMandatory: true - }, - { - type: "STRING|NUMBER|BOOLEAN|DATE|AFCOMPONENT|OBJECT|ARRAY", - name: "variableValue", - description: Granite.I18n.get("Value to set for the variable"), - isMandatory: true - }, - { - type: "AFCOMPONENT|FORM", - name: "normalFieldOrPanel", - description: Granite.I18n.get("Field or panel component to set the variable on (defaults to actual Form)"), - isMandatory: false - } - ], - type: "VOID", - description: Granite.I18n.get("Set variable value on a field or form"), - impl: "$0($1,$2,$3)" - }, - { - id: "getVariable", - displayName: Granite.I18n.get("Get Variable Value"), - args: [ - { - type: "STRING", - name: "variableName", - description: Granite.I18n.get("Name of the variable (supports dot notation e.g. 'address.city')"), - isMandatory: true - }, - { - type: "AFCOMPONENT|FORM", - name: "normalFieldOrPanel", - description: Granite.I18n.get("Field or panel component to get the value from (defaults to actual Form)"), - isMandatory: false - } - ], - type: "STRING|NUMBER|BOOLEAN|DATE|OBJECT|ARRAY|AFCOMPONENT", - description: Granite.I18n.get("Get field or form variable value"), - impl: "$0($1,$2)" - }); - } - - if (Granite.Toggles.isEnabled("FT_FORMS-20002")) { - functionsConfigJson.push({ - id: "exportFormData", - displayName: Granite.I18n.get("Export Form Data"), - args: [ - { - type: "BOOLEAN", - name: "stringify", - description: Granite.I18n.get("Convert the form data to a JSON string, defaults to true"), - isMandatory: false - }, - { - type: "STRING", - name: "key", - description: Granite.I18n.get("The key to get the value for (supports dot notation e.g. 'address.city'), defaults to all form data"), - isMandatory: false - } - ], - type: "STRING|OBJECT", - description: Granite.I18n.get("Export form data as a JSON string"), - impl: "$0($1,$2)" - }, - { - id: "importData", - displayName: Granite.I18n.get("Import Form Data"), - args: [ - { - type: "OBJECT", - name: "data", - description: Granite.I18n.get("The form data to set"), - isMandatory: true - } - ], - type: "VOID", - description: Granite.I18n.get("Import Form Data"), - impl: "importData($1)" - }); - } - - if (Granite.Toggles.isEnabled("FT_FORMS-20129")) { - functionsConfigJson.push({ - id : 'validate', - type : 'BOOLEAN', - displayName : Granite.I18n.get('Validate'), - "args": [ - { - type: "AFCOMPONENT|FORM", - name: "field", - description: Granite.I18n.get("Field, panel or form component to validate"), - isMandatory: true - } - ], - impl : '$0($1).length==0', - description : Granite.I18n.get('Validate') - } - ); - } - - if (Granite.Toggles.isEnabled("FT_FORMS-17789")) { - functionsConfigJson.push({ - id : 'downloadDoR', - type : 'ANY', - displayName : Granite.I18n.get('Download DoR'), - args : [{ - "type": "STRING", - "name": "fileName", - "description": Granite.I18n.get("The name of the file to be downloaded. Defaults to 'Downloaded_DoR.pdf' if not specified."), - isMandatory : false - }], - impl : '$0($1)', - description : Granite.I18n.get('Download DoR') - }); - } - - guidelib.author.FunctionsConfig_v2 = $.extend({}, { - json: functionsConfigJson, - searchKey: "displayName", - displayProps: ["displayName", "description"] - }); - -})(guidelib); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/RuntimeUtil.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/RuntimeUtil.js deleted file mode 100644 index 0b99ad10..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/af-exp-editor/runtime/RuntimeUtil.js +++ /dev/null @@ -1,785 +0,0 @@ -/******************************************************************************* - * ADOBE CONFIDENTIAL - * ___________________ - * Copyright 2016 Adobe Systems Incorporated - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Adobe Systems Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Adobe Systems Incorporated and its - * suppliers and are protected by all applicable intellectual property - * laws, including trade secret and copyright laws. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Adobe Systems Incorporated. - ******************************************************************************/ - -(function (guidelib, _) { - - var RuntimeUtil = guidelib.RuntimeUtil = { - scopeCache : {}, - GrammarStr : JSON.stringify(guidelib.author.Grammar), - SCRIPTS_NODE : "fd:scripts", - RULES_NODE : "fd:rules", - EVENTS_NODE : "fd:events", - SECURE_EVENT_PROPERTY_MAPPING : { - "Calculate" : "fd:calc", - "Visibility" : "fd:visible", - "Initialize" : "fd:init", - "Click" : "fd:click", - "Value Commit" : "fd:valueCommit", - "Enabled" : "fd:enabled", - "Validate" : "fd:validate", - "Format" : "fd:format", - "Completion" : "fd:completion", - "Summary" : "fd:summary", - "Options" : "fd:options", - "Navigation" : "fd:navigationChange", - "Successful Submission" : "fd:submitSuccess", - "Error in Submission" : "fd:submitError", - "Saved successfully" : "fd:saveSuccess", - "Error while saving the form" : "fd:saveError", - - // Communication Composer events - "Layout Ready" : "fd:layoutReady", - "Form Ready" : "fd:formReady", - "Doc Ready" : "fd:docReady" - }, - - - /** - * The mapping is to specify the property name to be used to store the script for consumption by - * runtime - */ - EVENT_PROPERTY_MAPPING : { - "Calculate" : "calcExp", - "Visibility" : "visibleExp", - "Initialize" : "initScript", - "Click" : "clickExp", - "Value Commit" : "valueCommitScript", - "Enabled" : "enabledExp", - "Validate" : "validateExp", - "Format" : "formatExp", - "Completion" : "completionExp", - "Summary" : "summaryExp", - "Options" : "optionsExp", - "Navigation" : "navigationChangeExp", - "Successful Submission" : "submitSuccess", - "Error in Submission" : "submitError", - "Saved successfully" : "saveSuccess", - "Error while saving the form" : "saveError", - - // Communication Composer events - "Layout Ready" : "layoutReady", - "Form Ready" : "formReady", - "Doc Ready" : "docReady" - }, - - /** - * converts old script properties into SCRIPTMODEL. Only used for migration of forms where JavaScript - * was saved in JCR. - * @param nodeProperties - * @param id - * @returns {{nodeName: string, items: *[]}} - * @private - */ - _scriptPropertiesToExpJson : function (nodeProperties, id) { - var items = []; - _.each(RuntimeUtil.EVENT_PROPERTY_MAPPING, function (eventPropertyName, eventName) { - var scriptContent = nodeProperties[eventPropertyName]; - if (typeof scriptContent !== "undefined") { - var model = { - nodeName : "SCRIPTMODEL", - script : { - field : id, - event : eventName, - content : scriptContent - }, - // marking it as old version - version : 0 - }; - items.push(model); - } - }); - if (items.length > 0) { - return { - nodeName : "RULES", - items : items - }; - } - }, - - /** - * This function handles a unique case during migration - * where for a given event a script object occurs before rule object - * in which case all rules after first script object are converted to - * script objects - */ - _migrateSingleEventRulesAndScripts : function (rules, id) { - var hasScriptAppeared = false; - return rules.map(function (model) { - if (hasScriptAppeared) { - if (model.nodeName != 'SCRIPTMODEL') { - return { - nodeName : 'SCRIPTMODEL', - script : { - field : id, - event : model.eventName, - content : model.script - } - }; - } else { - return model; - } - } else { - if (model.nodeName == 'SCRIPTMODEL') { - hasScriptAppeared = true; - } - return model; - } - }); - }, - - /** - * determines when migration is required - * migration is required only if any of the legacy - * properties are found - */ - isMigrationRequired : function (nodeProperties) { - var legacyProperties = RuntimeUtil.EVENT_PROPERTY_MAPPING; - var isAnyScriptPropertyPresent = _.some(Object.keys(legacyProperties), function (key) { - return typeof(nodeProperties[legacyProperties[key]]) != "undefined"; - }); - return isAnyScriptPropertyPresent || typeof(nodeProperties.expJson) != "undefined" ; - }, - - /** - * Given rules and scripts grouped by events - * separates rules and script - */ - _splitRulesAndScripts : function (rulesAndScripts) { - - var obj = {}; - - obj[RuntimeUtil.RULES_NODE] = _.mapValues(rulesAndScripts, function (models) { - return models.filter(function (model) { - return model.nodeName != 'SCRIPTMODEL'; - }); - }); - - obj[RuntimeUtil.SCRIPTS_NODE] = _.mapValues(rulesAndScripts, function (models) { - return models.filter(function (model) { - return model.nodeName == 'SCRIPTMODEL'; - }); - }); - - return obj; - - }, - /** - * takes an array of rule json models and - * groups them by events - * input : [ - * {nodeName:'ROOT',eventName:'Calculate', items:...}, - * {nodeName:'SCRIPTMODEL',script:{event:'Value Commit',content:"..."}}, - * {nodeName:'ROOT',eventName:'Value Commit', items:...} - * ] - * output: - * { - * calc:[{nodeName:'ROOT',eventName:'Calculate', items:...}] - * valueCommit:[{nodeName:'SCRIPTMODEL',script:{event:'Value Commit',content:"..."}}, - * {nodeName:'ROOT',eventName:'Value Commit', items:...}] - * } - */ - _groupModelsByEvents : function (modelsJson) { - return _.groupBy(modelsJson, function (modelJson) { - var eventName = modelJson.nodeName == 'SCRIPTMODEL' ? modelJson.script.event : modelJson.eventName; - var event = RuntimeUtil.SECURE_EVENT_PROPERTY_MAPPING[eventName]; - if (event) { - return event; - } - if (eventName && eventName.startsWith('custom:')) { - event = eventName.replace('custom:', 'fd:'); - } - return event; - }); - }, - /** - * Returns true if for any event a visual rule is found after script - * Called from server - */ - hasOrderConflict : function (nodeProperties) { - var expJson = nodeProperties.expJson; - if (!expJson) { // with no expJson we cannot have an order conflict - return false; - } - var expJsonObj = null; - try { - expJsonObj = JSON.parse(expJson); - } catch (error) { - console.error("Error while parsing expJson"); - return false; - } - var rules = expJsonObj.items || []; - var modelsByEvents = RuntimeUtil._groupModelsByEvents(rules); - var orderConflictFound = _.some(_.values(modelsByEvents), function (rulesForAnEvent) { - var hasScriptAppeared = false; - var conflict = false; - _.each(rulesForAnEvent, function (model) { - if (model.nodeName == 'SCRIPTMODEL') { - hasScriptAppeared = true; - } else if (hasScriptAppeared) { - conflict = true; - } - }); - return conflict; - }); - - return orderConflictFound; - }, - /** - * Can be called from server to migrate component to new format - */ - migrateComponent : function (nodeProperties, id) { - var expJson = nodeProperties.expJson; - if (!expJson) { - expJson = RuntimeUtil._scriptPropertiesToExpJson(nodeProperties, id); - } else { - expJson = JSON.parse(expJson); - } - var modelsByEvents = RuntimeUtil._groupModelsByEvents(expJson.items); - var migratedModels = _.mapValues(modelsByEvents, function (models) { - return RuntimeUtil._migrateSingleEventRulesAndScripts(models, id); - }); - var rulesAndScripts = RuntimeUtil._splitRulesAndScripts(migratedModels); - return RuntimeUtil._stringifyEachModel(rulesAndScripts); - }, - - /** - * Extract out the values of the rules object and creates a big array containing all of them. Equivalent of - * `Object.values(rules).flatten` But we cannot do that since it is not supported in JavaScript - * @param rules - * @returns {*[]} - * @private - */ - _mergeGroupedValues : function (rules) { - var events = Object.keys(rules); - var allRules = events.map(function (e) { - return rules[e]; - }); - return [].concat.apply([], allRules); - }, - _stringifyEachModel : function (rulesAndScript) { - return _.mapValues(rulesAndScript, function (rulesOrScripts) { - return _.mapValues(rulesOrScripts, function (models) { - models = _.isArray(models) ? models : []; - return models.map(function (model) { - return JSON.stringify(model); - }); - }); - }); - }, - /** - * parses each element in the array to JSON. - * @param models - * @returns {*} - * @private - */ - _parseEachModel : function (models) { - return models.map(function (model) { - if (typeof model === "string") { - return JSON.parse(model); - } - return model; - }); - }, - - _getExpJson : function (rules, scripts, props) { - var validKeys = _.values(RuntimeUtil.SECURE_EVENT_PROPERTY_MAPPING); - var rules = _.pickBy(rules || {}, function(value, key) { - return validKeys.indexOf(key) !== -1 || key.startsWith('fd:'); - }); - var scripts = _.pickBy(scripts || {}, function(value, key) { - return validKeys.indexOf(key) !== -1 || key.startsWith('fd:'); - }); - if (Object.keys(rules).length > 0 || Object.keys(scripts).length > 0) { - var mergedRules = RuntimeUtil._mergeGroupedValues(rules); - mergedRules = RuntimeUtil._parseEachModel(mergedRules); - // filter rules and scripts and discard any script objects - var filteredRules = mergedRules.filter(function (model) { - return model.nodeName != 'SCRIPTMODEL'; - }); - var mergedScripts = RuntimeUtil._mergeGroupedValues(scripts); - mergedScripts = RuntimeUtil._parseEachModel(mergedScripts); - - var allRulesAndScripts = filteredRules.concat(mergedScripts); - return { - nodeName : "RULES", - items : allRulesAndScripts - }; - - } else { - //converting scripts and rules saved directly as javascript in JCR - var items = []; - if (!_.isUndefined(props)) { - _.each(RuntimeUtil.EVENT_PROPERTY_MAPPING, function (eventPropertyName, eventName) { - var scriptContent = props[eventPropertyName]; - if (typeof scriptContent !== "undefined") { - var model = { - nodeName : "SCRIPTMODEL", - script : { - event : eventName, - content : scriptContent - }, - // marking it as old version - version : 0 - }; - items.push(model); - } - }); - } - - return { - nodeName : "RULES", - items : items - }; - } - }, - - prepareContext : function (fieldData, treeJson, path, guideNodeClass, formPath) { - if (typeof treeJson == "string") { - treeJson = JSON.parse(treeJson); - } - treeJson.items = [treeJson.rootPanel]; - treeJson.rootPanel = null; - var element = this._getElement(path, treeJson); - var options = { - completionExpReq : fieldData.completionExpReq, - summaryExpVisible : fieldData.summaryExpVisible === 'yes', - elementType : element && element.type ? element.type.split("|") : [] - }; - var eventsAndExpressions = this._getEventsAndExpressionList(guideNodeClass, options); - var config = this.createConfig(eventsAndExpressions, treeJson, path); - var rbScope = RuntimeUtil.scopeCache[formPath] = (RuntimeUtil.scopeCache[formPath] || this.createScope(treeJson, guidelib.author.TypesConfig)); - var eeContext = new expeditor.ExpEditorContext(config, null, {}); - eeContext.setScope(rbScope); - - return eeContext; - }, - - /** - * converts fd:rules and fd:scripts into JavaScript to be consumed by browser at server. - * Only evaluated on server using Rhino - * @param eeContext - * @param rules - * @param scripts - * @param transformer - * @param bJsonFormula - * @returns {{}} - */ - getScripts : function (eeContext, rules, scripts, transformer, bJsonFormula) { - var expJson = RuntimeUtil._getExpJson(rules, scripts, true); - transformer.setContext(eeContext); - - var listModel = new expeditor.model.ListModel('RULES', eeContext); - listModel = listModel.fromJson(expJson); - - var merger = bJsonFormula === true ? guidelib.author.AFJSONFormulaMerger : guidelib.author.scriptMerger; - - var mergedScripts = merger.mergeScript(expeditor.Utils.listModelToScript(listModel, transformer)); - var events = mergedScripts[Object.keys(mergedScripts)[0]]; - - var properties = {}; - _.each(events, function (script, evntName) { - properties[guidelib.RuntimeUtil.EVENT_PROPERTY_MAPPING[evntName]] = script.content.toString(); - }); - return properties; - }, - - /** - * Sets the enabled FTs for runtime - * @param enabledFT comma separated list of enabled FTs, to be used in runtime. Granite.Toggles.enabledToggle is hardcoded and loaded in StaticScriptsManager in cq-guides - */ - enableFeatureToggles : function (enabledFT) { - try { - if(enabledFT !== undefined && enabledFT !== null){ - var enabledFTs = enabledFT.split(","); - for (var i = 0; i < enabledFTs.length; i++) { - window.Granite.Toggles.enableToggle(enabledFTs[i]); - } - } - } catch(err) { - console.error("Error while processing enabledFT: "+JSON.stringify(enabledFT)+", Error: "+JSON.stringify(err)); - } - }, - - /** - * Converts Adaptive Form Rules To Scripts/JSON Formula Expression - * @param fieldData {completionExpReq: boolean, summaryExpVisible: enum("yes", "no")} - * @param treeJson - * @param path - * @param guideNodeClass - * @param rules - * @param scripts - * @param formPath - * @param bindRefToAFNameMap - * @param bJsonFormula whether to generate json formula or javascript - * @returns {{}} - */ - jsonToScripts : function (fieldData, - treeJson, - path, - guideNodeClass, - rules, - scripts, - formPath, - bindRefToAFNameMap, - bJsonFormula) { - guidelib.RuntimeUtil.bindRefToAFNameMap = bindRefToAFNameMap; - var eeContext = this.prepareContext(fieldData, treeJson, path, guideNodeClass, formPath); - bJsonFormula = bJsonFormula || false - var transformer = bJsonFormula ? new guidelib.author.AFJSONFormulaTransformer() : - new guidelib.author.AFTransformer(); - return this.getScripts(eeContext, rules, scripts, transformer, bJsonFormula); - }, - - createScope : function (treeJson, typesConfig) { - var rbScope = new expeditor.rb.RBScope({ - varStorage : "guidelib.author.TrieStorage" - }); - var treeProcessor = new expeditor.TreeProcessor(treeJson); - var flatModel = treeProcessor.getFlatModel(); - rbScope.addVars(flatModel); - rbScope.addTypes(typesConfig || {}); - return rbScope; - }, - - removeFormRelatedActionsFromExpEditor : function () { - var grammar = JSON.parse(RuntimeUtil.GrammarStr); - // we don't support form related actions in web channel as part of block statement - grammar.BLOCK_STATEMENT.rule = grammar.BLOCK_STATEMENT.rule.replace("SAVE_FORM | SUBMIT_FORM | RESET_FORM | VALIDATE_FORM |", ""); - grammar.BLOCK_STATEMENT.rule = grammar.BLOCK_STATEMENT.rule.replace("SET_VALUE_STATEMENT |", ""); - grammar.BLOCK_STATEMENT.rule = grammar.BLOCK_STATEMENT.rule.replace("CLEAR_VALUE_STATEMENT |", ""); - // store the new grammar - RuntimeUtil.GrammarStr = JSON.stringify(grammar); - }, - - createConfig : function (eventsAndExpressions, treeJson, path, isV2, grammar) { - var _isV2 = isV2 === true; - var grammarString = grammar; - if (!grammarString) { - grammarString = _isV2 ? JSON.stringify(guidelib.author.Grammar_v2) : - RuntimeUtil.GrammarStr; - } - var configurator = new expeditor.rb.RuleBuilderConfigurator() - - - var operators = configurator.getDefaultOperators() - if (_isV2) { - operators.push('CONCAT') - } - var configBuilder = configurator.addGrammar(grammarString) - .addStatement(eventsAndExpressions.statements) - .addChoice("EVENT_AND_COMPARISON_OPERATOR", eventsAndExpressions.events) - .enableOperator(operators) - .addChangeListener('ROOT', 'guidelib.author.ExpressionEditorUtil.eventChangeListener') - .addChangeListener('EVENT_SCRIPTS', 'guidelib.author.ExpressionEditorUtil.eventChangeListener') - .addChangeListener('TRIGGER_EVENT_SCRIPTS', 'guidelib.author.ExpressionEditorUtil.eventChangeListener') - //configBuilder = configBuilder.addChoice("BLOCK_STATEMENT", "DISPATCH_EVENT") - - if (!expeditor.rb.FeatureToggles.isCommComposerChannel()) { - configBuilder = configBuilder.addChoice("EVENT_AND_COMPARISON_OPERATOR", eventsAndExpressions.events); - configBuilder = configBuilder.addChoice("EXPRESSION", "WSDL_VALUE_EXPRESSION"); - configBuilder = configBuilder.addChoice("BLOCK_STATEMENT", "DISPATCH_EVENT"); - } - - var config = configBuilder.getConfig(); - eventsAndExpressions.expressions = ["EVENT_AND_COMPARISON"]; - - if(expeditor.rb.FeatureToggles.isCommComposerChannel()) { - eventsAndExpressions.expressions.push("SINGLE_TRIGGER_SCRIPTS"); - } - - if (Granite.Toggles.isEnabled('FT_FORMS-19582')) { - eventsAndExpressions.expressions.push("EVENT_AND_COMPARISON_LEFT_HAND_EXPRESSION"); - } - /* - ideally, element will never be null but some customer forms have components - at wrong place e.g. under layout node, adding default value to avoid NPE - see CQ-4209436 - */ - var element = this._getElement(path, treeJson) || { - id : "", - type : "", - name : "" - } - if (_isV2 && !expeditor.rb.FeatureToggles.isCommComposerChannel()) { - config = guidelib.author.ConfigUpdater.updateGrammar(config, treeJson.adaptiveFormVersion); - } - else if(expeditor.rb.FeatureToggles.isCommComposerChannel()){ - config = guidelib.author.ConfigUpdater.updateGrammarForCommComposer(config); - } - config = guidelib.author.ConfigUpdater.appendCurrentFieldJsonInExpressionGrammar(element, - eventsAndExpressions, - config, _isV2); - return config; - }, - /** - * Returns the element with the given path in the JSON - * @param path - * @param json - * @returns {*} - * @private - */ - _getElement : function (path, json) { - if (json.path == path) { - return json; - } - if (json.items) { - var returnJson = null; - _.find(json.items, function (item, index) { - returnJson = RuntimeUtil._getElement(path, item); - return returnJson != null; - }); - if (returnJson) { - return returnJson; - } - } - if (json.toolbar) { - return RuntimeUtil._getElement(path, json.toolbar); - } - }, - - /** - * Return event list from an editable. Currently it is hard coded, but would have been best to get it from - * server. Need to figure out a way for doing that. - * @param guideNodeClass - * @param options - * @private - */ - _getEventsAndExpressionList : function (guideNodeClass, options, isV2) { - if(isV2 && expeditor.rb.FeatureToggles.isCommComposerChannel()) { - return guidelib.author.ExpressionList.commComposer(guideNodeClass, options); - } - return isV2 === true ? guidelib.author.ExpressionList.v2(guideNodeClass, options) : - guidelib.author.ExpressionList.v1(guideNodeClass, options) - }, - /* - * Fixes SOM Expression by correctly putting indices (0) where not present. - * - */ - _fixSomExpression : function (som) { - if (typeof som === "string") { - if (som.length === 0) { - return som; - } - return som.replace(/\.|$/g, function (match, offset, str) { - var prevCharacter = str[offset - 1]; - if (prevCharacter !== "]" && prevCharacter !== "\\") { - return "[0]" + match; - } - return match; - }); - - } - return som; - }, - - _removeIndexFromSom : function (som) { - if (typeof som === "string") { - return som.replace(/\[[0-9]+\]/g, ""); - } - return som; - }, - - getRelativeName : function (id, relativeTo, scope) { - if (id === relativeTo) { - return "this"; - } - if (id.indexOf(".") === -1) { - // case it is guide, otherwise this case will never occur - return this._getRuntimeId(id); - } - if (scope !== null) { - var def = scope.findVarById(id); - if (def === null) { - return this._getRuntimeId(id); - } else { - if (def.foundId !== id) { - id = def.foundId; - } - } - id = scope.findUniqueVarId(id); - } - // if id contains an index like [1] or [10], remove them - if (id.match(/\[[1-9][0-9]*\]/)) { - id = this._fixSomExpression(id); - if (console) { - console.warn("Same named siblings are not supported"); - } - var id1 = this._removeIndexFromSom(id); - // this is not supported, but if it happens we need to add zeros - return this._getRuntimeId(id1); - } else if (scope === null) { - // it should never happen though - var currentFieldIdArray = relativeTo.split("."), - bMisMatch = false, - shortName = id.split(".").filter(function (item, index) { - var bMisMatchId = bMisMatch || (bMisMatch = currentFieldIdArray[index] !== item); - return bMisMatchId; - }).join("."); - if (shortName.length === 0) { - id = id.substring(id.lastIndexOf(".") + 1); - } - } - return this._getRuntimeId(id); - }, - - /** - * As JS doesn't understand variable with hyphen in it. So, encapsulating it to an resolveNode. - * ResolveNode takes this relative name as input and returns relevant forms component. - * @param id - * @returns id Id in resolve - * @private - */ - _getRuntimeId : function (id) { - if (id.indexOf("-") > -1) { - id = "guideBridge.resolveNode(\"" + id + "\")"; - } - return id; - }, - - isValueCommit : function (condition) { - if (expeditor.Utils.getOrElse(condition, "choiceModel.nodeName", null) == "EVENT_AND_COMPARISON") { - var event_and_comparison = condition.choiceModel; - if (event_and_comparison) { - var operatorModel = event_and_comparison.items[1]; - var operator = expeditor.Utils.getOrElse(operatorModel, 'choiceModel.nodeName', null); - if (operator && guidelib.RuntimeUtil.eventToEventName.hasOwnProperty(operator)) { - return false; - } - } - } - return true; - }, - - /* Checks if the condition is only an event. */ - isConditionOnlyAnEvent : function (condition) { - if (expeditor.Utils.getOrElse(condition, "choiceModel.nodeName", null) == "EVENT_AND_COMPARISON") { - var event_and_comparison = condition.choiceModel; - if (event_and_comparison) { - var operatorModel = event_and_comparison.items[1]; - var operator = expeditor.Utils.getOrElse(operatorModel, 'choiceModel.nodeName', null); - if (operator && guidelib.RuntimeUtil.eventToEventName.hasOwnProperty(operator)) { - return true; - } - } - } - return false; - }, - - /* Returns the event if any is present in condition model. Returns null otherwise */ - getEventFromCondition : function (conditionModel) { - if (expeditor.Utils.getOrElse(conditionModel, "nodeName", null) != "EVENT_CONDITION") { - return null; - } - if (expeditor.Utils.getOrElse(conditionModel, "choiceModel.nodeName", null) == "EVENT_AND_COMPARISON") { - var event_and_comparison = conditionModel.choiceModel; - if (event_and_comparison) { - var operatorModel = event_and_comparison.items[1]; - var operator = expeditor.Utils.getOrElse(operatorModel, 'choiceModel.nodeName', null); - if (RuntimeUtil.eventToEventName.hasOwnProperty(operator)) { - return operator; - } - return null; - } - } else if (expeditor.Utils.getOrElse(conditionModel, "choiceModel.nodeName", null) == "BINARY_EVENT_CONDITION") { - var binaryEventCondition = expeditor.Utils.getOrElse(conditionModel, "choiceModel", null); - if (binaryEventCondition) { - var condition1Event = this.getEventFromCondition(binaryEventCondition.items[0]); - var condition2Event = this.getEventFromCondition(binaryEventCondition.items[2]); - return condition1Event || condition2Event; - } - } - }, - - setCurrentEventField : function (model) { - if (expeditor.Utils.getOrElse(model, "choiceModel.nodeName", null) == "BINARY_EVENT_CONDITION") { - var binaryEventCondition = expeditor.Utils.getOrElse(model, "choiceModel", null); - if (binaryEventCondition) { - if (expeditor.Utils.getOrElse(binaryEventCondition.items[0], "choiceModel.nodeName", null) == "EVENT_AND_COMPARISON") { - var eventAndComparison = expeditor.Utils.getOrElse(binaryEventCondition.items[0], "choiceModel", null); - if (eventAndComparison) { - if (Granite.Toggles.isEnabled('FT_FORMS-19582') && eventAndComparison.items[0].nodeName === 'EVENT_AND_COMPARISON_LEFT_HAND_EXPRESSION') { - return eventAndComparison.items[0].choiceModel.getValue().id; - } else if (eventAndComparison.items[0].nodeName === 'COMPONENT') { - return eventAndComparison.items[0].getValue().id; - } - } - } - } - } - return null; - }, - - modifyRepeatablePanelFieldId : function (fieldId) { - var openParenCount = 0; - var foundParentheses = false; - var balancedStartIndex = 0; - var balancedLastIndex = -1; - - for (var i = fieldId.length - 1; i >= 0; i--) { - if (fieldId[i] === ']') { - foundParentheses = true; - openParenCount++; - balancedLastIndex = balancedLastIndex === -1 ? i : balancedLastIndex; - } else if (fieldId[i] === '[') { - openParenCount--; - } - - // If counts are equal, we found last balanced pair of parentheses - if (openParenCount === 0 && foundParentheses) { - balancedStartIndex = i+1; - break; - } - } - - var stringToReplace = fieldId.substring(balancedStartIndex, balancedLastIndex); - - if (foundParentheses) { - fieldId = fieldId.replace(stringToReplace, '*'); - } - - return fieldId; - }, - - /** - * escapes the scriptContent and encloses it an eval. Returns the final string - * @param scriptContent scriptContent to escape and put inside eval - * @returns {string} returns the scriptContent embedded inside eval - */ - putScriptContentInEval : function (scriptContent) { - return 'eval("' + scriptContent.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") - .replace(/\r/g, "\\r").replace(/\n/g, "\\n") + '")'; - }, - - eventToEventName : { - "is initialized" : "Initialize", - "is clicked" : "Click", - "is changed" : "Value Commit", - "is submitted successfully" : "Successful Submission", - "submission fails" : "Error in Submission", - "is saved successfully" : "Saved successfully", - "fails to save" : "Error while saving the form" - // "is layout ready" : "Layout Ready", - // "is form ready" : "Form Ready", - // "is doc ready" : "Doc Ready" - }, - - DEFAULT_EVENT : "is changed", - - SCRIPT_INDENT : " " - - }; -})(guidelib, fd._); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/BaseTransformer.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/BaseTransformer.js deleted file mode 100644 index 6ddd17fc..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/BaseTransformer.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @package com.adobe.expeditor.rb.BaseTransformer - */ -(function (expeditor) { - var machine_generated_script_prefix = "/**\n", - machine_generated_script_suffix = "\n * This is a machine-generated code for the rule.\n" + - " * If you modify it in the code editor, you will not be able to view and edit the rule in the visual editor.\n" + - " */\n\n"; - var BaseTransformer = expeditor.rb.BaseTransformer = expeditor.Class.extend({ - - CODE_EDITOR_MODE : 0, - MERGE_MODE : 1, - - init : function () { - this.reset(); - this.bAddCopyRightHeader = true; - this.mode = this.CODE_EDITOR_MODE; - this.copyrightMessage = ""; - }, - - setContext : function (ctx) { - this.ctx = ctx; - }, - - setMode : function (mode) { - if (mode === this.CODE_EDITOR_MODE || mode === this.MERGE_MODE) { - this.mode = mode; - } - }, - - setAddCopyrightHeader : function (bAddCopyrightHeader) { - this.bAddCopyRightHeader = bAddCopyrightHeader; - }, - - setCopyrightMessage : function (message) { - this.copyrightMessage = message; - }, - - getCopyrightHeader : function () { - return machine_generated_script_prefix + this.copyrightMessage + machine_generated_script_suffix; - }, - - write : function (str) { - if (str != null) { - this.script += str; - } - return this; - }, - - writeLn : function (str) { - this.write(str); - this.write("\n"); - return this; - }, - - getScript : function () { - return { - content : this.script - }; - }, - - newScript : function () { - if (this.bAddCopyRightHeader) { - this.script = this.getCopyrightHeader(); - } - return this; - }, - - reset : function () { - this.script = ""; - this.bAddCopyRightHeader = true; - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/RBScope.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/RBScope.js deleted file mode 100644 index d022468b..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/RBScope.js +++ /dev/null @@ -1,234 +0,0 @@ -/** - * @package com.adobe.expeditor.rb.RBScope - * @import com.adobe.expeditor.rb.FeatureToggle - * Defines scope for rule builder - * All variables and functions are defined using this scope - */ -(function (expeditor, window) { - var RBScope = expeditor.rb.RBScope = expeditor.Class.extend({ - /** - * constructor to initialize scope - * config structure is as follows - * var config ={ - * vars:{ - * "i":{name:"i",type:"NUMBER",disabled:true}, - * "name":{name:"name",type:"STRING"} - * }, - * funcs:{ - * "sum":{ - * name:"sum", - * type:"NUMBER", - * args:[] - * {name:"panel",type:"PANEL",description:"Select a panel"}, - * {name:"field",type:"NUMBER",description:"Select a field"} - * ], - * impl : "$0($1,$2)" // optional, where $0 is the function id, $1, $2 are param ids - * }, - * }, - * types:{ - * 'NUMBER FIELD':{ - * inherits:'FIELD', - * vars:{ - * 'value':{name:"value",type:'NUMBER'} - * } - * } - * } - * } - */ - init : function (config) { - this.clearVars(); - var _config = config || {}; - var functionStorage = _config.funcStorage || "expeditor.rb.MapStorage"; - var varStorage = _config.varStorage || "expeditor.rb.MapStorage"; - var storageClass = expeditor.Utils.getOrElse(window, varStorage, expeditor.rb.MapStorage); - this.varsById = new storageClass(); - storageClass = expeditor.Utils.getOrElse(window, functionStorage, expeditor.rb.MapStorage); - this.funcById = new storageClass(); - this.funcsByType = {}; - this.types = {}; - if (config) { - this.addVars(config.vars); - this.addFunctions(config.funcs); - this.addTypes(config.types); - } - }, - - clearVars : function () { - if (this.varsById) { - this.varsById.clear(); - } - this.varsByType = {}; - }, - - addVars : function (vars) { - if (vars) { - for (var varId in vars) { - if (vars.hasOwnProperty(varId)) { - var def = vars[varId]; - if (def !== null) { - this.defineVariable(new expeditor.rb.VariableDefinition(varId, def.displayName, def.type, - def.displayPath, def.isDuplicate, def.name, def.options, def.parent, def.disabled, def.metadata)); - } - if (varId === '$form' && def.metadata && def.metadata.isFragment) { - def = { - id : "$globalForm", - displayName : "FORM", - displayPath : "FORM/", - name : "FORM", - type : "FORM" - }; - this.defineVariable(new expeditor.rb.VariableDefinition(def.id, def.displayName, def.type, - def.displayPath, def.isDuplicate, def.name, def.options, def.parent, def.disabled, def.metadata)); - } - } - } - } - }, - - addFunctions : function (funcs) { - if (funcs) { - for (var funcId in funcs) { - var def = funcs[funcId]; - this.defineFunction(new expeditor.rb.FunctionDefinition(funcId, def.displayName, def.type, - def.args, def.impl, def.name, def.isErrorHandler)); - } - } - }, - - addTypes : function (types) { - if (types) { - for (var typeId in types) { - var def = types[typeId]; - var newDef = {}; - var newVars = {}; - if (def.inherits) { - var parentType = this.types[def.inherits]; - var parentFields = parentType.vars; - newVars = expeditor.Utils.extend(true, newVars, parentType.vars); - } - newVars = expeditor.Utils.extend(true, newVars, def.vars); - newDef.inherits = def.inherits; - newDef.vars = newVars; - this.types[typeId] = newDef; - } - } - }, - - _defineVarOrFunc : function (variable, varOrFunc) { - var idStore = this._getIdStore(varOrFunc); - var typeStore = this._getTypeStore(varOrFunc); - var id = variable.getId(); - var type = variable.getType(); - if (!id || !type) { - throw new Error("Error Defining " + variable + " id and type are required"); - } - idStore.addElement(id, variable); - var types = type.split("|").forEach(function (varType) { - var trimmedType = varType.trim(); - (typeStore[trimmedType] = typeStore[trimmedType] || []).push(variable); - }, this); - }, - - defineVariable : function (variable) { - this._defineVarOrFunc(variable, "var"); - }, - - defineFunction : function (func) { - this._defineVarOrFunc(func, "func"); - }, - - _getIdStore : function (varOrFunc) { - return varOrFunc === "var" ? this.varsById : this.funcById; - }, - - _getTypeStore : function (varOrFunc) { - return varOrFunc === "var" ? this.varsByType : this.funcsByType; - }, - - _getAll : function (varOrFunc) { - var store = this._getIdStore(varOrFunc); - return store.getAll(); - }, - - _getAllFunctions : function () { - return this._getAll("func"); - }, - - _getAllVars : function () { - return this._getAll("var"); - }, - - getMatchingPromiseType : function (type, typeStore) { - var variables = []; - if (type.toLowerCase() === 'promise') { - Object.entries(typeStore).forEach(function (e) { - if (e[0].startsWith(type) && //Promise<*> or Promise<{}> or Promise<a[]> or Promise<{a:string, b:string[]}> - !e[0].match(/\[]$|^[]/)) { - variables = variables.concat(e[1]); - } - }); - } else { - variables = typeStore[type]; - } - return variables; - }, - - findByType : function (types, varOrFunc) { - if (types.length == 0) { - return []; - } - var typeStore = this._getTypeStore(varOrFunc); - var typesArray = types.split("|"); - if (typesArray.indexOf("ANY") > -1) { - return this._getAll(varOrFunc); - } else { - var idsAdded = {}, returnVars = [], i = 0; - for (; i < typesArray.length; i++) { - var type = typesArray[i].trim(), - variables = expeditor.rb.FeatureToggles.isPromisesEnabled() ? - this.getMatchingPromiseType(type, typeStore) : typeStore[type], - j = 0; - if (variables instanceof Array) { - for (; j < variables.length; j++) { - var variable = variables[j]; - if (typeof idsAdded[variable.getId()] === "undefined") { - returnVars.push(variable); - } - } - } - - } - return returnVars; - } - }, - - findVarByType : function (types) { - return this.findByType(types, "var"); - }, - - findFunctionsByType : function (types) { - return this.findByType(types, "func"); - }, - - findVarById : function (id) { - return this.varsById.get(id); - }, - - findFunctionById : function (id) { - return this.funcById.get(id); - }, - - findById : function (id, varOrFunc) { - var store = this._getIdStore(varOrFunc); - return store.get(id); - }, - - getAllTypes : function () { - return this.types; - }, - - findUniqueVarId : function (id) { - return this.varsById.getUniqueId(id); - } - }); -})(expeditor, this); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/ToJsonFormulaTransformer.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/ToJsonFormulaTransformer.js deleted file mode 100644 index 0c3b3b1d..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/ToJsonFormulaTransformer.js +++ /dev/null @@ -1,304 +0,0 @@ -/** - * @import com.adobe.expeditor.rb.BaseTransformer - * @package com.adobe.expeditor.rb.ToJsonFormulaTransformer - */ -(function (expeditor) { - - // todo: add 'HAS_SELECTED': - var OperatorToFnMapping = { - 'CONTAINS' : 'contains', - 'STARTS_WITH' : 'startsWith', - 'ENDS_WITH' : 'endsWith', - 'DOES_NOT_CONTAIN' : '!contains' - }; - - var ToJsonFormulaTransformer = expeditor.rb.ToJsonFormulaTransformer = expeditor.rb.BaseTransformer.extend({ - - init : function () { - this._super.apply(this); - this.bAddCopyRightHeader = false; - }, - - enterROOT : function (model) { - this.reset(); - this.newScript(); - }, - - exitSTATEMENT : function (model) { - - }, - - exitBLOCK_STATEMENT : function (model) { - - }, - - enterIF_STATEMENT : function (model) { - this.write("if("); - model.items[0].accept(this); - this.write(", "); - model.items[2].accept(this); - this.write(", {})"); - return true; - }, - - enterSET_VALUE_STATEMENT : function (model) { - model.items[0].accept(this); - this.write(" = "); - model.items[2].accept(this); - return true; - }, - - enterBINARY_EXPRESSION : function (model) { - this.write("("); - return this._handleUnaryOperators(model) || this._handleFunctionalOperator(model); - }, - - exitBINARY_EXPRESSION : function (model) { - this.write(")"); - }, - - enterSTARTS_WITH : function (model) { - throw "should be handled by the parent model"; - }, - - enterHAS_SELECTED : function (model) { - throw "should be handled by the parent model"; - }, - - enterIS_TRUE : function (model) { - this.write(" == true() "); - }, - - enterIS_FALSE : function (model) { - this.write(" == false() "); - }, - - enterENDS_WITH : function (model) { - throw "should be handled by the parent model"; - }, - - enterSTRING_LITERAL : function (model) { - this.write("'" + model.getValue() + "'"); - }, - - enterNUMERIC_LITERAL : function (model) { - this.write(model.getValue()); - }, - - enterDATE_LITERAL : function (model) { - this.write("'" + model.getValue() + "'"); - }, - - enterBINARY_LITERAL : function (model) { - this.write('"' + model.getValue() + '"'); - }, - - enterVARIABLE : function (model) { - this.write(model.getValue()); - }, - - enterPLUS : function (model) { - this.write(" + "); - }, - - enterMINUS : function (model) { - this.write(" - "); - }, - - enterDIVIDE : function (model) { - this.write(" / "); - }, - - enterMULTIPLY : function (model) { - this.write(" * "); - }, - - enterLESS_THAN : function () { - this.write(" < "); - }, - - enterGREATER_THAN : function () { - this.write(" > "); - }, - - enterEQUALS_TO : function () { - this.write(" == "); - }, - - enterNOT_EQUALS_TO : function () { - this.write(" != "); - }, - - enterAND : function () { - this.write(" && "); - }, - - enterOR : function () { - this.write(" || "); - }, - - enterCONTAINS : function () { - throw "should be handled by the parent model"; - }, - - enterDOES_NOT_CONTAIN : function () { - throw "should be handled by the parent model"; - }, - - enterTrue : function () { - this.write("true()"); - }, - - enterFalse : function () { - this.write("false()"); - }, - - enterPRIMITIVE_VARIABLE : function (model) { - var val = model.getValue(); - this.write(val.id); - if (expeditor.Utils.isPrimitive(val.type)) { - this.write(".value"); - } - }, - - exitPRIMITIVE_VARIABLE : function () { - - }, - - _handleUnaryOperators : function (model) { - var operator = expeditor.Utils.getOrElse(model.get(1), "choiceModel.nodeName", null); - if (operator === 'IS_EMPTY') { - this.write("!("); - model.get(0).accept(this); - this.write(")"); - return true; - } - if (operator === 'IS_NOT_EMPTY') { - this.write("!(!("); - model.get(0).accept(this); - this.write("))"); - return true; - } - - if (operator === 'IS_TRUE' || operator === 'IS_FALSE') { - model.get(0).accept(this); - model.get(1).accept(this); - return true; - } - }, - - _handleDateOperators : function (model) { - var operator = expeditor.Utils.getOrElse(model.get(1), "choiceModel.nodeName", null); - if (operator === "IS_BEFORE" || operator === "IS_AFTER") { - var oldScript = this.script; - this.script = ""; - model.get(0).accept(this); - this.script = oldScript + "dateToDaysSinceEpoch(" + this.script + ")"; - switch (operator) { - case "IS_BEFORE": - this.write("<"); - break; - case "IS_AFTER": - this.write(">"); - break; - default: - throw "Invalid operator"; - } - oldScript = this.script; - this.script = ""; - model.get(2).accept(this); - this.script = oldScript + "dateToDaysSinceEpoch(" + this.script + ")"; - return true; - } - }, - - _writeFunction : function (fnName, models) { - this.write(fnName + "("); - var self = this; - models.forEach(function (m, i) { - m.accept(self); - var sep = (i === models.length - 1) ? '' : ', '; - self.write(sep); - }); - this.write(')'); - }, - - _handleFunctionalOperator : function (model) { - var operator = expeditor.Utils.getOrElse(model.get(1), "choiceModel.nodeName", null); - if (OperatorToFnMapping.hasOwnProperty(operator)) { - var input = [model.get(0), model.get(2)]; - this._writeFunction(OperatorToFnMapping[operator], input); - return true; - } - return false; - }, - - enterCOMPARISON_EXPRESSION : function (model) { - return this._handleFunctionalOperator(model) || this._handleUnaryOperators(model) || this._handleDateOperators(model); - }, - - enterCONDITION : function (model) { - if (model.nested) { - this.write("("); - } - }, - - exitCONDITION : function (model) { - if (model.nested) { - this.write(")"); - } - }, - - enterBOOLEAN_BINARY_EXPRESSION : function (model) { - return this._handleFunctionalOperator(model); - }, - - enterCOMPONENT : function (model) { - this.write(model.getValue()); - }, - - enterMEMBER_EXPRESSION : function (model) { - model.items[2].accept(this); - this.write("."); - model.items[0].accept(this); - return true; - }, - - enterPROPERTY_LIST : function (model) { - this.write("$" + model.getValue()); - }, - - enterFUNCTION_CALL : function (model) { - var funcDef = model.getFunctionName(), - impl = funcDef.impl, - self = this; - /* Function Implementation is of the type $<NUM>($<NUM>, $<NUM>) - * Currently any $<NUM> will be replaced by the transformation of <NUM> argument - * where 0th argument is the function id. - * $ not following a number will be replaced by $ only - * If the implementation wants to escape a $<NUM> we have to modify the regex - * below to - * /\\(?=\$)\$|\$([\d]+)|./g, - * And to escape, the user has to write $0($1, \\$3) - * - */ - impl.replace(/\$([\d]+)|./g, function (match, n1, offset) { - if (n1 && n1.length > 0) { - var num = +n1; - if (num === 0) { - self.write(funcDef.id); - } else { - if (model.getParameter(num - 1).getChoiceModel() == null) { // means optional parameter is not set - self.write("undefined"); - } else { - model.getParameter(num - 1).accept(self); - } - } - } else { - self.write(match); - } - }); - } - - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/ToSummaryTransformer.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/ToSummaryTransformer.js deleted file mode 100644 index 5ea44929..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/core/ToSummaryTransformer.js +++ /dev/null @@ -1,519 +0,0 @@ -/** - * @import com.adobe.expeditor.rb.BaseTransformer - * @package com.adobe.expeditor.ToSummaryTransformer - */ -(function (expeditor) { - var defaultConfig = { - displayProp : "name" - }; - var ToSummaryTransformer = expeditor.ToSummaryTransformer = expeditor.rb.BaseTransformer.extend({ - - HTML_MODE : 0, - PLAIN_TEXT_MODE : 1, - undefinedFieldDisplayName : Granite.I18n.get("Unknown Field"), - init : function (ctx, config) { - this._super.apply(this, arguments); - this.ctx = ctx; - this.config = config || defaultConfig; - this.programCalls = 0; - this.mode = this.HTML_MODE; - this.scriptContext = {}; - }, - - setMode : function (mode) { - if (mode === this.HTML_MODE || mode === this.PLAIN_TEXT_MODE) { - this.mode = mode; - } - }, - - newScript : function () { - this.script = ""; - this.scriptContext = {}; - return this; - }, - - _currentScriptContext : function () { - return this.scriptContext; - }, - - enterROOT : function (model) { - this.newScript(); - this._currentScriptContext().index = this.programCalls; - this._currentScriptContext().isvalid = model.getIsValid(); - this._currentScriptContext().enabled = model.getIsEnabled(); - }, - - exitROOT : function (model) { - this.programCalls++; - this._currentScriptContext().content = this.script; - }, - - enterSTATEMENT : function (model) { - this._currentScriptContext().title = Granite.I18n.get("Rule") + " " + this.programCalls; - if (this.mode === this.HTML_MODE) { - this.write('<span>'); - } - }, - - enterSCRIPTMODEL : function (model) { - this.newScript(); - if (model.script) { - var stmt = '<div>'; - stmt += '<code class="summary-script"><pre>' + model.script.content + "</pre></code>"; - this.write(stmt); - this.write('</div>'); - this._currentScriptContext().content = this.script; - this._currentScriptContext().field = model.script.field; - this._currentScriptContext().eventName = model.script.event; - this._currentScriptContext().index = this.programCalls; - this._currentScriptContext().isvalid = model.getIsValid(); - this._currentScriptContext().enabled = model.getIsEnabled(); - this._currentScriptContext().isScript = true; - this.programCalls++; - } - }, - - IF_STATEMENT : function (model) { - this.writeStatement(Granite.I18n.get("IF")); - }, - - exitSTATEMENT : function (model) { - if (this.mode === this.HTML_MODE) { - this.write("</span>"); - } - }, - - enterTHEN : function (model) { - this.writeBreak(); - this.writeStatement(" " + Granite.I18n.get("THEN") + " "); - this.writeBreak(); - }, - - enterSET_VALUE_STATEMENT : function (model) { - this.writeNormal(" " + Granite.I18n.get("Set value of") + " "); - }, - - enterCOMPARISON_EXPRESSION : function (model) { - this.writeNormal(" " + Granite.I18n.get("(")); - }, - - enterVALUE_FIELD : function (model) { - this._writeVariable(model); - }, - - exitCOMPARISON_EXPRESSION : function (model) { - this.writeNormal(Granite.I18n.get(")") + " "); - }, - - // TODO : decide whether to keep this or not - enterTo : function (model) { - this.writeNormal(" " + Granite.I18n.get("to", null, "Prefixed by: Set value to VARIABLE") + " "); - }, - - //TODO: Need to think of something else. "enterto" looks weird - enterto : function (model) { - this.writeNormal(" " + Granite.I18n.get("to", null, "Prefixed by: Set value to VARIABLE") + " "); - }, - - enterNUMERIC_LITERAL : function (model) { - this.writeLiteral(model.getValue()); - }, - - enterDATE_LITERAL : function (model) { - this.writeLiteral(model.getValue()); - }, - - enterBINARY_LITERAL : function (model) { - this.writeLiteral(model.getValue()); - }, - - enterFalse : function () { - this.writeLiteral(" " + Granite.I18n.get("FALSE") + " "); - }, - - enterTrue : function () { - this.writeLiteral(" " + Granite.I18n.get("TRUE") + " "); - }, - - _writeVariable : function (model) { - var valObj = model.getValue(); - if (!expeditor.UnderscoreUtils.isUndefined(valObj) && !expeditor.UnderscoreUtils.isNull(valObj)) { - if (!expeditor.UnderscoreUtils.isUndefined(valObj.id)) { - var scope = this.ctx.getScope(); - var variable = scope.findVarById(valObj.id); - if (expeditor.rb.FeatureToggles.isHighlightBrokenRulesInSummaryViewEnabled()) { - // If the variable hierarchy has changed, then the rule is broken. - if (variable && variable.foundId !== valObj.id) { - // Skip validation for old repeatable field SOM format to avoid false positives - // When FT_FORMS-16466 is enabled, old rules may still reference fields using - // the previous format: [length(parentSOM) - 1] instead of [getRelativeInstanceIndex(parentSOM)] - // This is to avoid marking rule as broken - if (valObj.id.indexOf('[length(') !== -1 && Granite.Toggles.isEnabled('FT_FORMS-16466')) { - console.debug('ToSummaryTransformer: Skipping validation for old repeatable field SOM format:', valObj.id); - } else { - variable = null; - } - } - } - if (variable === null) { - this._writeTag("span", [ - { - name : "class", - value : "undefined-variable" - }, - { - name : "title", - value : Granite.I18n.get("Reference Error : The $$ field with SOM ID $$ is undefined as it has been renamed or removed. Please review and re-save the rule.").replace("$$", valObj.displayName).replace("$$", valObj.id) - } - ], valObj.displayName || valObj.name); - this._currentScriptContext().isvalid = false; - if (expeditor.rb.FeatureToggles.isHighlightBrokenRulesInSummaryViewEnabled()) { - this._currentScriptContext().isBroken = true; - } - } else { - variable = variable.element; - var varDN = variable[this.config.displayProp]; - this.writeVariable(varDN); - } - } else { - variable = valObj.displayName; - if (!expeditor.UnderscoreUtils.isUndefined(variable)) { - this.writeVariable(variable); - } - } - } - }, - - /** - * Write a Tag having tagName, attribute as attrs and text. The values of attribute cannot contain " character - * @param tagName - * @param attrs - * @param text - * @private - */ - _writeTag : function (tagName, attrs, text) { - if (this.mode === this.HTML_MODE) { - this.write("<" + tagName + " "); - attrs.forEach(function (attr) { - this.write(attr.name + ' = "' + attr.value + '" '); - }, this); - this.write(">"); - } - this.write(text); - if (this.mode === this.HTML_MODE) { - this.write("</" + tagName + ">"); - } - }, - - enterCOMPONENT : function (model) { - this._writeVariable(model); - }, - - enterPRIMITIVE_VARIABLE : function (model) { - this._writeVariable(model); - }, - - enterDATA_MODEL_EXPRESSION : function (model) { - var valObj = model.getValue(); - if (valObj && valObj.displayName) { - this.writeVariable(valObj.displayName); - } else if (valObj && valObj.name) { - this.writeVariable(valObj.name); - } else { - this.writeVariable("Unknown Data Model"); - } - }, - - enterVARIABLE : function (model) { - this.writeVariable(model.getId()); - }, - - enterBINARY_EXPRESSION : function (model) { - this.writeNormal(" " + Granite.I18n.get("(")); - }, - - exitBINARY_EXPRESSION : function (model) { - this.writeNormal(Granite.I18n.get(")") + " "); - }, - - enterCALC_EXPRESSION : function (model) { - this._currentScriptContext().field = model.items[0].getValue().id; - this.writeStatement(" " + Granite.I18n.get("SET VALUE OF") + " "); - this.writeBreak(); - }, - - enterCONDITION : function (model) { - if (model.nested) { - this.writeNormal(" " + Granite.I18n.get("(")); - } - }, - - exitCONDITION : function (model) { - if (model.nested) { - this.writeNormal(Granite.I18n.get(")") + " "); - } - }, - - enterSTRING_LITERAL : function (model) { - this.writeLiteral(model.getValue()); - }, - - enterCONTAINS : function (model) { - this.writeNormal(" " + Granite.I18n.get("contains") + " "); - }, - - enterDOES_NOT_CONTAIN : function (model) { - this.writeNormal(" " + Granite.I18n.get("does not contain") + " "); - }, - - enterEQUALS_TO : function (model) { - this.writeNormal(" " + Granite.I18n.get("is equal to") + " "); - }, - - enterNOT_EQUALS_TO : function (model) { - this.writeOperator(" " + Granite.I18n.get("≠") + " "); - }, - - enterPLUS : function (model) { - this.writeOperator(" " + Granite.I18n.get("+") + " "); - }, - - enterMINUS : function (model) { - this.writeOperator(" " + Granite.I18n.get("-") + " "); - }, - - enterMULTIPLY : function (model) { - this.writeOperator(" " + Granite.I18n.get("×") + " "); - }, - - enterDIVIDE : function (model) { - this.writeOperator(" " + Granite.I18n.get("÷") + " "); - }, - - enterLESS_THAN : function (model) { - this.writeOperator(" " + Granite.I18n.get("<") + " "); - }, - - enterGREATER_THAN : function (model) { - this.writeOperator(" " + Granite.I18n.get(">") + " "); - }, - - enterSTARTS_WITH : function (model) { - this.writeNormal(" " + Granite.I18n.get("starts with") + " "); - }, - - enterENDS_WITH : function (model) { - this.writeNormal(" " + Granite.I18n.get("ends with") + " "); - }, - - enterIS_EMPTY : function (model) { - this.writeNormal(" " + Granite.I18n.get("is empty")); - }, - - enterIS_NOT_EMPTY : function (model) { - this.writeNormal(" " + Granite.I18n.get("is not empty")); - }, - - enterHAS_SELECTED : function (model) { - this.writeNormal(" " + Granite.I18n.get("has selected") + " "); - }, - - enterIS_TRUE : function (model) { - this.writeNormal(" " + Granite.I18n.get("is true") + " "); - }, - - enterIS_BEFORE : function (model) { - this.writeNormal(" " + Granite.I18n.get("is before") + " "); - }, - - enterIS_AFTER : function (model) { - this.writeNormal(" " + Granite.I18n.get("is after") + " "); - }, - - enterIS_FALSE : function (model) { - this.writeNormal(" " + Granite.I18n.get("is false") + " "); - }, - - enterOR : function (model) { - this.writeBreak(); - this.writeLogicalOperator(" " + Granite.I18n.get("OR") + " "); - this.writeBreak(); - }, - - enterAND : function (model) { - this.writeBreak(); - this.writeLogicalOperator(" " + Granite.I18n.get("AND") + " "); - this.writeBreak(); - }, - - writeKeyword : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-keyword">' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeOperator : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-operator" >' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeLiteral : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-literal" >' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeVariable : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-variable" >' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeNormal : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-normal" >' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeInfo : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-normal" >' + - '<coral-icon icon="infoCircle" size="XS" ></coral-icon> ' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeLogicalOperator : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-logical-operator" >' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeStatement : function (str) { - if (this.mode === this.HTML_MODE) { - this.write('<span class="summary-statement" >' + str + '</span>'); - } else { - this.write(str); - } - }, - - writeBreak : function () { - if (this.mode === this.HTML_MODE) { - this.write("<br class='summary-break' />"); - } - }, - - enterOf : function () { - this.writeNormal(" " + Granite.I18n.get("of") + " "); - }, - - enterPROPERTY_LIST : function (model) { - this.writeVariable(model.getValue()); - this.writeNormal(" " + Granite.I18n.get("property of") + " "); - }, - - enterWSDL_STATEMENT : function (model) { - - var val = model.getValue(); - if (val && val.wsdlInfo) { - //Different summary statement for normal and preconfigured WSDL - if (val.wsdlInfo.wsdlEndPoint) { - this.writeNormal(" " + Granite.I18n.get("Invoke Webservice:") + " "); - if (val.wsdlInfo.webServiceTitle == null) { - this.writeLiteral(val.wsdlInfo.wsdlEndPoint + " "); - this.writeBreak(); - this.writeNormal(Granite.I18n.get("Operation:") + " "); - this.writeLiteral(val.wsdlInfo.operationName); - } else { - //Preconfigured WSDL statement just shows the jcr:title for the service - this.writeLiteral(val.wsdlInfo.webServiceTitle); - } - } else { - this.writeNormal(" " + Granite.I18n.get("Invoke Service:") + " "); - this.writeLiteral(val.wsdlInfo.operationTitle || val.wsdlInfo.operationName); - this.writeBreak(); - this.writeNormal(Granite.I18n.get("of FormDataModel:") + " "); - this.writeLiteral(val.wsdlInfo.formDataModelId + " "); - } - } - }, - - exitWSDL_STATEMENT : function (model) { - }, - - enterFUNCTION_CALL : function (model) { - var funcDef = model.getFunctionName(); - if (funcDef && funcDef.displayName) { - if (expeditor.rb.FeatureToggles.isHighlightBrokenRulesInSummaryViewEnabled()) { - var scope = this.ctx.getScope(); - var func = scope.findFunctionById(funcDef.id); - if (func === null) { - this.writeNormal(" (" + Granite.I18n.get("Output of Function") + " "); - this._writeTag("span", [{ - name : "class", - value : "undefined-variable" - }, { - name : "title", - value : Granite.I18n.get("Reference Error : The $$ function is undefined.").replace("$$", funcDef.displayName) - }], funcDef.displayName); - this.writeNormal(") "); - this._currentScriptContext().isvalid = false; - this._currentScriptContext().isBroken = true; - } else { - this.writeNormal(" (" + Granite.I18n.get("Output of Function") + " " + Granite.I18n.get(funcDef.displayName) + ") "); - } - } else { - this.writeNormal(" (" + Granite.I18n.get("Output of Function") + " " + Granite.I18n.get(funcDef.displayName) + ") "); - } - } - }, - - _getDisplayName : function (id, displayProp) { - var scope = this.ctx.getScope(); - var variable = scope.findVarById(id); - if (variable == null) { - return this.undefinedFieldDisplayName; - } - var _displayProp = displayProp; - if (_displayProp == null) { - _displayProp = this.config.displayProp; - } - var varDN = variable.element[_displayProp]; - return varDN; - }, - - getScript : function () { - var scriptObj = { - content : this._currentScriptContext().content, - title : this._currentScriptContext().title, - index : this._currentScriptContext().index, - isvalid : this._currentScriptContext().isvalid, - eventName : this._currentScriptContext().eventName, - enabled : this._currentScriptContext().enabled, - isScript : this._currentScriptContext().isScript, - isProxyRule : this._currentScriptContext().isProxyRule - }; - if (expeditor.rb.FeatureToggles.isHighlightBrokenRulesInSummaryViewEnabled()) { - scriptObj.isBroken = this._currentScriptContext().isBroken; - } - return scriptObj; - }, - enterJSPEL_EXPRESSION : function (model) { - this.writeLiteral(Granite.I18n.get("Output of JSP Expression {0}", model.getValue())); - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/jquery_oops.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/jquery_oops.js deleted file mode 100644 index 0a7a63c9..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/jquery_oops.js +++ /dev/null @@ -1,64 +0,0 @@ -/* Simple JavaScript Inheritance - * By John Resig http://ejohn.org/ - * MIT Licensed. - */ -// Inspired by base2 and Prototype -(function(expeditor){ - var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; - - // The base Class implementation (does nothing) - var Class = expeditor.Class = function(){}; - - // Create a new Class that inherits from this class - Class.extend = function(prop) { - var _super = this.prototype; - - // Instantiate a base class (but only create the instance, - // don't run the init constructor) - initializing = true; - var prototype = new this(); - initializing = false; - - // Copy the properties over onto the new prototype - for (var name in prop) { - // Check if we're overwriting an existing function - prototype[name] = typeof prop[name] == "function" && - typeof _super[name] == "function" && fnTest.test(prop[name]) ? - (function(name, fn){ - return function() { - var tmp = this._super; - - // Add a new ._super() method that is the same method - // but on the super-class - this._super = _super[name]; - - // The method only need to be bound temporarily, so we - // remove it when we're done executing - var ret = fn.apply(this, arguments); - this._super = tmp; - - return ret; - }; - })(name, prop[name]) : - prop[name]; - } - - // The dummy class constructor - function Class() { - // All construction is actually done in the init method - if ( !initializing && this.init ) - this.init.apply(this, arguments); - } - - // Populate our constructed prototype object - Class.prototype = prototype; - - // Enforce the constructor to be what we expect - Class.prototype.constructor = Class; - - // And make this class extendable - Class.extend = arguments.callee; - - return Class; - }; -})(this.expeditor); \ No newline at end of file diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/BaseModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/BaseModel.js deleted file mode 100644 index bb1ac708..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/BaseModel.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @package com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var BaseModel = expeditor.model.BaseModel = expeditor.Class.extend({ - - init : function (nodeName, ctx) { - this.nodeName = nodeName; - this.ctx = ctx; - }, - - /** - * convenience methods - * - */ - _visitStart : function (visitor) { - var fn = visitor["enter" + this.nodeName]; - - if (fn) { - return fn.call(visitor, this); - } else { - return false; - } - }, - - _visitEnd : function (visitor) { - var fn = visitor["exit" + this.nodeName]; - - if (fn) { - return fn.call(visitor, this); - } else { - return false; - } - }, - - setVersion : function (version) { - this.version = version; - }, - - accept : function (visitor) { - this._visitStart(visitor); - this._visitEnd(visitor); - }, - - validate : function () { - - }, - - copy : function () { - return expeditor.Utils.ModelFactory.fromJson(this.toJson(), this.ctx); - }, - - destroy : function () { - } - - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ChoiceModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ChoiceModel.js deleted file mode 100644 index b8a58708..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ChoiceModel.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @package com.adobe.expeditor.model.ChoiceModel - * @import com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var ChoiceModel = expeditor.model.ChoiceModel = expeditor.model.BaseModel.extend({ - init : function (nodeName, ctx) { - this.nodeName = nodeName; - this.ctx = ctx; - this.choiceModel = null; - }, - - setChoiceModel : function (m) { - this.choiceModel = m; - }, - - getChoiceModel : function () { - return this.choiceModel; - }, - - fromJson : function (jsonObj) { - this.nodeName = jsonObj.nodeName; - if (jsonObj.choice !== null) { - this.choiceModel = expeditor.Utils.ModelFactory.fromJson(jsonObj.choice, this.ctx); - } else { - this.choiceModel = null; - } - return this; - }, - - toJson : function () { - var choice = null; - if (this.choiceModel !== null) { - choice = this.choiceModel.toJson(); - } - return { - nodeName : this.nodeName, - choice : choice - }; - }, - - accept : function (visitor) { - if (!this._visitStart(visitor)) { - if (this.choiceModel) { - this.choiceModel.accept(visitor); - } - } - this._visitEnd(visitor); - }, - - validate : function () { - return this.choiceModel.validate(); - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ConditionModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ConditionModel.js deleted file mode 100644 index ce535f6b..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ConditionModel.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @package com.adobe.expeditor.model.ConditionModel - * @import com.adobe.expeditor.model.ChoiceModel - */ -(function (expeditor) { - var ConditionModel = expeditor.model.ConditionModel = expeditor.model.ChoiceModel.extend({ - init : function (nodeName, ctx) { - this._super.apply(this, arguments); - this.nested = false; - }, - - fromJson : function (jsonObj) { - this._super.apply(this, arguments); - this.nested = jsonObj.nested; - return this; - }, - - toJson : function () { - var obj = this._super.apply(this, arguments); - obj.nested = this.nested; - return obj; - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/FunctionModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/FunctionModel.js deleted file mode 100644 index 0216f36e..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/FunctionModel.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @package com.adobe.expeditor.model.FunctionModel - * @import com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var parameterConfig = { - extras : { - component : { - dataType : 'ANY' - }, - view : { - inline : true - } - } - }; - var FunctionModel = expeditor.model.FunctionModel = expeditor.model.BaseModel.extend({ - init : function (nodeName, ctx, extraConfig) { - this._super.apply(this, arguments); - this.parameters = []; - this.parentNodeName = null; - }, - - setFunctionName : function (value) { - this.functionName = value; - }, - - getFunctionName : function () { - return this.functionName; - }, - - setParameter : function (index, paramModel) { - this.parameters[index] = paramModel; - }, - - setParameters : function (parameters) { - this.parameters = parameters; - }, - - getParameters : function () { - return this.parameters; - }, - - getParameter : function (index) { - return this.parameters[index]; - }, - - setParentNodeName : function (parentNodeName) { - this.parentNodeName = parentNodeName; - }, - - getParentNodeName : function () { - return this.parentNodeName; - }, - - resetParameters : function () { - this.parameters = []; - }, - - toJson : function () { - return { - nodeName : this.nodeName, - parentNodeName : this.parentNodeName, - functionName : this.functionName, - params : this.parameters.map(function (param) { - return param.toJson(); - }) - }; - }, - - fromJson : function (json) { - this.nodeName = json.nodeName; - this.parentNodeName = json.parentNodeName; - this.functionName = json.functionName; - this.parameters = json.params.map(function (paramJson) { - var paramConfig = expeditor.Utils.extend({}, parameterConfig); - return this.ctx.createModel("EXPRESSION", paramConfig).fromJson(paramJson); - }, this); - return this; - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ListModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ListModel.js deleted file mode 100644 index 95bdb658..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ListModel.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @package com.adobe.expeditor.model.ListModel - * @import com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var ListModel = expeditor.model.ListModel = expeditor.model.BaseModel.extend({ - init : function (nodeName, ctx) { - this.nodeName = nodeName; - this.ctx = ctx; - this.items = []; - }, - - add : function (model) { - this.items.push(model); - }, - - remove : function (index) { - this.items.splice(index, 1); - }, - - move : function (index, newIndex) { - this.items.splice(newIndex, 0, this.items.splice(index, 1)[0]); - }, - - get : function (index) { - return this.items[index]; - }, - - size : function () { - return this.items.length; - }, - - set : function (index, model) { - if (index > -1 && index < this.items.length) { - this.items[index] = model; - } - }, - - setItems : function (items) { - this.items = items; - }, - - clear : function () { - this.items = []; - }, - - fromJson : function (jsonObj) { - var jsonItems = jsonObj.items; - this.nodeName = jsonObj.nodeName; - this.clear(); - if (jsonItems) { - for (var i = 0; i < jsonItems.length; i++) { - this.add(expeditor.Utils.ModelFactory.fromJson(jsonItems[i], this.ctx)); - } - } - return this; - }, - - toJson : function () { - var obj = { - nodeName : this.nodeName, - items : [] - - }; - for (var i = 0; i < this.items.length; i++) { - obj.items.push(this.items[i].toJson()); - } - return obj; - }, - - validate : function () { - var isValid = true; - for (var i = 0; i < this.items.length; i++) { - isValid = isValid && this.items[i].validate(); - } - return isValid; - }, - - accept : function (visitor) { - if (!this._visitStart(visitor)) { - for (var i = 0; i < this.items.length; i++) { - this.items[i].accept(visitor); - } - } - this._visitEnd(visitor); - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/RootModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/RootModel.js deleted file mode 100644 index 148c68cc..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/RootModel.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @package com.adobe.expeditor.model.RootModel - * @import com.adobe.expeditor.model.SequenceModel - */ -(function (expeditor) { - var RootModel = expeditor.model.RootModel = expeditor.model.SequenceModel.extend({ - init : function (nodeName, ctx) { - this._super.apply(this, arguments); - this.isValid = false; - this.enabled = true; - /** - * showOptionalParamDiscardWarning flag is used to show warning dialog modal. It can have the following values: - * undefined : denotes that user has not seen the warning model dialog yet or user has chosen to Cancel the rule save operation. - * false : if user has chosen to Save rule in warning dialog modal by discarding the incomplete optional function param. - * true : if we have found incomplete optional function param and user has not chosen to Save the rule after warning yet. - * @type {boolean|undefined} - */ - this.showOptionalFunctionParamDiscardWarning = undefined; - }, - - fromJson : function (jsonObj) { - this._super.apply(this, arguments); - this.isValid = jsonObj.isValid; - this.version = jsonObj.version || 0; - this.enabled = jsonObj.enabled !== undefined ? jsonObj.enabled : true; - return this; - }, - - toJson : function () { - var obj = this._super.apply(this, arguments); - obj.isValid = this.isValid; - obj.enabled = this.enabled; - obj.version = this.version; - return obj; - }, - - setIsValid : function (flag) { - this.isValid = flag; - }, - - getIsValid : function () { - return this.isValid; - }, - - getIsEnabled : function () { - return this.enabled; - }, - - setEnabled : function (flag) { - this.enabled = flag; - }, - - setShowOptionalFunctionParamDiscardWarning : function (flag) { - this.showOptionalFunctionParamDiscardWarning = flag; - }, - - getShowOptionalFunctionParamDiscardWarning : function () { - return this.showOptionalFunctionParamDiscardWarning; - }, - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ScriptModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ScriptModel.js deleted file mode 100644 index 15a74155..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/ScriptModel.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @package com.adobe.expeditor.model.ScriptModel - * @import com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var ScriptModel = expeditor.model.ScriptModel = expeditor.model.BaseModel.extend({ - init : function () { - this._super.apply(this, arguments); - this.script = { - content : "", - event : "" - }; - this.enabled = true; - }, - - setScript : function (script) { - this.script = script; - return this; - }, - - toJson : function () { - return { - script : expeditor.Utils.extend({}, this.script), - nodeName : this.nodeName, - version : this.version, - enabled : this.enabled - }; - }, - - fromJson : function (json) { - this.script = json.script; - this.version = json.version || 0; - this.enabled = json.enabled !== undefined ? json.enabled : true; - return this; - }, - - fixModel : function (jsonConfig) { - if (jsonConfig[this.nodeName]) { // fix id of script model - var model = jsonConfig[this.nodeName]; - var fieldId = expeditor.Utils.getOrElse(model, "script.field", null); - if (fieldId) { - this.script.field = fieldId; - } - } - }, - - getIsValid : function () { - //Checks if script is has event to be valid. - return !expeditor.UnderscoreUtils.isEmpty(this.script.event); - }, - - getIsEnabled : function () { - return this.enabled; - }, - - setEnabled : function (flag) { - this.enabled = flag; - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/SequenceModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/SequenceModel.js deleted file mode 100644 index fc21ef48..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/SequenceModel.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @package com.adobe.expeditor.model.SequenceModel - * @import com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var SequenceModel = expeditor.model.SequenceModel = expeditor.model.BaseModel.extend({ - init : function (nodeName, ctx) { - this.nodeName = nodeName; - this.ctx = ctx; - this.items = []; - }, - - set : function (position, model) { - this.items[position] = model; - }, - - get : function (position) { - return this.items[position]; - }, - - fromJson : function (jsonObj) { - this.nodeName = jsonObj.nodeName; - var jsonItems = jsonObj.items; - if (jsonItems) { - this.items = []; - for (var i = 0; i < jsonItems.length; i++) { - var childModel = expeditor.Utils.ModelFactory.fromJson(jsonItems[i], this.ctx); - this.items.push(childModel); - } - } - return this; - }, - - toJson : function () { - var obj = {nodeName : this.nodeName, items : []}; - if (this.items) { - for (var i = 0; i < this.items.length; i++) { - obj.items.push(this.items[i].toJson()); - } - } - return obj; - }, - - accept : function (visitor) { - if (!this._visitStart(visitor)) { - for (var i = 0; i < this.items.length; i++) { - this.items[i].accept(visitor); - } - } - this._visitEnd(visitor); - }, - - validate : function () { - var valid = true; - for (var i = 0; i < this.items.length && valid; i++) { - valid = valid && this.items[i].validate(); - } - return valid; - }, - - /** - * API fixes the model provided the jsonModel of its children. - * @param jsonConfig - */ - fixModel : function (jsonConfig) { - if (typeof jsonConfig === "object" && jsonConfig !== null) { - this.items.forEach(function (item) { - if (jsonConfig[item.nodeName]) { - item.fromJson(jsonConfig[item.nodeName]); - } - }); - } - } - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/TerminalModel.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/TerminalModel.js deleted file mode 100644 index 0fea2a40..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/model/TerminalModel.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @package com.adobe.expeditor.model.TerminalModel - * @import com.adobe.expeditor.model.BaseModel - */ -(function (expeditor) { - var TerminalModel = expeditor.model.TerminalModel = expeditor.model.BaseModel.extend({ - init : function (nodeName, ctx) { - this.nodeName = nodeName; - this.ctx = ctx; - this.value = null; - }, - - setValue : function (val) { - this.value = val; - }, - - fromJson : function (jsonObj) { - if (typeof jsonObj.value === "object" && jsonObj.value !== null) { - this.value = expeditor.Utils.deepClone(jsonObj.value); - } else { - this.value = jsonObj.value; - } - return this; - }, - - getValue : function () { - return this.value; - }, - - toJson : function () { - return {nodeName : this.nodeName, value : this.getValue()}; - }, - - validate : function () { - return this.value !== null; - } - - }); -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/namespace.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/namespace.js deleted file mode 100644 index bb712933..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/namespace.js +++ /dev/null @@ -1,25 +0,0 @@ -/************************************************************************* -* ADOBE CONFIDENTIAL -* ___________________ -* -* Copyright 2015 Adobe Systems Incorporated -* All Rights Reserved. -* -* NOTICE: All information contained herein is, and remains -* the property of Adobe Systems Incorporated and its suppliers, -* if any. The intellectual and technical concepts contained -* herein are proprietary to Adobe Systems Incorporated and its -* suppliers and are protected by all applicable intellectual property -* laws, including trade secret and copyright laws. -* Dissemination of this information or reproduction of this material -* is strictly forbidden unless prior written permission is obtained -* from Adobe Systems Incorporated. -**************************************************************************/ -(function () { - this.expeditor = this.expeditor || {}; - this.expeditor.component = this.expeditor.component || {}; - this.expeditor.view = this.expeditor.view || {}; - this.expeditor.model = this.expeditor.model || {}; - this.expeditor.rb = this.expeditor.rb || {}; - this.expeditor.runtime = {}; -})(); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/utils.js b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/utils.js deleted file mode 100644 index 75dbc94a..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/exp-editor/utils.js +++ /dev/null @@ -1,738 +0,0 @@ -/************************************************************************* -* ADOBE CONFIDENTIAL -* ___________________ -* -* Copyright 2015 Adobe Systems Incorporated -* All Rights Reserved. -* -* NOTICE: All information contained herein is, and remains -* the property of Adobe Systems Incorporated and its suppliers, -* if any. The intellectual and technical concepts contained -* herein are proprietary to Adobe Systems Incorporated and its -* suppliers and are protected by all applicable intellectual property -* laws, including trade secret and copyright laws. -* Dissemination of this information or reproduction of this material -* is strictly forbidden unless prior written permission is obtained -* from Adobe Systems Incorporated. -**************************************************************************/ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -var defaultConfig = { - choice : { - component : 'expeditor.component.ChoiceComponent', - model : 'expeditor.model.ChoiceModel', - view : 'expeditor.view.ChoiceView' - }, - sequence : { - component : 'expeditor.component.SequenceComponent', - model : 'expeditor.model.SequenceModel', - view : 'expeditor.view.SequenceView' - }, - list : { - component : 'expeditor.component.ListComponent', - model : 'expeditor.model.ListModel', - view : 'expeditor.view.ListView' - }, - terminal : { - component : 'expeditor.component.TerminalComponent', - model : 'expeditor.model.TerminalModel', - view : 'expeditor.view.TerminalView' - }, - variable : { - component : 'expeditor.component.VariableComponent', - model : 'expeditor.model.TerminalModel', - view : 'expeditor.view.VariableView' - } -}; -var nativeForEach = Array.prototype.forEach; -var breaker = {}; -var ObjProto = Object.prototype; -var hasOwnProperty = ObjProto.hasOwnProperty; -var slice = Array.prototype.slice; -var toString = ObjProto.toString; -var templateSettings = { - evaluate : /<%([\s\S]+?)%>/g, - interpolate : /<%=([\s\S]+?)%>/g, - escape : /<%-([\s\S]+?)%>/g -}; -var noMatch = /.^/; -var escapes = { - '\\' : '\\', - "'" : "'", - 'r' : '\r', - 'n' : '\n', - 't' : '\t', - 'u2028' : '\u2028', - 'u2029' : '\u2029' -}; -var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; -var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g; -var nativeIsArray = Array.isArray; - -(function (expeditor) { - - var Utils = expeditor.Utils = { - - getCurrentVersion : function () { - return 1; - }, - - getPrimitiveArrayTypes : function () { - return ["STRING[]", "NUMBER[]", "BOOLEAN[]", "DATE[]"]; - }, - - getPrimitiveTypes : function () { - return ["STRING", "NUMBER", "BOOLEAN", "DATE", "BINARY"]; - }, - - chomp : function (str) { - if (typeof str === "string") { - return str.replace(/.$/, ""); - } - return str; - }, - - excerpts : function (code, maxLines) { - if (typeof code !== "string") { - return code; - } - var lines = code.split("\n"), - excerpt = code, - _maxLines = maxLines || 3, - excerptArray = new Array(_maxLines), - i; - if (lines.length > _maxLines) { - excerptArray[0] = lines[0]; - for (i = 1; i < _maxLines - 1; i++) { - excerptArray[i] = "....."; - } - excerptArray[_maxLines - 1] = lines[lines.length - 1]; - excerpt = excerptArray.join("\n"); - } - return excerpt; - }, - - trimString : function (arr) { - if (typeof arr === "string") { - return arr.trim(); - } - if (!(arr instanceof Array)) { - return arr; - } - var newArr = [], index; - for (index = 0; index < arr.length; index++) { - var str = arr[index]; - newArr[index] = typeof str === "string" ? str.trim() : str; - } - return newArr; - }, - - isPrimitive : function (type) { - if (type == null || (typeof type !== "string" && !(type instanceof Array))) { - return false; - } - if (!(type instanceof Array)) { - type = Utils.trimString(type.split("|"))[0]; - } - return this.getPrimitiveTypes().indexOf(type) > -1; - }, - - filterPrimitiveTypes : function (type) { - return this.getCompatibleTypes(this.getPrimitiveTypes(), type); - }, - - isTypesCompatible : function (type1, type2) { - if (type1 == null || type2 == null) { - return false; - } - if (!(type1 instanceof Array)) { - type1 = type1.split("|").map(function (type) {return type.trim();}); - } - if (!(type2 instanceof Array)) { - type2 = type2.split("|").map(function (type) {return type.trim();}); - } - return type1.indexOf("ANY") > -1 || - type2.indexOf("ANY") > -1 || - type2.some(function (type) { - return type1.indexOf(type) > -1; - }); - }, - - getRenderCondition : function (config, child, childConfig) { - var condition = Utils.getOrElse(config, child, null); - if (condition === null) { - condition = Utils.getOrElse(childConfig, "extras.component.renderCondition", true); - } - return condition; - }, - - getCompatibleTypes : function (type1, type2) { - if (type1 === null || type2 === null) { - return ""; - } - if (!(type1 instanceof Array)) { - type1 = type1.split("|").map(function (type) {return type.trim();}); - } - if (!(type2 instanceof Array)) { - type2 = type2.split("|").map(function (type) {return type.trim();}); - } - var iterType1 = 0, - result = ""; - if (type1.indexOf("ANY") > -1) { - return type2.join("|"); - } - if (type2.indexOf("ANY") > -1) { - return type1.join("|"); - } - for (; iterType1 < type1.length; iterType1++) { - if (type2.indexOf(type1[iterType1]) > -1) { - result += type1[iterType1] + "|"; - } - } - return result.replace(/\|$/, ""); - }, - - isTypeSame : function (type1, type2) { - if (type1 == null || type2 == null) { - return false; - } - if (type1 === type2) { - return true; - } - if (!(type1 instanceof Array)) { - type1 = Utils.trimString(type1.split("|")); - } - if (!(type2 instanceof Array)) { - type2 = Utils.trimString(type2.split("|")); - } - if (type2.length !== type1.length) { - return false; - } - var iterType1 = 0, isSame = true; - for (; iterType1 < type1.length && isSame; iterType1++) { - isSame = isSame && type2.indexOf(type1[iterType1]) > -1; - } - return isSame; - }, - - getOrElse : function (obj) { - var currObject = obj; - if (arguments.length < 2) { - return currObject; - } else if (arguments.length == 2) { - if (!expeditor.UnderscoreUtils.isUndefined(currObject)) { - return currObject; - } else { - return expeditor.UnderscoreUtils.clone(arguments[1]); - } - } else { - var propChain = (arguments[1] || "").split("."); - var defaultValue = arguments[2]; - expeditor.UnderscoreUtils.each(propChain, function (prop) { - if (expeditor.UnderscoreUtils.isObject(currObject)) { - currObject = currObject[prop]; - } else { - currObject = undefined; - } - }); - - if (!expeditor.UnderscoreUtils.isUndefined(currObject)) { - return currObject; - } else { - return expeditor.UnderscoreUtils.clone(defaultValue); //May have to do deep clone in future. TODO: support for conditional clone - } - } - }, - - getClassForName : function (className) { - return Utils.getOrElse(window, className, null); - }, - - ModelFactory : { - //TODO : identify how models created with custom configuration will be cloned - fromJson : function (json, ctx) { - var model = ctx.createModel(json.nodeName).fromJson(json); - if (typeof model.fixModel === "function") { - var jsonConfig = Utils.getOrElse(ctx.getConfig(json.nodeName), "jsonModel", null); - if (jsonConfig != null) { - model.fixModel(jsonConfig); - } - } - return model; - } - }, - - getChildRules : function (rule) { - var children = []; - if (typeof rule !== "string") { - return children; - } - if (rule.match(/\|/)) { - children = rule.split(/\|/).map(function (option) { - return option.trim(); - }).filter(function (option) { - return option != null && option.length > 0; - }); - } // check for list rule - else if (rule.match(/\+$/)) { - var child = rule.replace(/\+$/, "").trim(); - children = [child]; - } else if (rule.match(/\*$/)) { - var child = rule.replace(/\*$/, "").trim(); - children = [child]; - } else { // sequence rule - children = rule.trim().split(" ").map(function (option) { - return option.trim(); - }).filter(function (option) { - return option != null && option.length > 0; - }); - } - return children; - }, - - _getRuleImpl : function (rule) { - var config = {}; - var children = this.getChildRules(rule); - config.children = children; - // check for choice rule - if (rule.match(/\|/)) { - config.impl = Utils.extend({}, defaultConfig.choice); - } // check for list rule - else if (rule.match(/\+$/)) { - config.impl = Utils.extend({}, defaultConfig.list); - config.extras = config.extras || {}; - config.extras.component = {minCount : 1}; - }else if (rule.match(/\*$/)) { - config.impl = Utils.extend({}, defaultConfig.list); - config.extras = config.extras || {}; - config.extras.component = {minCount : 0}; - } else if (rule == "VARIABLE") { - config.impl = Utils.extend({}, defaultConfig.variable); - } else { // sequence rule - config.impl = Utils.extend({}, defaultConfig.sequence); - } - return config; - }, - - listModelToScript : function (listModel, transformer) { - transformer.setMode(transformer.MERGE_MODE); - transformer.setAddCopyrightHeader(false); - return listModel.items.filter(function (model) { - return (model.getIsValid() && model.getIsEnabled()); - }).map(function (model) { - model.accept(transformer); - return transformer.getScript(); - }); - }, - - /** - * encodes <script> and </script> with <script> and *lt;/script> - * and also img,video and audio tag respectively - * - * other tags are being removed since scripts can be run through - * <img onerror="script" /> (same for audio and video) - */ - encodeScriptableTags : function (str) { - var index; - if (expeditor.UnderscoreUtils.isString(str)) { - return str.replace(/<(\/?)(script[^<>]*)>/gi, '<$1$2>') - .replace(/<(\/?)(img[^<>]*)>/gi, '<$1$2>') - .replace(/<(\/?)(video[^<>]*)>/gi, '<$1$2>') - .replace(/<(\/?)(audio[^<>]*)>/gi, '<$1$2>'); - } - }, - - /** - * Merges two objects reecursively but doesn't override any primitive value in the target object - * - * @param source - * @param target - * @return {*} - */ - deepMerge : function (source, target, override) { - if (source === undefined) { - return target; - } else if (target === undefined) { - return this.deepClone(source); - } else if (typeof source !== "object" || typeof target !== "object") { - return target; - } else { - var key; - for (key in source) { - if (source.hasOwnProperty(key)) { - if (typeof target[key] === "object" && typeof source[key] === "object") { - target[key] = this.deepMerge(source[key], target[key], override); - } else if (target[key] == null || override) { - target[key] = source[key]; - } - } - } - return target; - } - }, - - clearConfigFromCache : function (nodeName) { - if (Utils.getConfig.cache.hasOwnProperty(nodeName)) { - delete Utils.getConfig.cache[nodeName]; - } - }, - - /** - * expands the config for the rule - * @param rule the rule object - * @param nodeName name of the config - * @param cache whether to pick from cache or not - * @param extras - */ - getConfig : function (rule, nodeName, cache, extras) { - var config; - if (Utils.getConfig.cache == null) { - Utils.getConfig.cache = {}; - } - if (nodeName === undefined || cache === false || !Utils.getConfig.cache.hasOwnProperty(nodeName)) { - if (typeof rule === "string") { - config = this._getRuleImpl(rule); - if (extras && extras.hasOwnProperty(rule)) { - config.extras = Utils.extend({}, config.extras, this.deepClone(extras[rule])); - } - } else if (typeof rule === "object") { - config = this.getConfig(rule.rule, undefined, undefined, extras); - var prop; - for (prop in config.impl) { - if (config.impl.hasOwnProperty(prop) && rule[prop] !== undefined) { - config.impl[prop] = rule[prop]; - } - } - if (config.extras && rule.extras) { - this.deepMerge(rule.extras, config.extras, true); - } else { - config.extras = Utils.extend({}, rule.extras); - } - config.choiceName = Granite.I18n.get(rule.choiceName); - config.jsonModel = Utils.extend({}, rule.jsonModel); - } else { - config = { - impl : Utils.extend({}, defaultConfig.terminal) - }; - } - if (nodeName === undefined || cache === false) { - return config; - } - Utils.getConfig.cache[nodeName] = config; - } - return Utils.getConfig.cache[nodeName]; - }, - - capitalizeFirstCharacter : function (str) { - if (str == null) { - return null; - } - return str[0].toUpperCase() + str.substring(1).toLowerCase(); - }, - // mimics limited behaviour of $.extend - extend : function () { - if (arguments.length < 1) { - return; - } - if (typeof(arguments[0]) == "undefined") { - return; - } - var lhsArg = arguments[0]; - var deep = false; - var first = 1; - if (typeof(lhsArg) == "boolean") { - lhsArg = arguments[1]; - deep = lhsArg; - first = 2; - } - for (var i = first,arglen = arguments.length; i < arglen; i++) { - var rhsArg = arguments[i]; - if (typeof(rhsArg) != "undefined") { - for (var key in rhsArg) { - if (rhsArg.hasOwnProperty(key)) { - var rhsVal = rhsArg[key]; - if (deep && !(typeof(rhsVal) in {"number" : "","string" : "","function" : "","boolean" : ""})) { - if (rhsVal !== null && typeof(rhsVal) != "undefined") { - if (!lhsArg[key]) { - lhsArg[key] = (rhsVal.constructor == Array) ? [] : {}; - } - Utils.extend(true, lhsArg[key], rhsVal); - } - } else { - lhsArg[key] = rhsVal; - } - } - } - } - } - - return lhsArg; - }, - - extractTextFromHTML : function (htmlString) { - var div = document.createElement('div'); - div.innerHTML = window.expeditor.Utils.encodeScriptableTags(htmlString); - htmlString = div.textContent || div.innerText; - div.remove(); - return htmlString.replace(/<[^>]*>/g, ''); - }, - - deepClone : function (obj) { - return JSON.parse(JSON.stringify(obj)); - } - }; - - var ExpEditorContext = expeditor.ExpEditorContext = expeditor.Class.extend({ - init : function (config, scope, webServicesConfig, defaultExtras, version) { - this.config = config; - this.version = version || "1.0"; - this.webServicesConfig = webServicesConfig; - this.scope = scope; - this.defaultExtras = defaultExtras; - Utils.getConfig.cache = {}; - }, - - getVersion : function () { - return this.version; - }, - - setScope : function (scope) { - this.scope = scope; - }, - - getScope : function () { - return this.scope; - }, - - getConfig : function (nodeName, componentConfig) { - var cachedConfig, finalConfig, prop; - if (this.config[nodeName]) { - cachedConfig = Utils.getConfig(this.config[nodeName], nodeName, undefined, this.defaultExtras); - if (typeof componentConfig === "object" && componentConfig !== null) { - finalConfig = expeditor.Utils.extend(true, {}, cachedConfig, componentConfig); - } else { - finalConfig = cachedConfig; - } - } else { - finalConfig = Utils.getConfig(componentConfig, nodeName, false, this.defaultExtras); - } - return finalConfig; - }, - - createComponent : function (nodeName, componentConfig) { - var _componentConfig = this.getConfig(nodeName, componentConfig), - componentClassName = _componentConfig.impl.component, - componentClass = Utils.getClassForName(componentClassName), - extraConfig = Utils.getOrElse(_componentConfig, "extras.component", null); - var newComponent = new componentClass(nodeName, this, extraConfig, componentConfig); - if (typeof(newComponent.loadConfigJsonModel) == "function") { - newComponent.loadConfigJsonModel(); - } - return newComponent; - }, - - createModel : function (nodeName, componentConfig) { - if (nodeName === "SCRIPTMODEL") { - return new expeditor.model.ScriptModel(nodeName, this); - } - var _componentConfig = this.getConfig(nodeName, componentConfig), - modelClassName = _componentConfig.impl.model; - if (modelClassName) { - var modelClass = Utils.getClassForName(modelClassName); - if (modelClass) { - return new modelClass(nodeName, this, Utils.getOrElse(_componentConfig, "extras.model", null)); - } - } - }, - - createView : function (nodeName, componentConfig) { - var _componentConfig = this.getConfig(nodeName, componentConfig), - viewClassName = _componentConfig.impl.view; - if (viewClassName) { - var viewClass = Utils.getClassForName(viewClassName); - if (viewClass) { - return new viewClass(nodeName, this, Utils.getOrElse(_componentConfig, "extras.view", null)); - } - } - } - }); - - var UnderscoreUtils = expeditor.UnderscoreUtils = { - - isUndefined : function (obj) { - return obj === void 0; - }, - - each : function (obj, iterator, context) { - if (obj == null) { - return; - } - if (nativeForEach && obj.forEach === nativeForEach) { - obj.forEach(iterator, context); - }else if (obj.length === +obj.length) { - for (var i = 0, l = obj.length; i < l; i++) { - if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) { - return; - } - } - } else { - for (var key in obj) { - if (hasOwnProperty.call(obj, key)) { - if (iterator.call(context, obj[key], key, obj) === breaker) { - return; - } - } - } - } - }, - - extend : function (obj) { - UnderscoreUtils.each(slice.call(arguments, 1), function (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - }); - return obj; - }, - - find : function (obj, iterator, context) { - var result; - var context = function (value, index, list) { - if (iterator.call(context, value, index, list)) { - result = value; - return true; - } - }; - iterator || (iterator = function (value) { - return value; - }); - var result = false; - if (obj == null) { - return result; - } - if (typeof nativeSome !== 'undefined' && nativeSome && obj.some === nativeSome) { - return obj.some(iterator, context); - } - UnderscoreUtils.each(obj, function (value, index, list) { - if (result || (result = iterator.call(context, value, index, list))) { - return breaker; - } - }); - return !!result; - }, - - isNull : function (obj) { - return obj === null; - }, - - isArray : nativeIsArray || function (obj) { - return toString.call(obj) == '[object Array]'; - }, - - isObject : function (obj) { - return obj === Object(obj); - }, - - isString : function (obj) { - return toString.call(obj) == '[object String]'; - }, - - isEmpty : function (obj) { - if (obj == null) { - return true; - } - if (UnderscoreUtils.isArray(obj) || UnderscoreUtils.isString(obj)) { - return obj.length === 0; - } - for (var key in obj) { - if (hasOwnProperty.call(obj, key)) { - return false; - } - }; - return true; - }, - - defaults : function (obj) { - UnderscoreUtils.each(slice.call(arguments, 1), function (source) { - for (var prop in source) { - if (obj[prop] == null) { - obj[prop] = source[prop]; - } - } - }); - return obj; - }, - - unescape : function (code) { - return code.replace(unescaper, function (match, escape) { - return escapes[escape]; - }); - }, - - template : function (text, data, settings) { - for (var p in escapes) { - escapes[escapes[p]] = p; - } - settings = UnderscoreUtils.defaults(settings || {}, templateSettings); - var _ = function (obj) { - return new wrapper(obj); - }; - var source = "__p+='" + text - .replace(escaper, function (match) { - return '\\' + escapes[match]; - }) - .replace(settings.escape || noMatch, function (match, code) { - return "'+\n_.escape(" + UnderscoreUtils.unescape(code) + ")+\n'"; - }) - .replace(settings.interpolate || noMatch, function (match, code) { - return "'+\n(" + UnderscoreUtils.unescape(code) + ")+\n'"; - }) - .replace(settings.evaluate || noMatch, function (match, code) { - return "';\n" + UnderscoreUtils.unescape(code) + "\n;__p+='"; - }) + "';\n"; - - // If a variable is not specified, place data values in local scope. - if (!settings.variable) { - source = 'with(obj||{}){\n' + source + '}\n'; - } - - source = "var __p='';" + "var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" + source + "return __p;\n"; - - var render = new Function(settings.variable || 'obj', '_', source); - if (data) { - return render(data, UnderscoreUtils._); - } - var template = function (data) { - return render.call(this, data, UnderscoreUtils._); - }; - - template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; - - return template; - }, - - clone : function (obj) { - if (!UnderscoreUtils.isObject(obj)) { - return obj; - } - return UnderscoreUtils.isArray(obj) ? obj.slice() : UnderscoreUtils.extend({}, obj); - } - }; - -})(expeditor); diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/__init__.py deleted file mode 100644 index 72b9e142..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# Vendored subset of formsgenailib v0.2.91 — only core/form/ subpackage -# Source: Adobe Artifactory (pypi-aemforms-release-local) -# Only the JCR→CRISPR form conversion is included. diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/__init__.py deleted file mode 100644 index bdaebfe8..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -from .base import BaseForm, Field, Panel -from .form_crispr import CoreComponentField, CoreComponentForm, CoreComponentPanel, ModelJsonForm -from .form_jcr import InfinityJsonForm, JcrField, JcrForm, JcrPanel -from .transformers import core_component_to_jcr, jcr_to_core_component - -__all__ = [ - "Field", - "Panel", - "BaseForm", - "JcrField", - "JcrPanel", - "JcrForm", - "ModelJsonForm", - "InfinityJsonForm", - "CoreComponentField", - "CoreComponentPanel", - "CoreComponentForm", - "core_component_to_jcr", - "jcr_to_core_component", -] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/base.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/base.py deleted file mode 100644 index ed6978f3..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/base.py +++ /dev/null @@ -1,69 +0,0 @@ -import json -from abc import ABC, abstractmethod -from dataclasses import dataclass -from typing import List, Literal, Optional, Union - - -@dataclass -class Field: - """A general purpose container to represent a form field with its properties""" - - id: str - name: str - fieldType: str - label: str - - # Derived Properties - path: Optional[str] = None - symbolicName: Optional[str] = None - enum: Optional[List[str]] = None - enumNames: Optional[List[str]] = None - - # Raw Data - _raw_source: Optional[Literal["jcr", "crispr", "foundation"]] = None - _raw: dict = None - - -@dataclass -class Panel: - """A general purpose container to represent a form panel with its properties""" - - id: str - name: str - fieldType: str - label: str - items: List[Union["Panel", Field]] - - # Derived Properties - path: Optional[str] = None - symbolicName: Optional[str] = None - - # Raw Data - _raw_source: Optional[Literal["jcr", "crispr", "guidejson"]] = None - _raw: dict = None - - -class BaseForm(ABC): - """Abstract base class for all form types""" - - def __init__(self, form: Union[dict, str]): - if isinstance(form, str): - self.form_dict = json.loads(form) - elif isinstance(form, dict): - self.form_dict = form - else: - raise ValueError("Form must be either a JSON string or dictionary") - - self._panels: List[Panel] = [] - self._fields: List[Union[Field, Panel]] = [] - self._parse_form() - - @abstractmethod - def _parse_form(self) -> None: - """Parse the form JSON into internal structure""" - pass - - @abstractmethod - def flatten(self) -> List[dict]: - """Convert form to a flat structure suitable for LLM processing""" - pass diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/form_crispr.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/form_crispr.py deleted file mode 100644 index 93e3fb1c..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/form_crispr.py +++ /dev/null @@ -1,236 +0,0 @@ -from typing import Any, Dict, List, Literal, Optional, Union - -from pydantic import BaseModel, ConfigDict -from pydantic import Field as PydanticField -from pydantic import model_validator - -from .base import BaseForm, Field, Panel - - -class CoreComponentLabel(BaseModel): - """Model for label objects in Core Components""" - - value: str - richText: Optional[bool] = False - - -class CoreComponentConstraintMessages(BaseModel): - """Model for validation constraint messages""" - - minLength: Optional[str] = None - maxLength: Optional[str] = None - required: Optional[str] = None - format: Optional[str] = None - pattern: Optional[str] = None - - -class CoreComponentBase(BaseModel): - """Base model for all Core Components""" - - name: str - fieldType: str - id: Optional[str] = None - label: Optional[Union[CoreComponentLabel, str]] = None - description: Optional[str] = None - screenReaderText: Optional[str] = None - properties: Optional[Any] = None - events: Optional[Any] = None - rules: Optional[Any] = None - colon_type: Optional[str] = PydanticField(None, alias=":type") - - def label_str(self) -> Optional[str]: - if isinstance(self.label, CoreComponentLabel): - return self.label.value - return self.label - - model_config = ConfigDict(populate_by_name=True) - - -class CoreComponentField(CoreComponentBase): - """Model for Core Component fields""" - - type: Optional[str] = None - default: Optional[Any] = None - minLength: Optional[int] = None - maxLength: Optional[int] = None - required: Optional[bool] = None - format: Optional[str] = None - pattern: Optional[str] = None - enum: Optional[List[Any]] = None - enumNames: Optional[List[Any]] = None - constraintMessages: Optional[CoreComponentConstraintMessages] = None - mandatory_message: Optional[str] = PydanticField(None, alias="mandatoryMessage") - tooltip: Optional[str] = None - placeholder: Optional[str] = None - enabled: Optional[bool] = True - visible: Optional[bool] = True - read_only: Optional[bool] = PydanticField(default=False, alias="readOnly") - colspan: Optional[Union[str, int]] = None # Grid column width for responsive layout (1-12) - behavior: Optional[str] = None - display_format: Optional[str] = PydanticField(None, alias="displayFormat") - value: Optional[Any] = None - rich_text: Optional[bool] = PydanticField(default=None, alias="richText") - dor_bind_ref: Optional[str] = PydanticField(None, alias="dorBindRef") - data_ref: Optional[str] = PydanticField(None, alias="dataRef") - checked_value: Optional[Union[str, bool, int, float]] = PydanticField(None, alias="checkedValue") - - @model_validator(mode="before") - @classmethod - def validate_field_type(cls, data: Any) -> Any: - if isinstance(data, dict) and data.get("fieldType") == "panel": - raise ValueError('fieldType cannot be "panel"') - return data - - def apply_mappings(self, mappings: Dict[str, str]) -> "CoreComponentField": - data = self.model_dump(by_alias=True) - data[":type"] = mappings.get(self.fieldType) - return CoreComponentField(**data) - - -class CoreComponentPanel(CoreComponentBase): - """Model for Core Component panels""" - - fieldType: Literal["panel"] = "panel" - items: Optional[List[Union[CoreComponentField, "CoreComponentPanel"]]] = None - colon_items: Optional[Dict[str, Union[CoreComponentField, "CoreComponentPanel"]]] = PydanticField( - None, alias=":items" - ) - colon_items_order: Optional[List[str]] = PydanticField(None, alias=":itemsOrder") - colspan: Optional[Union[str, int]] = None # Grid column width for responsive layout (1-12) - behavior: Optional[str] = None - - def children(self) -> List[Union[CoreComponentField, "CoreComponentPanel"]]: - if self.items is not None: - return self.items - if self.colon_items is None: - return [] - if self.colon_items_order is None: - return list(self.colon_items.values()) - return [self.colon_items[item_id] for item_id in self.colon_items_order] - - def apply_mappings(self, mappings: Dict[str, str]) -> "CoreComponentPanel": - def inner( - element: Union[CoreComponentField, CoreComponentPanel], - ) -> Union[CoreComponentField, CoreComponentPanel]: - match element: - case CoreComponentField(): - return element.apply_mappings(mappings) - case CoreComponentPanel(): - data = element.model_dump(by_alias=True) - data[":type"] = mappings.get(element.fieldType) - data["items"] = [inner(child) for child in element.children()] - return CoreComponentPanel(**data) - return element - - return inner(self) - - -# Required for forward references in type hints -CoreComponentPanel.model_rebuild() - - -class CoreComponentForm(BaseModel): - """Model for Core Components Form""" - - fieldType: Literal["form"] = "form" - title: Optional[str] = None - lang: Optional[str] = None - properties: Optional[Any] = None - metadata: Optional[Any] = None - items: Optional[List[Union[CoreComponentField, CoreComponentPanel]]] = None - colon_items: Optional[Dict[str, Union[CoreComponentField, CoreComponentPanel]]] = PydanticField( - None, alias=":items" - ) - colon_items_order: Optional[List[str]] = PydanticField(None, alias=":itemsOrder") - colon_type: Optional[str] = PydanticField(None, alias=":type") - - def children(self) -> List[Union[CoreComponentField, CoreComponentPanel]]: - if self.items is not None: - return self.items - if self.colon_items is None: - return [] - if self.colon_items_order is None: - return list(self.colon_items.values()) - return [self.colon_items[item_id] for item_id in self.colon_items_order] - - def apply_mappings(self, mappings: Dict[str, str]) -> "CoreComponentForm": - def inner( - element: Union[CoreComponentField, CoreComponentPanel, CoreComponentForm], - ) -> Union[CoreComponentField, CoreComponentPanel, CoreComponentForm]: - match element: - case CoreComponentField(): - return element.apply_mappings(mappings) - case CoreComponentPanel(): - return element.apply_mappings(mappings) - case CoreComponentForm(): - data = element.model_dump(by_alias=True) - data[":type"] = mappings.get(element.fieldType) - data["items"] = [inner(child) for child in element.children()] - return CoreComponentForm(**data) - return element - - return inner(self) - - -class ModelJsonForm(BaseForm): - """Implementation for Core Components form type""" - - def __init__(self, form_dict: dict): - self._form: Optional[CoreComponentForm] = None - super().__init__(form_dict) - - def _parse(self, component: Union[CoreComponentForm, CoreComponentPanel, CoreComponentField]): - match component.fieldType: - case "panel": - assert isinstance(component, CoreComponentPanel) - panel = Panel( - id=component.id, - name=component.name, - fieldType=component.fieldType, - label=component.label_str(), - items=[], - _raw=component.model_dump(by_alias=True), - _raw_source="crispr", - ) - self._fields.append(panel) - for item in component.children(): - item_repr = self._parse(item) - panel.items.append(item_repr) - self._panels.append(panel) - return panel - case "form": - assert isinstance(component, CoreComponentForm) - for item in component.children(): - _ = self._parse(item) - case _: - assert isinstance(component, CoreComponentField) - field = Field( - id=component.id, - name=component.name, - fieldType=component.fieldType, - label=component.label_str(), - _raw=component.model_dump(by_alias=True), - enum=component.enum, - enumNames=component.enumNames, - _raw_source="crispr", - ) - self._fields.append(field) - return field - - def _parse_form(self) -> None: - # Handle the afModelDefinition wrapper if present - form_dict = self.form_dict.get("afModelDefinition", self.form_dict) - - # Parse the entire form structure into a Pydantic model - self._form = CoreComponentForm.model_validate(form_dict) - self._parse(self._form) - - @property - def model(self) -> CoreComponentForm: - """Get the parsed form model""" - if self._form is None: - raise ValueError("Form has not been parsed yet") - return self._form - - def flatten(self) -> List[Union[Field, Panel]]: - return [field for field in self._fields] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/form_jcr.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/form_jcr.py deleted file mode 100644 index db882282..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/form_jcr.py +++ /dev/null @@ -1,939 +0,0 @@ -import json -import os -from functools import cached_property -from typing import Annotated, Any, Dict, List, Literal, Optional, Tuple, Union - -from pydantic import BaseModel, BeforeValidator, ConfigDict -from pydantic import Field as PydanticField - -from .base import BaseForm, Field, Panel -from .form_crispr import CoreComponentField, CoreComponentForm, CoreComponentPanel - - -def convert_colspan_to_str(v: Any) -> Optional[str]: - """Convert integer colspan values to string representation.""" - if v is None: - return None - if isinstance(v, int) and 1 <= v <= 12: - return str(v) - return v - - -class ResponsiveDefault(BaseModel): - """Model for cq:responsive default structure. - - This represents the default responsive behavior for Core Components forms. - Contains width and offset values for responsive grid layout. - """ - - jcr_primary_type: str = PydanticField("nt:unstructured", alias="jcr:primaryType") - width: Optional[str] = None # Grid column width (1-12) - offset: Optional[str] = "0" # Grid column offset - behavior: Optional[str] = None - model_config = ConfigDict(populate_by_name=True) - - -class CqResponsive(BaseModel): - """Model for cq:responsive structure. - - This represents the complete responsive configuration for Core Components forms. - Contains the default responsive behavior and any responsive breakpoints. - """ - - jcr_primary_type: str = PydanticField("nt:unstructured", alias="jcr:primaryType") - default: Optional[ResponsiveDefault] = None # Default responsive behavior - - model_config = ConfigDict(populate_by_name=True) - - -class JcrBaseNode(BaseModel): - """Base model for all JCR nodes""" - - jcr_primary_type: str = PydanticField("nt:unstructured", alias="jcr:primaryType") - sling_resource_type: Optional[str] = PydanticField(None, alias="sling:resourceType") - - name: Optional[str] = None - fieldType: str - jcr_title: Optional[str] = PydanticField(None, alias="jcr:title") - read_only: Optional[bool] = PydanticField(default=False, alias="readOnly") - enabled: Optional[bool] = PydanticField(default=True) - visible: Optional[bool] = PydanticField(default=True) - # Direct colspan for EDS forms - colspan: Optional[ - Annotated[ - Literal["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], - BeforeValidator(convert_colspan_to_str), - ] - ] = None - behavior: Optional[str] = None - # cq:responsive structure for Core Components forms - cq_responsive: Optional[CqResponsive] = PydanticField(None, alias="cq:responsive") - fd_rules: Optional[Dict[str, Any]] = PydanticField(None, alias="fd:rules") - fd_events: Optional[Dict[str, Any]] = PydanticField(None, alias="fd:events") - - # Derived Properties - path: Optional[str] = None - - model_config = ConfigDict(populate_by_name=True) - fd_viewType: Optional[str] = PydanticField(None, alias="fd:viewType") - xmp_CreatorTool: Optional[str] = PydanticField(None, alias="xmp:CreatorTool") - - @staticmethod - def _collect_children(element_dict: dict) -> List[Tuple[str, dict]]: - children = [] - for key, value in element_dict.items(): - if isinstance(value, dict) and "fieldType" in value: - children.append((key, value)) - return children - - -class JcrField(JcrBaseNode): - """Pydantic model for JCR field representation""" - - placeholder: Optional[str] = None - default: Optional[Union[str, bool, int, float]] = None - description: Optional[str] = None - mandatory_message: Optional[str] = PydanticField(None, alias="mandatoryMessage") - tooltip: Optional[str] = PydanticField(None, alias="tooltip") - enum: Optional[List[str]] = None - enumNames: Optional[List[str]] = None - value: Optional[Any] = None - type: Optional[ - Literal[ - "boolean", - "boolean[]", - "file", - "file[]", - "number", - "number[]", - "object", - "object[]", - "string", - "string[]", - "integer", - "integer[]", - ] - ] = None - required: Optional[bool] = None - orientation: Optional[str] = None # For radio/checkbox groups - text_is_rich: Optional[Union[bool, List[bool]]] = PydanticField( - default=None, alias="textIsRich" - ) - buttonType: Optional[Literal["button", "submit", "reset"]] = None # For buttons - dor_bind_ref: Optional[str] = PydanticField(None, alias="dorBindRef") - data_ref: Optional[str] = PydanticField(None, alias="dataRef") - checked_value: Optional[Union[str, bool, int, float]] = PydanticField( - None, alias="checkedValue" - ) - - @staticmethod - def from_repr(repr: Field) -> "JcrField": - assert repr._raw_source == "jcr", ( - "JcrField can only be created from a JCR representation" - ) - return JcrField( - **repr._raw, - path=repr.path, - ) - - @staticmethod - def from_crispr( - crispr_field: "CoreComponentField", target_format: Literal["eds", "cc"] = "eds" - ) -> "JcrField": - """Convert a Core Component field to JCR field. - - Args: - crispr_field: The Core Component field to convert - target_format: Target format - "eds" for Experience Data Services forms - (direct colspan) or "cc" for Core Components forms (cq:responsive) - - Returns: - JcrField: The converted JCR field with appropriate responsive layout structure - """ - if target_format == "eds" and crispr_field.colspan is not None: - # EDS forms: Use direct colspan attribute for responsive layout - colspan = crispr_field.colspan - cq_responsive = None - else: - # Core Components forms: Use cq:responsive structure for responsive layout - colspan = None - # Only create cq:responsive if colspan is present - if crispr_field.colspan is not None: - cq_responsive = CqResponsive( - jcr_primary_type="nt:unstructured", - default=ResponsiveDefault( - jcr_primary_type="nt:unstructured", - width=crispr_field.colspan, - offset="0", - behavior=crispr_field.behavior, - ), - ) - else: - cq_responsive = None - - if crispr_field.fieldType == "checkbox" and crispr_field.checked_value is None: - crispr_field.checked_value = True - - return JcrField( - name=crispr_field.name, - fieldType=crispr_field.fieldType, - jcr_title=crispr_field.label_str(), - type=crispr_field.type, - value=crispr_field.value, - required=crispr_field.required, - description=crispr_field.description, - mandatory_message=crispr_field.mandatory_message, - tooltip=crispr_field.tooltip, - default=crispr_field.default, - enum=crispr_field.enum, - enumNames=crispr_field.enumNames, - sling_resource_type=crispr_field.colon_type, - dor_bind_ref=crispr_field.dor_bind_ref, - data_ref=crispr_field.data_ref, - placeholder=crispr_field.placeholder, - enabled=crispr_field.enabled, - visible=crispr_field.visible, - read_only=crispr_field.read_only, - text_is_rich=crispr_field.rich_text, - colspan=colspan, - cq_responsive=cq_responsive, - fd_rules=crispr_field.rules, - fd_events=crispr_field.events, - checked_value=crispr_field.checked_value, - xmp_CreatorTool="FORMS EXPERIENCE BUILDER SERVICE", - ) - - @staticmethod - def from_infinity(element_dict: dict, path: str = "") -> "JcrField": - field_kwargs: Dict[str, Any] = { - "name": element_dict.get("name"), - "fieldType": element_dict.get("fieldType"), - "jcr_title": element_dict.get("jcr:title"), - "path": path, - "sling_resource_type": element_dict.get("sling:resourceType"), - } - optional_keys = ( - "enum", - "enumNames", - "placeholder", - "default", - "description", - "required", - "tooltip", - "type", - "textIsRich", - "value", - "buttonType", - "dorExclusion", - "fd:rules", - "fd:events", - ) - field_kwargs.update( - {k: v for k, v in element_dict.items() if k in optional_keys} - ) - return JcrField(**field_kwargs) - - -class JcrPanel(JcrBaseNode): - """Pydantic model for JCR panel representation""" - - fieldType: str = "panel" - items: Dict[str, Union["JcrPanel", JcrField]] = PydanticField( - default_factory=dict, - exclude=True, # Exclude from serialization - ) - - model_config = ConfigDict( - extra="allow", # Allow extra fields for dynamic items - populate_by_name=True, - ) - - def _get_unique_name(self, name: str) -> str: - """Get a unique name for the item""" - if name in self.items: - return f"{name}_{len(self.items)}" - return name - - def model_dump(self, **kwargs): - # Get the base dictionary without items - data = super().model_dump(**kwargs) - # Add items directly to the parent dictionary - data.update({k: v.model_dump(**kwargs) for k, v in self.items.items()}) - return data - - @staticmethod - def from_repr(repr: Panel) -> "JcrPanel": - assert repr._raw_source == "jcr", ( - "JcrPanel can only be created from a JCR representation" - ) - return JcrPanel( - **repr._raw, - path=repr.path, - ) - - @staticmethod - def from_crispr( - crispr_panel: "CoreComponentPanel", target_format: Literal["eds", "cc"] = "eds" - ) -> "JcrPanel": - """Convert a Core Component panel to JCR panel. - - Args: - crispr_panel: The Core Component panel to convert - target_format: Target format - "eds" for Experience Data Services forms - (direct colspan) or "cc" for Core Components forms (cq:responsive) - - Returns: - JcrPanel: The converted JCR panel with appropriate responsive layout structure - """ - - if target_format == "eds" and crispr_panel.colspan is not None: - # EDS forms: Use direct colspan attribute for responsive layout - colspan = crispr_panel.colspan - cq_responsive = None - else: - # Core Components forms: Use cq:responsive structure for responsive layout - colspan = None - # Only create cq:responsive if colspan is present - if crispr_panel.colspan is not None: - cq_responsive = CqResponsive( - jcr_primary_type="nt:unstructured", - default=ResponsiveDefault( - jcr_primary_type="nt:unstructured", - width=crispr_panel.colspan, - offset="0", - behavior=crispr_panel.behavior, - ), - ) - else: - cq_responsive = None - - panel = JcrPanel( - name=crispr_panel.name, - fieldType="panel", - sling_resource_type=crispr_panel.colon_type, - jcr_title=crispr_panel.label_str(), - colspan=colspan, - cq_responsive=cq_responsive, - items={}, - xmp_CreatorTool="FORMS EXPERIENCE BUILDER SERVICE", - ) - - # Convert child items - for item in crispr_panel.items: - if isinstance(item, CoreComponentPanel): - panel.items[panel._get_unique_name(item.name)] = JcrPanel.from_crispr( - item, target_format - ) - else: - panel.items[panel._get_unique_name(item.name)] = JcrField.from_crispr( - item, target_format - ) - - return panel - - @staticmethod - def from_infinity(element_dict: dict, path: str = "") -> "JcrPanel": - panel = JcrPanel( - name=element_dict.get("name"), - fieldType="panel", - jcr_title=element_dict.get("jcr:title"), - sling_resource_type=element_dict.get("sling:resourceType"), - path=path, - items={}, - ) - children = JcrPanel._collect_children(element_dict) - for name, child in children: - if child["fieldType"] == "panel": - parsed_child = JcrPanel.from_infinity(child, path + f"/{name}") - else: - parsed_child = JcrField.from_infinity(child, path + f"/{name}") - panel.items[name] = parsed_child - return panel - - -class JcrForm(JcrBaseNode): - """Pydantic model for JCR form representation""" - - fieldType: str = "form" - fd_version: str = PydanticField("2.1", alias="fd:version") - title: Optional[str] = None - themeRef: Optional[str] = None - thankYouOption: Optional[str] = None - items: Dict[str, Union[JcrPanel, JcrField]] = PydanticField( - default_factory=dict, - exclude=True, # Exclude from serialization - ) - - model_config = ConfigDict( - extra="allow", # Allow extra fields for dynamic items - populate_by_name=True, - ) - - def _get_unique_name(self, name: str) -> str: - """Get a unique name for the item""" - if name in self.items: - return f"{name}_{len(self.items)}" - return name - - def model_dump(self, **kwargs): - # Get the base dictionary without items - data = super().model_dump(**kwargs) - # Add items directly to the parent dictionary - data.update({k: v.model_dump(**kwargs) for k, v in self.items.items()}) - return data - - @classmethod - def from_crispr( - cls, - crispr_form: "CoreComponentForm", - target_format: Literal["eds", "cc"] = "eds", - ) -> "JcrForm": - """Convert a Core Component form to JCR form. - - Args: - crispr_form: The Core Component form to convert - target_format: Target format - "eds" for Experience Data Services forms - (direct colspan) or "cc" for Core Components forms (cq:responsive) - - Returns: - JcrForm: The converted JCR form with appropriate responsive layout structure - """ - items = {} - form = JcrForm( - fieldType="form", - sling_resource_type=crispr_form.colon_type, - jcr_title=crispr_form.title, - items=items, - xmp_CreatorTool="FORMS EXPERIENCE BUILDER SERVICE", - ) - # Convert all child elements (panels and fields) with the specified target format - for item in crispr_form.children(): - if isinstance(item, CoreComponentPanel): - form.items[form._get_unique_name(item.name)] = JcrPanel.from_crispr( - item, target_format - ) - else: - form.items[form._get_unique_name(item.name)] = JcrField.from_crispr( - item, target_format - ) - return form - - @staticmethod - def _split_path(path: str) -> List[str]: - """Normalize and split a JCR element path into segments.""" - if not path: - return [] - if path == "/": - return [] - return [seg for seg in path.strip("/").split("/") if seg] - - def _get_container_by_path(self, path: str) -> Union["JcrForm", JcrPanel, None]: - """Return the container (form or panel) at a given path. - If the path points to a field (leaf), this returns None.""" - path_segments = JcrForm._split_path(path) - if not path_segments: - return self - current: Union[JcrForm, JcrPanel, JcrField] = self - for node_name in path_segments: - if not isinstance(current, (JcrForm, JcrPanel)): - return None - child = current.items.get(node_name) - if child is None: - return None - current = child - return current if isinstance(current, (JcrForm, JcrPanel)) else None - - def _get_parent_and_child_key( - self, path: str - ) -> Tuple[Union["JcrForm", JcrPanel, None], Optional[str]]: - """Return the parent container and the final key (segment) for a path.""" - path_segments = JcrForm._split_path(path) - if not path_segments: - return None, None - parent_path_segments = path_segments[:-1] - child_key = path_segments[-1] - parent_path = ( - "/" + "/".join(parent_path_segments) if parent_path_segments else "/" - ) - parent = self._get_container_by_path(parent_path) - return parent, child_key - - def _get_node_by_path(self, path: str) -> Optional[Union[JcrPanel, JcrField]]: - """Return the node (panel or field) at a given path.""" - parent, key = self._get_parent_and_child_key(path) - if parent is None or key is None: - return None - return parent.items.get(key) - - def _recalculate_paths_for_subtree( - self, node: Union[JcrPanel, JcrField], base_path: str - ) -> None: - """Recalculate the `path` for a node and its subtree given a new base path.""" - node.path = base_path - if isinstance(node, JcrPanel): - for child_key, child in node.items.items(): - child_path = ( - f"{base_path}/{child_key}" if base_path else f"/{child_key}" - ) - self._recalculate_paths_for_subtree(child, child_path) - - def _insert_into_items_before( - self, - items: Dict[str, Union[JcrPanel, JcrField]], - key: str, - value: Union[JcrPanel, JcrField], - before_key: Optional[str], - ) -> Dict[str, Union[JcrPanel, JcrField]]: - """Return a new dict inserting key/value before before_key (if provided).""" - if before_key is None or before_key not in items: - # Append semantics - new_items = dict(items) - new_items[key] = value - return new_items - new_items: Dict[str, Union[JcrPanel, JcrField]] = {} - inserted = False - for k, v in items.items(): - if k == before_key and not inserted: - new_items[key] = value - inserted = True - new_items[k] = v - if not inserted: - new_items[key] = value - return new_items - - def _alias_to_field_name(self, model: BaseModel, prop: str) -> Optional[str]: - """Map an alias like 'jcr:title' to the model field name like 'jcr_title'.""" - # Get the model class - model_class = type(model) - if prop in model_class.model_fields: - return prop - # Then try alias lookup - for fname, f in model_class.model_fields.items(): - if getattr(f, "alias", None) == prop: - return fname - return None - - def add(self, element: Union[JcrPanel, JcrField]) -> str: - """Add a `JcrPanel` or `JcrField` at the form root. - - Args: - element: The element to add. - key: Optional key (dict key / path segment). If not provided, a key is derived - from `element.name` or `element.fieldType` and made unique. - - Returns: - The key under which the element was added (path segment). - """ - base_name = element.name - - new_base_path = f"/{base_name}" - self._recalculate_paths_for_subtree(element, new_base_path) - self.items[base_name] = element - return base_name - - def remove(self, path: str) -> bool: - """Remove an element (panel or field) by its path. - - Returns True if removed, False if not found. - """ - parent, element_key = self._get_parent_and_child_key(path) - if parent is None or element_key is None: - return False - if element_key not in parent.items: - return False - parent.items.pop(element_key, None) - return True - - def update(self, path: str, prop: str, value: Any) -> bool: - """Update a property of a `JcrField` or `JcrPanel` at `path`. - - Supports both field names (e.g. 'jcr_title') and aliases (e.g. 'jcr:title'). - """ - node = self._get_node_by_path(path) - if node is None: - return False - field_name = self._alias_to_field_name(node, prop) or prop - try: - setattr(node, field_name, value) - return True - except Exception: - # As a fallback, stash into model_extra for unknown props if allowed - try: - if hasattr(node, "model_extra") and isinstance(node.model_extra, dict): - node.model_extra[prop] = value - return True - except Exception: - pass - return False - - def move( - self, - element_path: str, - destination_path: str, - before_path: Optional[str] = None, - ) -> bool: - """Move an element to a new container with optional ordering. - - Args: - element_path: Full path of the element to move (e.g., '/panel1/field1'). - destination_path: Path to destination container (form '/' or a panel path). - before_path: Optional full path of sibling before which to insert. - """ - src_parent, src_key = self._get_parent_and_child_key(element_path) - if src_parent is None or src_key is None or src_key not in src_parent.items: - return False - node = src_parent.items.pop(src_key) - - dest_container = self._get_container_by_path(destination_path) - if dest_container is None: - src_parent.items[src_key] = node - return False - - desired_key = src_key - if desired_key in dest_container.items: - # Discuss if the Name is already present then path will change for subsequent operations - desired_key = dest_container._get_unique_name(desired_key) - - before_key: Optional[str] = None - if before_path: - b_parent, b_key = self._get_parent_and_child_key(before_path) - if b_parent is dest_container and b_key in dest_container.items: - before_key = b_key - - # Insert in the desired order - dest_container.items = self._insert_into_items_before( - dest_container.items, desired_key, node, before_key - ) - - # Recalculate paths for moved subtree based on new location - base_path = ( - "" if destination_path in ("", "/") else destination_path.rstrip("/") - ) + f"/{desired_key}" - self._recalculate_paths_for_subtree(node, base_path) - - return True - - @staticmethod - def from_infinity( - element_dict: dict, path: str = "" - ) -> Union["JcrForm", JcrPanel, JcrField]: - """Parse a raw JCR dict into JcrForm/JcrPanel/JcrField tree. - - This mirrors the structure of the input JSON and populates the `items` maps. - """ - field_type = element_dict["fieldType"] - match field_type: - case "form": - form = JcrForm( - fieldType="form", - jcr_title=element_dict.get("jcr:title"), - title=element_dict.get("title"), - themeRef=element_dict.get("themeRef"), - thankYouOption=element_dict.get("thankYouOption"), - fd_version=element_dict.get("fd:version", "2.1"), - sling_resource_type=element_dict.get("sling:resourceType"), - path=path, - items={}, - xmp_CreatorTool=element_dict.get("xmp:CreatorTool"), - ) - children = JcrForm._collect_children(element_dict) - for name, child in children: - if child["fieldType"] == "panel": - parsed_child = JcrPanel.from_infinity(child, path + f"/{name}") - else: - parsed_child = JcrField.from_infinity(child, path + f"/{name}") - form.items[name] = parsed_child - return form - case "panel": - return JcrPanel.from_infinity(element_dict, path) - case _: - return JcrField.from_infinity(element_dict, path) - - -class InfinityJsonForm(BaseForm): - """Implementation for Infinity JSON form type""" - - def _collect_children(self, element_dict: dict) -> List[Tuple[str, dict]]: - children = [] - for key, value in element_dict.items(): - if isinstance(value, dict): - if "fieldType" in value: - children.append((key, value)) - return children - - def _parse(self, element_dict: dict, path="", symbolicName=""): - field_type = element_dict["fieldType"] - match field_type: - case "form": - children = self._collect_children(element_dict) - for name, child in children: - self._parse(child, path + f"/{name}", "$form") - case "panel": - name = element_dict.get("name") - symbolicName = f"{symbolicName}.{name}" - panel = Panel( - id=path.split("/")[-1] if path else name, - name=name, - fieldType=element_dict["fieldType"], - label=element_dict.get("jcr:title"), - items=[], - _raw=element_dict, - path=path, - symbolicName=symbolicName, - _raw_source="jcr", - ) - self._fields.append(panel) - children = self._collect_children(element_dict) - children = [ - self._parse(child, path + f"/{name}", symbolicName) - for (name, child) in children - ] - panel.items = children - self._panels.append(panel) - return panel - case _: - name = element_dict.get("name") - symbolicName = f"{symbolicName}.{name}" - field = Field( - id=path.split("/")[-1] if path else name, - name=name, - fieldType=element_dict["fieldType"], - label=element_dict.get("jcr:title"), - _raw=element_dict, - path=path, - symbolicName=symbolicName, - _raw_source="jcr", - ) - if "enum" in element_dict: - field.enum = element_dict["enum"] - if "enumNames" in element_dict: - field.enumNames = element_dict["enumNames"] - self._fields.append(field) - return field - - def _parse_form(self) -> None: - self._parse(self.form_dict) - - def flatten(self) -> List[Union[Field, Panel]]: - return [field for field in self._fields] - - def _extract_from_raw( - self, ref: str, element: Union[Field, Panel] - ) -> Optional[str]: - """Extract value from field or panel's raw dictionary using dot notation. - - Args: - ref: Reference path using dot notation (e.g. "properties.f.validationStatus") - element: Field or Panel object to extract from - - Returns: - Extracted value or None if not found - - Example: - >>> field = Field(...) # Field with properties.fd:rules.validationStatus = "valid" - >>> _extract_from_raw("properties.fd:rules.validationStatus", field) - 'valid' - """ - if not ref or not element or not hasattr(element, "_raw"): - return None - - parts = ref.split(".") - current = element._raw - - try: - for part in parts: - if not isinstance(current, dict): - return None - current = current.get(part) - if current is None: - return None - return current - except (KeyError, TypeError, AttributeError): - return None - - def filter(self, allowlist: List[str]) -> List[dict]: - """Filter fields and return only specified properties. - - Args: - allowlist: List of property names to include - - Returns: - List of dictionaries containing only the specified properties - """ - result = [] - for field in self._fields: - item_dict = {} - for item in allowlist: - if hasattr(field, item): - value = getattr(field, item) - if value is not None: - item_dict[item] = value - else: - value = self._extract_from_raw(item, field) - if value is not None: - item_dict[item] = value - if item_dict: # Only append if we found any matching properties - result.append(item_dict) - return result - - def rules(self) -> List[dict]: - fields = self._fields - result = [] - for field in fields: - raw_dict = field._raw - fd_rules_dict = raw_dict.get("fd:rules", {}) - for name, rules in fd_rules_dict.items(): - if "fd:" not in name: - continue - if not isinstance(rules, list): - rules = [rules] - for rule in rules: - result.append( - { - "path": field.path, - "type": name, - "rule": rule, - "name": field.name, - } - ) - return result - - def to_tree(self) -> dict: - """Transform the form into a tree structure with elementPath and children. - - Returns: - dict: A tree structure where each node has elementPath and children properties. - Example: - { - "elementPath": "/", - "children": { - "panel1": { - "elementPath": "/panel1", - "name": "panel1", - "children": { - "field1": { - "elementPath": "/panel1/field1", - "name": "field1" - } - } - } - } - } - """ - - def _build_tree(element: Union[Field, Panel], path: str = "") -> dict: - result = {"elementPath": path, "label": element.label} - - if isinstance(element, Panel): - result["children"] = {} - for child in element.items: - result["children"][child.id] = _build_tree(child, child.path) - - return result - - # Start with root form - root = {"elementPath": "", "name": "form", "children": {}} - - # Process all panels first - for panel in self._panels: - if not panel.path: # Skip if no path - continue - root["children"][panel.id] = _build_tree(panel, panel.path) - - # Process fields that are direct children of the form (not in panels) - for field in self._fields: - if not field.path or isinstance( - field, Panel - ): # Skip panels and fields without path - continue - # Only process fields that are direct children (path has one segment) - path_parts = field.path.strip("/").split("/") - if len(path_parts) == 1: - root["children"][field.id] = { - "elementPath": field.path, - "label": field.label, - } - - return root - - @cached_property - def _field_names(self) -> set[str]: - """Cached set of all field names for O(1) lookup. - - Returns: - set[str]: Set of all non-empty field names in the form - """ - return {field.name for field in self._fields if field.name} - - @cached_property - def _field_paths(self) -> set[str]: - """Cached set of all field paths for O(1) lookup. - - Returns: - set[str]: Set of all non-empty field paths in the form - """ - return {field.path for field in self._fields if field.path} - - def field_exists_by_name(self, name: str) -> bool: - """Check if a field with the given name exists in the form. - - Time Complexity: O(1) - Uses cached set lookup - Memory: O(n) - Cached set of field names - - Args: - name: The name of the field to search for - - Returns: - bool: True if a field with the given name exists, False otherwise - """ - if not name: - return False - return name in self._field_names - - def field_exists_by_path(self, path: str) -> bool: - """Check if a field at the given path exists in the form. - - Time Complexity: O(1) - Uses cached set lookup - Memory: O(n) - Cached set of field paths - - Args: - path: The path of the field to search for (e.g., "/panel1/field1") - - Returns: - bool: True if a field at the given path exists, False otherwise - """ - if not path: - return False - return path in self._field_paths - - -def get_allowed_properties( - field_type: str, - filter_properties: List[str], - form_type: Literal["eds", "cc"] = "eds", -) -> List[str]: - """Get allowed properties for a field type based on form type. - - Args: - field_type: The type of the field - filter_properties: List of properties to filter - form_type: The type of the form - - Returns: - List[str]: List of allowed properties - """ - if form_type == "eds": - eds_props_path = os.path.join( - os.path.dirname(__file__), "../../../data/eds_form_props.json" - ) - with open(eds_props_path, "r", encoding="utf-8") as f: - eds_props = json.load(f) - all_properties = ( - eds_props.get("formComponents", {}) - .get(field_type, {}) - .get("properties", {}) - .keys() - ) - return [prop for prop in filter_properties if prop in all_properties] - else: - return filter_properties diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/transformers.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/transformers.py deleted file mode 100644 index 40c008fc..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/bridge/vendor/formsgenailib/core/form/transformers.py +++ /dev/null @@ -1,181 +0,0 @@ -from typing import Literal, Union - -from .form_crispr import ( - CoreComponentField, - CoreComponentForm, - CoreComponentPanel, - ModelJsonForm, -) -from .form_jcr import InfinityJsonForm, JcrField, JcrForm, JcrPanel - - -def core_component_to_jcr( - element: CoreComponentField - | CoreComponentPanel - | CoreComponentForm - | ModelJsonForm, - target_format: Literal["eds", "cc"] = "eds", -) -> JcrField | JcrPanel | JcrForm: - """Convert Core Component elements to JCR format. - - This function handles the conversion of Core Component form elements to their JCR - representation, supporting two different responsive layout formats: - - EDS (Experience Data Services): Uses direct colspan attributes - - CC (Core Components): Uses cq:responsive structure - - Args: - element: CoreComponent element to convert (field, panel, or form) - target_format: Target JCR format - "eds" for Experience Data Services forms - (direct colspan) or "cc" for Core Components forms (cq:responsive) - - Returns: - JcrField | JcrPanel | JcrForm: The converted JCR element with appropriate - responsive layout structure - - Raises: - ValueError: If the element type is not supported for conversion - """ - match element: - case CoreComponentField(): - return JcrField.from_crispr(element, target_format) - case CoreComponentPanel(): - return JcrPanel.from_crispr(element, target_format) - case CoreComponentForm(): - return JcrForm.from_crispr(element, target_format) - case ModelJsonForm(): - return JcrForm.from_crispr(element.model, target_format) - case _: - raise ValueError( - f"Cannot convert {element.__class__.__name__} to JCR format" - ) - - -def jcr_to_core_component( - element: JcrField | JcrPanel | JcrForm | InfinityJsonForm, -) -> CoreComponentField | CoreComponentPanel | CoreComponentForm: - """Convert JCR elements to Core Component format. - - This function handles the conversion of JCR form elements to their Core Component - representation. It extracts colspan from either direct colspan attribute (EDS forms) - or from cq:responsive structure (CC forms). - - Args: - element: JCR element to convert (field, panel, or form) - - Returns: - CoreComponentField | CoreComponentPanel | CoreComponentForm: The converted - Core Component element - - Raises: - ValueError: If the element type is not supported for conversion - """ - match element: - case JcrField(): - return _jcr_field_to_crispr(element) - case JcrPanel(): - return _jcr_panel_to_crispr(element) - case JcrForm(): - return _jcr_form_to_crispr(element) - case InfinityJsonForm(): - # Parse the form dict into JcrForm and convert - jcr_form = JcrForm.from_infinity(element.form_dict) - if isinstance(jcr_form, JcrForm): - return _jcr_form_to_crispr(jcr_form) - raise ValueError("Expected JcrForm from InfinityJsonForm") - case _: - raise ValueError( - f"Cannot convert {element.__class__.__name__} to Core Component format" - ) - - -def _extract_colspan(element: Union[JcrField, JcrPanel]) -> str | None: - """Extract colspan from JCR element (either direct or from cq:responsive).""" - # First check direct colspan (EDS format) - if element.colspan is not None: - return element.colspan - # Then check cq:responsive structure (CC format) - if element.cq_responsive and element.cq_responsive.default: - return element.cq_responsive.default.width - return None - - -def _extract_behavior(element: Union[JcrField, JcrPanel]) -> str | None: - """Extract behavior from JCR element (either direct or from cq:responsive).""" - if element.behavior is not None: - return element.behavior - if element.cq_responsive and element.cq_responsive.default: - return element.cq_responsive.default.behavior - return None - - -def _jcr_field_to_crispr(jcr_field: JcrField) -> CoreComponentField: - """Convert a JCR field to Core Component field.""" - return CoreComponentField( - name=jcr_field.name or "", - fieldType=jcr_field.fieldType, - label=jcr_field.jcr_title, - description=jcr_field.description, - colon_type=jcr_field.sling_resource_type, - type=jcr_field.type, - default=jcr_field.default, - required=jcr_field.required, - enum=jcr_field.enum, - enumNames=jcr_field.enumNames, - placeholder=jcr_field.placeholder, - enabled=jcr_field.enabled, - visible=jcr_field.visible, - read_only=jcr_field.read_only, - colspan=_extract_colspan(jcr_field), - behavior=_extract_behavior(jcr_field), - value=jcr_field.value, - mandatory_message=jcr_field.mandatory_message, - tooltip=jcr_field.tooltip, - rules=jcr_field.fd_rules, - events=jcr_field.fd_events, - dor_bind_ref=jcr_field.dor_bind_ref, - data_ref=jcr_field.data_ref, - checked_value=jcr_field.checked_value, - rich_text=jcr_field.text_is_rich - if isinstance(jcr_field.text_is_rich, bool) - else None, - ) - - -def _jcr_panel_to_crispr(jcr_panel: JcrPanel) -> CoreComponentPanel: - """Convert a JCR panel to Core Component panel.""" - items = [] - for item in jcr_panel.items.values(): - if isinstance(item, JcrPanel): - items.append(_jcr_panel_to_crispr(item)) - else: - items.append(_jcr_field_to_crispr(item)) - - return CoreComponentPanel( - name=jcr_panel.name or "", - fieldType="panel", - label=jcr_panel.jcr_title, - colon_type=jcr_panel.sling_resource_type, - items=items, - colspan=_extract_colspan(jcr_panel), - behavior=_extract_behavior(jcr_panel), - ) - - -def _jcr_form_to_crispr(jcr_form: JcrForm) -> CoreComponentForm: - """Convert a JCR form to Core Component form.""" - items = [] - for item in jcr_form.items.values(): - if isinstance(item, JcrPanel): - items.append(_jcr_panel_to_crispr(item)) - else: - items.append(_jcr_field_to_crispr(item)) - - # Use model_validate with alias since CoreComponentForm doesn't have populate_by_name=True - return CoreComponentForm.model_validate( - { - "fieldType": "form", - "title": jcr_form.jcr_title or jcr_form.title, - ":type": jcr_form.sling_resource_type, - "items": items, - } - ) diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/__init__.py deleted file mode 100644 index 6690e54b..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Context module for component lookup and form context management.""" - -from .component_lookup import ComponentLookup -from .form_context import FormContext -from .form_context_cache import FormContextCache, get_cache - -__all__ = ['ComponentLookup', 'FormContext', 'FormContextCache', 'get_cache'] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/component_lookup.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/component_lookup.py deleted file mode 100644 index 03e00829..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/component_lookup.py +++ /dev/null @@ -1,409 +0,0 @@ -""" -Component lookup service for rule generation. - -This module provides the ComponentLookup class which: -1. Builds a cache of all components from treeJson for quick lookup -2. Provides methods to search and retrieve component information -3. Formats component data for use in rule generation (matching VariableDefinition.toJson() structure) -""" - -import logging -from typing import Dict, Any, Optional, List - -logger = logging.getLogger(__name__) - - -class ComponentLookup: - """Service to look up component information and format it for rules.""" - - def __init__( - self, - tree_json: Dict[str, Any], - functions_config: Optional[List[Dict[str, Any]]] = None - ): - """ - Initialize with form tree JSON and optional functions configuration. - - Args: - tree_json: The complete form tree JSON structure (from transform-form.js). - functions_config: Optional list of function definitions. - """ - self.tree_json = tree_json - self.functions_config = functions_config or [] - self._component_cache: Dict[str, Dict[str, Any]] = {} - self._functions_cache: Dict[str, Dict[str, Any]] = {} - self._build_component_cache() - self._build_functions_cache() - - def _build_component_cache(self): - """Build a cache of all components for quick lookup.""" - - def traverse(node: Dict[str, Any], parent_id: str = "", display_path: str = "FORM/"): - if not node: - return - - node_id = node.get("id", "") - node_name = node.get("name", "") - display_name = node.get("displayName", node.get("name", "")) - - # Build metadata object with isAncestorRepeatable - metadata = {} - if "isAncestorRepeatable" in node: - metadata["isAncestorRepeatable"] = node.get("isAncestorRepeatable", False) - # Merge with any existing metadata - if node.get("metadata"): - metadata.update(node.get("metadata")) - - if node_id: - # Store component info - ALWAYS use the full type from treeJson - # The treeJson type is generated by _getExpEditorDataType() in ExpressionEditorTree.js - # and contains the full pipe-delimited type (e.g., "AFCOMPONENT|FIELD|TEXT FIELD|STRING") - original_type = node.get("type", "") - component_type = original_type if original_type else self._get_fallback_type(node) - - self._component_cache[node_id] = { - "id": node_id, - "name": node_name, - "displayName": display_name, - "type": component_type, - "displayPath": display_path, - "parent": parent_id, - "fieldType": node.get("fieldType", ""), - "path": node.get("path", ""), - "isDuplicate": False, - "metadata": metadata - } - - # Also store by name for easier lookup - if node_name and node_name != node_id: - self._component_cache[node_name] = self._component_cache[node_id] - - # Traverse children - use child's displayName for path - items = node.get("items", []) - if items and isinstance(items, list): - for item in items: - item_display_name = item.get("displayName", item.get("name", "")) - child_display_path = f"{display_path}{item_display_name}/" - traverse(item, node_id, child_display_path) - - traverse(self.tree_json) - logger.debug(f"Built component cache with {len(self._component_cache)} entries") - - def _build_functions_cache(self): - """Build a cache of all functions for quick lookup.""" - if not self.functions_config: - return - - for func in self.functions_config: - func_id = func.get('id', '') - if func_id: - self._functions_cache[func_id] = func - # Also store by displayName for easier lookup - display_name = func.get('displayName', '') - if display_name: - self._functions_cache[display_name.lower()] = func - - logger.debug(f"Built functions cache with {len(self._functions_cache)} entries") - - def _get_fallback_type(self, node: Dict[str, Any]) -> str: - """ - Generate full pipe-delimited type string as fallback when not present in treeJson. - - This mirrors the _getExpEditorDataType() function from ExpressionEditorTree.js. - The type format is: AFCOMPONENT|FIELD|<FIELD_TYPE>|<DATA_TYPE> - - Only used as fallback when treeJson doesn't have the type already. - """ - field_type = node.get("fieldType", "") - data_type = node.get("type", "string") # JSON schema type - - # Form is special - just returns "FORM" - if field_type == "form": - return "FORM" - - # Build the type array like ExpressionEditorTree.js does - type_parts = ["AFCOMPONENT"] - - # Field types that are considered "fields" (not panels, images, etc.) - field_types = ["text-input", "multiline-input", "email", "number-input", - "date-input", "drop-down", "radio-group", "checkbox-group", - "checkbox", "button", "file-input", "captcha"] - - if field_type in field_types: - type_parts.append("FIELD") - - # Map fieldType to specific type names - field_type_mapping = { - "text-input": ["TEXT FIELD"], - "multiline-input": ["TEXT FIELD"], - "email": ["TEXT FIELD"], - "number-input": ["NUMBER FIELD"], - "date-input": ["DATE FIELD"], - "drop-down": ["DROPDOWN"], - "radio-group": ["RADIO BUTTON"], - "checkbox-group": ["CHECK BOX"], - "checkbox": [], - "button": ["BUTTON"], - "file-input": ["FILE ATTACHMENT", "BINARY"], - "panel": ["PANEL"], - "plain-text": ["STATIC TEXT", "STRING"], - "image": ["IMAGE", "STRING"], - "captcha": [] - } - - if field_type in field_type_mapping: - type_parts.extend(field_type_mapping[field_type]) - - # Add data type based on JSON schema type (skip for button) - if field_type != "button": - if data_type in ["number", "integer"]: - type_parts.append("NUMBER") - elif data_type == "boolean": - type_parts.append("BOOLEAN") - elif data_type == "string": - # Check for date format - if node.get("format") == "date": - type_parts.append("DATE") - elif field_type in field_types: - type_parts.append("STRING") - elif data_type in ["number[]", "string[]", "boolean[]"]: - type_parts.append(data_type.upper()) - elif data_type == "file": - type_parts.append("FILE") - elif data_type == "file[]": - type_parts.append("FILE[]") - - return "|".join(type_parts) - - def get_component( - self, - identifier: str - ) -> Optional[Dict[str, Any]]: - """ - Get component information by ID or name. - - Returns the full type from treeJson (e.g., "AFCOMPONENT|FIELD|TEXT FIELD|STRING"). - This is the preferred approach - use the full type everywhere for consistency. - - Args: - identifier: Component ID or name. - - Returns: - Component info dict matching VariableDefinition.toJson() structure: - {id, displayName, type, isDuplicate, displayPath, name, parent, metadata} - or None if not found. - """ - component = self._component_cache.get(identifier) - if not component: - logger.warning(f"Component not found: {identifier}") - return None - - # Return structure matching exp-editor/rule-builder/core/VariableDefinition.js toJson() - result = { - "id": component["id"], - "displayName": component["displayName"], - "type": component["type"], # Always use full type from treeJson - "isDuplicate": component["isDuplicate"], - "displayPath": component["displayPath"], - "name": component["name"], - "parent": component["parent"] - } - - # Add metadata if it has properties - metadata = component.get("metadata", {}) - if metadata: - result["metadata"] = metadata - - return result - - def get_component_for_action(self, identifier: str) -> Optional[Dict[str, Any]]: - """ - Get component info for use in action statements (HIDE, SHOW, ENABLE, etc.). - - Returns the full type from treeJson (e.g., "AFCOMPONENT|FIELD|TEXT FIELD|STRING"). - This preserves the complete type information for grammar validation. - - Args: - identifier: Component ID or name. - - Returns: - Component info dict with full type from treeJson. - """ - return self.get_component(identifier) # Use full type, no override - - def get_component_for_value_field(self, identifier: str) -> Optional[Dict[str, Any]]: - """ - Get component info for use in SET_VALUE_STATEMENT target (VALUE_FIELD). - - Returns the full type from treeJson (e.g., "AFCOMPONENT|FIELD|TEXT FIELD|STRING"). - This preserves the complete type information for grammar validation. - - Args: - identifier: Component ID or name. - - Returns: - Component info dict with full type from treeJson. - """ - return self.get_component(identifier) - - def search_components(self, query: str) -> List[Dict[str, Any]]: - """ - Search for components by partial name or display name. - - Args: - query: Search query. - - Returns: - List of matching components. - """ - query_lower = query.lower() - results = [] - seen_ids = set() - - for key, component in self._component_cache.items(): - comp_id = component.get("id", "") - if comp_id in seen_ids: - continue - - if (query_lower in component.get("name", "").lower() or - query_lower in component.get("displayName", "").lower()): - results.append({ - "id": component["id"], - "displayName": component["displayName"], - "type": component["type"], - "displayPath": component["displayPath"], - "name": component["name"], - "parent": component["parent"], - "fieldType": component.get("fieldType", "") - }) - seen_ids.add(comp_id) - - return results - - def list_all_components(self) -> List[Dict[str, Any]]: - """ - List all available components. - - Returns: - List of all components. - """ - results = [] - seen_ids = set() - - for key, component in self._component_cache.items(): - comp_id = component.get("id", "") - if comp_id and comp_id not in seen_ids: - results.append({ - "id": component["id"], - "displayName": component["displayName"], - "type": component["type"], - "name": component["name"], - "fieldType": component.get("fieldType", "") - }) - seen_ids.add(comp_id) - - return results - - def get_form_component(self) -> Optional[Dict[str, Any]]: - """ - Get the root form component ($form). - - Returns: - Form component info dict. - """ - return self.get_component("$form") - - def get_function_info(self, function_identifier: str) -> Optional[Dict[str, Any]]: - """ - Get complete function definition including all arg descriptions. - - IMPORTANT: Use this to get the exact args[] array for FUNCTION_CALL. - The returned functionName structure should be copied EXACTLY to FUNCTION_CALL.functionName. - - Args: - function_identifier: Function id or displayName. - - Returns: - Complete function definition with structure matching FUNCTION_CALL.functionName: - {id, displayName, type, isDuplicate, displayPath, args, impl} - or None if not found. - """ - func = None - - # Try direct lookup first - if function_identifier in self._functions_cache: - func = self._functions_cache[function_identifier] - # Try lowercase lookup - elif function_identifier.lower() in self._functions_cache: - func = self._functions_cache[function_identifier.lower()] - else: - # Try partial match - for key, f in self._functions_cache.items(): - if function_identifier.lower() in key.lower(): - func = f - break - if function_identifier.lower() in f.get('id', '').lower(): - func = f - break - if function_identifier.lower() in f.get('displayName', '').lower(): - func = f - break - - if not func: - return None - - # Return structure matching FUNCTION_CALL.functionName format - return { - "id": func.get("id", ""), - "displayName": func.get("displayName", ""), - "type": func.get("type", "VOID"), - "isDuplicate": False, - "displayPath": "", - "args": func.get("args", []), - "impl": func.get("impl", "") - } - - def search_functions(self, query: str) -> List[Dict[str, Any]]: - """ - Search for functions by partial name or description. - - Args: - query: Search query. - - Returns: - List of matching functions. - """ - query_lower = query.lower() - results = [] - seen_ids = set() - - for key, func in self._functions_cache.items(): - func_id = func.get("id", "") - if func_id in seen_ids: - continue - - if (query_lower in func.get("id", "").lower() or - query_lower in func.get("displayName", "").lower() or - query_lower in func.get("description", "").lower()): - results.append(func) - seen_ids.add(func_id) - - return results - - def list_all_functions(self) -> List[Dict[str, Any]]: - """ - List all available functions with their full definitions. - - Returns: - List of all functions with complete args arrays. - """ - results = [] - seen_ids = set() - - for key, func in self._functions_cache.items(): - func_id = func.get("id", "") - if func_id and func_id not in seen_ids: - results.append(func) - seen_ids.add(func_id) - - return results diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/form_context.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/form_context.py deleted file mode 100644 index 1547c8f0..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/form_context.py +++ /dev/null @@ -1,306 +0,0 @@ -""" -Form context module for managing form data and context. - -This module provides the FormContext class which: -1. Loads and transforms form definition JSON to treeJson -2. Loads and merges OOTB + custom functions -3. Provides a unified interface for component and function lookup -""" - -import json -import subprocess -import os -from typing import Dict, Any, Optional, List -from pathlib import Path -from dataclasses import dataclass, field - -from .component_lookup import ComponentLookup - - -# Path to the bridge CLI -BRIDGE_CLI_PATH = Path(__file__).parent.parent / 'bridge' / 'cli' -FUNCTIONS_PATH = Path(__file__).parent.parent / 'functions' - - -@dataclass -class FormContext: - """ - Complete form context for rule generation. - - Contains: - - treeJson: Transformed form structure for component lookup - - functions: List of all available functions (OOTB + custom) - - component_lookup: ComponentLookup instance for searching - """ - tree_json: Dict[str, Any] - functions: List[Dict[str, Any]] = field(default_factory=list) - _component_lookup: Optional[ComponentLookup] = field(default=None, repr=False) - - @property - def component_lookup(self) -> ComponentLookup: - """Get or create the ComponentLookup instance.""" - if self._component_lookup is None: - self._component_lookup = ComponentLookup(self.tree_json, self.functions) - return self._component_lookup - - @classmethod - def load_from_form_json( - cls, - form_json: Dict[str, Any], - custom_functions_path: Optional[str] = None - ) -> 'FormContext': - """ - Create FormContext from a form JSON object. - - Args: - form_json: The form definition JSON (not yet transformed). - custom_functions_path: Optional path to custom functions JS file. - - Returns: - FormContext instance. - """ - # Transform form JSON to treeJson - tree_json = cls._transform_form_json(form_json) - - # Load functions - functions = cls._load_all_functions(custom_functions_path) - - return cls( - tree_json=tree_json, - functions=functions - ) - - @classmethod - def load_from_form_file( - cls, - form_json_path: str, - custom_functions_path: Optional[str] = None - ) -> 'FormContext': - """ - Create FormContext from a form JSON file. - - Args: - form_json_path: Path to the form definition JSON file. - custom_functions_path: Optional path to custom functions JS file. - - Returns: - FormContext instance. - """ - with open(form_json_path, 'r') as f: - form_json = json.load(f) - - return cls.load_from_form_json(form_json, custom_functions_path) - - @classmethod - def load_from_tree_json( - cls, - tree_json: Dict[str, Any], - custom_functions_path: Optional[str] = None - ) -> 'FormContext': - """ - Create FormContext from an already-transformed treeJson. - - Args: - tree_json: The transformed form tree JSON. - custom_functions_path: Optional path to custom functions JS file. - - Returns: - FormContext instance. - """ - # Load functions - functions = cls._load_all_functions(custom_functions_path) - - return cls( - tree_json=tree_json, - functions=functions - ) - - @staticmethod - def _transform_form_json(form_json: Dict[str, Any]) -> Dict[str, Any]: - """ - Transform form definition JSON to treeJson using the bridge CLI. - - Args: - form_json: The form definition JSON. - - Returns: - The transformed treeJson. - """ - transform_script = BRIDGE_CLI_PATH / 'transform-form.js' - - if not transform_script.exists(): - raise FileNotFoundError(f"Transform form CLI not found: {transform_script}") - - # Run the transform-form.js CLI with stdin input - result = subprocess.run( - ['node', str(transform_script), '--stdin'], - input=json.dumps(form_json), - capture_output=True, - text=True, - cwd=str(BRIDGE_CLI_PATH.parent) - ) - - if result.returncode != 0: - error_output = result.stderr or result.stdout - raise RuntimeError(f"Failed to transform form JSON: {error_output}") - - try: - output = json.loads(result.stdout) - except json.JSONDecodeError as e: - raise RuntimeError(f"Invalid JSON output from transformer: {e}") - - if not output.get('success', False): - raise RuntimeError(f"Transform error: {output.get('error', 'Unknown error')}") - - return output.get('treeJson', {}) - - @staticmethod - def _load_all_functions( - custom_functions_path: Optional[str] = None - ) -> List[Dict[str, Any]]: - """ - Load all functions (OOTB + custom). - - Args: - custom_functions_path: Optional path to custom functions JS file. - - Returns: - List of all function definitions. - """ - functions = [] - - # Load OOTB functions - ootb_path = FUNCTIONS_PATH / 'ootb-functions.json' - if ootb_path.exists(): - with open(ootb_path, 'r') as f: - ootb_data = json.load(f) - functions.extend(ootb_data.get('functions', [])) - - # Load custom functions if path provided - if custom_functions_path and os.path.exists(custom_functions_path): - parse_script = BRIDGE_CLI_PATH / 'parse-functions.js' - - if parse_script.exists(): - result = subprocess.run( - ['node', str(parse_script), custom_functions_path], - capture_output=True, - text=True, - cwd=str(BRIDGE_CLI_PATH.parent) - ) - - if result.returncode == 0: - try: - output = json.loads(result.stdout) - if output.get('success', False): - custom_funcs = output.get('customFunction', []) - functions.extend(custom_funcs) - except json.JSONDecodeError: - pass # Ignore parse errors for custom functions - - return functions - - def get_component(self, identifier: str) -> Optional[Dict[str, Any]]: - """ - Get component by ID or name. - - Args: - identifier: Component ID or name. - - Returns: - Component info dict or None. - """ - return self.component_lookup.get_component(identifier) - - def get_component_for_action(self, identifier: str) -> Optional[Dict[str, Any]]: - """ - Get component for use in actions (with AFCOMPONENT type). - - Args: - identifier: Component ID or name. - - Returns: - Component info dict with AFCOMPONENT type. - """ - return self.component_lookup.get_component_for_action(identifier) - - def search_components(self, query: str) -> List[Dict[str, Any]]: - """ - Search for components by partial name. - - Args: - query: Search query. - - Returns: - List of matching components. - """ - return self.component_lookup.search_components(query) - - def list_all_components(self) -> List[Dict[str, Any]]: - """ - List all available components. - - Returns: - List of all components. - """ - return self.component_lookup.list_all_components() - - def get_function_info(self, function_identifier: str) -> Optional[Dict[str, Any]]: - """ - Get function info by ID or name. - - Args: - function_identifier: Function ID or displayName. - - Returns: - Function info dict or None. - """ - return self.component_lookup.get_function_info(function_identifier) - - def search_functions(self, query: str) -> List[Dict[str, Any]]: - """ - Search for functions by partial name or description. - - Args: - query: Search query. - - Returns: - List of matching functions. - """ - return self.component_lookup.search_functions(query) - - def list_all_functions(self) -> List[Dict[str, Any]]: - """ - List all available functions. - - Returns: - List of all functions. - """ - return self.component_lookup.list_all_functions() - - def to_dict(self) -> Dict[str, Any]: - """ - Convert to dictionary for serialization. - - Returns: - Dictionary representation of the form context. - """ - return { - 'treeJson': self.tree_json, - 'functions': self.functions - } - - @classmethod - def from_dict(cls, data: Dict[str, Any]) -> 'FormContext': - """ - Create FormContext from a dictionary. - - Args: - data: Dictionary with 'treeJson' and optional 'functions'. - - Returns: - FormContext instance. - """ - return cls( - tree_json=data.get('treeJson', {}), - functions=data.get('functions', []) - ) diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/form_context_cache.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/form_context_cache.py deleted file mode 100644 index 826af6a2..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/context/form_context_cache.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -FormContext caching with automatic invalidation. - -This module provides: -1. Caching of FormContext to avoid repeated transformations -2. Automatic invalidation when source files change -3. Manual refresh capability -""" - -import json -import os -import hashlib -from typing import Dict, Any, Optional, List -from pathlib import Path -from dataclasses import dataclass, field -import logging - -from .form_context import FormContext - -logger = logging.getLogger(__name__) - - -@dataclass -class CacheEntry: - """A cached FormContext with metadata for invalidation.""" - context: FormContext - form_json_path: str - form_json_mtime: float - form_json_hash: str - custom_functions_path: Optional[str] = None - custom_functions_mtime: Optional[float] = None - custom_functions_hash: Optional[str] = None - - -class FormContextCache: - """ - Caches FormContext instances with automatic invalidation. - - Usage: - cache = FormContextCache() - - # Get or create context (auto-caches) - ctx = cache.get_context("path/to/form.json", "path/to/functions.js") - - # Check if cache is valid - if cache.is_valid("path/to/form.json"): - ctx = cache.get_cached("path/to/form.json") - - # Force refresh - ctx = cache.refresh("path/to/form.json", "path/to/functions.js") - - # Clear all caches - cache.clear() - """ - - _instance: Optional['FormContextCache'] = None - - def __new__(cls): - """Singleton pattern - one cache per process.""" - if cls._instance is None: - cls._instance = super().__new__(cls) - cls._instance._cache: Dict[str, CacheEntry] = {} - return cls._instance - - @staticmethod - def _get_file_mtime(path: str) -> Optional[float]: - """Get file modification time.""" - try: - return os.path.getmtime(path) - except OSError: - return None - - @staticmethod - def _get_file_hash(path: str) -> Optional[str]: - """Get MD5 hash of file contents.""" - try: - with open(path, 'rb') as f: - return hashlib.md5(f.read()).hexdigest() - except OSError: - return None - - def _get_cache_key(self, form_json_path: str) -> str: - """Generate cache key from form path.""" - return os.path.abspath(form_json_path) - - def is_valid(self, form_json_path: str, custom_functions_path: Optional[str] = None) -> bool: - """ - Check if cached context is still valid. - - Validates by checking: - 1. Form JSON file modification time and hash - 2. Custom functions file modification time and hash (if provided) - - Args: - form_json_path: Path to form JSON file. - custom_functions_path: Optional path to custom functions JS. - - Returns: - True if cache is valid, False if needs refresh. - """ - key = self._get_cache_key(form_json_path) - - if key not in self._cache: - return False - - entry = self._cache[key] - - # Check form JSON - current_mtime = self._get_file_mtime(form_json_path) - if current_mtime is None or current_mtime != entry.form_json_mtime: - # Mtime changed, verify with hash - current_hash = self._get_file_hash(form_json_path) - if current_hash != entry.form_json_hash: - logger.debug(f"Form JSON changed: {form_json_path}") - return False - - # Check custom functions if path provided - if custom_functions_path: - abs_func_path = os.path.abspath(custom_functions_path) - - # If functions path changed - if entry.custom_functions_path != abs_func_path: - logger.debug(f"Custom functions path changed") - return False - - current_mtime = self._get_file_mtime(custom_functions_path) - if current_mtime is None or current_mtime != entry.custom_functions_mtime: - current_hash = self._get_file_hash(custom_functions_path) - if current_hash != entry.custom_functions_hash: - logger.debug(f"Custom functions changed: {custom_functions_path}") - return False - elif entry.custom_functions_path is not None: - # Had functions before, now none provided - logger.debug("Custom functions removed") - return False - - return True - - def get_cached(self, form_json_path: str) -> Optional[FormContext]: - """ - Get cached context without validation. - - Args: - form_json_path: Path to form JSON file. - - Returns: - Cached FormContext or None. - """ - key = self._get_cache_key(form_json_path) - entry = self._cache.get(key) - return entry.context if entry else None - - def get_context( - self, - form_json_path: str, - custom_functions_path: Optional[str] = None, - force_refresh: bool = False - ) -> FormContext: - """ - Get FormContext, using cache if valid. - - Args: - form_json_path: Path to form JSON file. - custom_functions_path: Optional path to custom functions JS. - force_refresh: If True, ignore cache and reload. - - Returns: - FormContext instance. - """ - if not force_refresh and self.is_valid(form_json_path, custom_functions_path): - logger.debug(f"Using cached FormContext for: {form_json_path}") - return self.get_cached(form_json_path) - - return self.refresh(form_json_path, custom_functions_path) - - def refresh( - self, - form_json_path: str, - custom_functions_path: Optional[str] = None - ) -> FormContext: - """ - Force refresh the cached context. - - Args: - form_json_path: Path to form JSON file. - custom_functions_path: Optional path to custom functions JS. - - Returns: - Fresh FormContext instance. - """ - logger.info(f"Loading FormContext: {form_json_path}") - - # Load fresh context - context = FormContext.load_from_form_file(form_json_path, custom_functions_path) - - # Build cache entry - key = self._get_cache_key(form_json_path) - entry = CacheEntry( - context=context, - form_json_path=os.path.abspath(form_json_path), - form_json_mtime=self._get_file_mtime(form_json_path), - form_json_hash=self._get_file_hash(form_json_path) - ) - - if custom_functions_path: - entry.custom_functions_path = os.path.abspath(custom_functions_path) - entry.custom_functions_mtime = self._get_file_mtime(custom_functions_path) - entry.custom_functions_hash = self._get_file_hash(custom_functions_path) - - self._cache[key] = entry - logger.debug(f"Cached FormContext for: {form_json_path}") - - return context - - def invalidate(self, form_json_path: str) -> bool: - """ - Manually invalidate a cached context. - - Args: - form_json_path: Path to form JSON file. - - Returns: - True if entry was removed, False if not found. - """ - key = self._get_cache_key(form_json_path) - if key in self._cache: - del self._cache[key] - logger.debug(f"Invalidated cache for: {form_json_path}") - return True - return False - - def clear(self): - """Clear all cached contexts.""" - self._cache.clear() - logger.debug("Cleared all FormContext caches") - - def list_cached(self) -> List[str]: - """List all cached form paths.""" - return list(self._cache.keys()) - - def get_cache_info(self, form_json_path: str) -> Optional[Dict[str, Any]]: - """ - Get cache metadata for debugging. - - Args: - form_json_path: Path to form JSON file. - - Returns: - Dict with cache info or None. - """ - key = self._get_cache_key(form_json_path) - entry = self._cache.get(key) - - if not entry: - return None - - return { - "form_json_path": entry.form_json_path, - "form_json_mtime": entry.form_json_mtime, - "custom_functions_path": entry.custom_functions_path, - "custom_functions_mtime": entry.custom_functions_mtime, - "is_valid": self.is_valid(form_json_path, entry.custom_functions_path), - "components_count": len(entry.context.list_all_components()), - "functions_count": len(entry.context.functions) - } - - def export_for_cli(self, form_json_path: str) -> Optional[Dict[str, Any]]: - """ - Export cached context data for use by Node.js CLI tools. - - Returns the treeJson and functions in a format that can be - passed to CLI tools via --context flag or stdin. - - Args: - form_json_path: Path to form JSON file. - - Returns: - Dict with treeJson and functions, or None if not cached. - """ - key = self._get_cache_key(form_json_path) - entry = self._cache.get(key) - - if not entry: - return None - - return entry.context.to_dict() - - -# Convenience function for getting the singleton -def get_cache() -> FormContextCache: - """Get the FormContextCache singleton.""" - return FormContextCache() diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/debug/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/debug/__init__.py deleted file mode 100644 index 6f462705..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/debug/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Debug utilities for rule generation.""" - -from .rule_diff import diff_rules, format_diff_report - -__all__ = ['diff_rules', 'format_diff_report'] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/debug/rule_diff.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/debug/rule_diff.py deleted file mode 100644 index f5f92f84..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/debug/rule_diff.py +++ /dev/null @@ -1,350 +0,0 @@ -""" -Rule diff utility for comparing rule JSONs. - -This module provides tools to compare expected vs actual rule JSON -and identify structural differences for debugging. -""" - -from typing import Dict, Any, List, Tuple, Optional -from dataclasses import dataclass - - -@dataclass -class Difference: - """Represents a difference between two rule JSONs.""" - path: str - expected: Any - actual: Any - diff_type: str # 'missing', 'extra', 'value_mismatch', 'type_mismatch' - - def __str__(self) -> str: - if self.diff_type == 'missing': - return f"{self.path}: missing (expected: {self._format_value(self.expected)})" - elif self.diff_type == 'extra': - return f"{self.path}: unexpected key (actual: {self._format_value(self.actual)})" - elif self.diff_type == 'type_mismatch': - return f"{self.path}: type mismatch (expected: {type(self.expected).__name__}, actual: {type(self.actual).__name__})" - else: - return f"{self.path}: expected {self._format_value(self.expected)}, got {self._format_value(self.actual)}" - - def _format_value(self, value: Any) -> str: - if value is None: - return "null" - if isinstance(value, str): - return f"'{value}'" - if isinstance(value, dict): - return "{...}" - if isinstance(value, list): - return f"[{len(value)} items]" - return str(value) - - -def diff_rules( - expected: Dict[str, Any], - actual: Dict[str, Any], - ignore_keys: Optional[List[str]] = None -) -> List[Difference]: - """ - Compare two rule JSONs and return list of differences. - - Args: - expected: The expected rule JSON (correct structure) - actual: The actual rule JSON (generated/to validate) - ignore_keys: Optional list of keys to ignore (e.g., ['_description']) - - Returns: - List of Difference objects describing each difference - """ - ignore_keys = ignore_keys or ['_description', '_natural_language'] - differences: List[Difference] = [] - - def compare(exp: Any, act: Any, path: str = ""): - # Handle None cases - if exp is None and act is None: - return - if exp is None: - differences.append(Difference(path, exp, act, 'extra')) - return - if act is None: - differences.append(Difference(path, exp, act, 'missing')) - return - - # Type mismatch - if type(exp) != type(act): - differences.append(Difference(path, exp, act, 'type_mismatch')) - return - - # Compare dictionaries - if isinstance(exp, dict): - all_keys = set(exp.keys()) | set(act.keys()) - for key in all_keys: - if key in ignore_keys: - continue - new_path = f"{path}.{key}" if path else key - - if key not in act: - differences.append(Difference(new_path, exp[key], None, 'missing')) - elif key not in exp: - differences.append(Difference(new_path, None, act[key], 'extra')) - else: - compare(exp[key], act[key], new_path) - - # Compare lists - elif isinstance(exp, list): - if len(exp) != len(act): - differences.append(Difference( - f"{path}.length", - len(exp), - len(act), - 'value_mismatch' - )) - # Compare items up to the shorter length - for i in range(min(len(exp), len(act))): - compare(exp[i], act[i], f"{path}[{i}]") - # Note missing items - for i in range(len(act), len(exp)): - differences.append(Difference( - f"{path}[{i}]", - exp[i], - None, - 'missing' - )) - # Note extra items - for i in range(len(exp), len(act)): - differences.append(Difference( - f"{path}[{i}]", - None, - act[i], - 'extra' - )) - - # Compare primitives - else: - if exp != act: - differences.append(Difference(path, exp, act, 'value_mismatch')) - - compare(expected, actual) - return differences - - -def format_diff_report(differences: List[Difference]) -> str: - """ - Format a list of differences into a readable report. - - Args: - differences: List of Difference objects - - Returns: - Formatted string report - """ - if not differences: - return "No differences found." - - lines = [f"Found {len(differences)} difference(s):", ""] - - # Group by type - missing = [d for d in differences if d.diff_type == 'missing'] - extra = [d for d in differences if d.diff_type == 'extra'] - type_mismatch = [d for d in differences if d.diff_type == 'type_mismatch'] - value_mismatch = [d for d in differences if d.diff_type == 'value_mismatch'] - - if missing: - lines.append("MISSING:") - for d in missing: - lines.append(f" - {d}") - lines.append("") - - if extra: - lines.append("UNEXPECTED:") - for d in extra: - lines.append(f" - {d}") - lines.append("") - - if type_mismatch: - lines.append("TYPE MISMATCH:") - for d in type_mismatch: - lines.append(f" - {d}") - lines.append("") - - if value_mismatch: - lines.append("VALUE MISMATCH:") - for d in value_mismatch: - lines.append(f" - {d}") - lines.append("") - - return "\n".join(lines) - - -def check_structure( - rule: Dict[str, Any], - expected_structure: Optional[Dict[str, Any]] = None -) -> Tuple[bool, List[str]]: - """ - Check if a rule has the expected basic structure. - - Args: - rule: The rule JSON to check - expected_structure: Optional custom structure (uses default if None) - - Returns: - Tuple of (is_valid, list of errors) - """ - errors = [] - - # Check ROOT - if rule.get('nodeName') != 'ROOT': - errors.append("Root node must have nodeName='ROOT'") - - if 'items' not in rule: - errors.append("ROOT must have 'items' array") - return False, errors - - if not rule['items']: - errors.append("ROOT.items must not be empty") - return False, errors - - # Check STATEMENT - statement = rule['items'][0] - if not isinstance(statement, dict): - errors.append("First item in ROOT must be a STATEMENT object") - return False, errors - - if statement.get('nodeName') != 'STATEMENT': - errors.append("First item must have nodeName='STATEMENT'") - - if 'choice' not in statement: - errors.append("STATEMENT must have 'choice' property") - return False, errors - - # Check TRIGGER_SCRIPTS - choice = statement['choice'] - if not isinstance(choice, dict): - errors.append("STATEMENT.choice must be an object") - return False, errors - - if choice.get('nodeName') != 'TRIGGER_SCRIPTS': - errors.append("STATEMENT.choice must be TRIGGER_SCRIPTS") - - if 'items' not in choice: - errors.append("TRIGGER_SCRIPTS must have 'items' array") - return False, errors - - # Check SINGLE_TRIGGER_SCRIPTS - if not choice['items']: - errors.append("TRIGGER_SCRIPTS.items must not be empty") - return False, errors - - sts = choice['items'][0] - if not isinstance(sts, dict): - errors.append("First TRIGGER_SCRIPTS item must be object") - return False, errors - - if sts.get('nodeName') != 'SINGLE_TRIGGER_SCRIPTS': - errors.append("Expected SINGLE_TRIGGER_SCRIPTS") - - if 'items' not in sts: - errors.append("SINGLE_TRIGGER_SCRIPTS must have 'items'") - return False, errors - - sts_items = sts['items'] - if len(sts_items) < 4: - errors.append(f"SINGLE_TRIGGER_SCRIPTS must have 4+ items, found {len(sts_items)}") - - # Check required items - if len(sts_items) >= 1: - if sts_items[0].get('nodeName') != 'COMPONENT': - errors.append("Item 0 must be COMPONENT") - - if len(sts_items) >= 2: - if sts_items[1].get('nodeName') != 'TRIGGER_EVENT': - errors.append("Item 1 must be TRIGGER_EVENT") - - if len(sts_items) >= 3: - if sts_items[2].get('nodeName') != 'When': - errors.append("Item 2 must be 'When' literal token") - - if len(sts_items) >= 4: - if sts_items[3].get('nodeName') != 'TRIGGER_EVENT_SCRIPTS': - errors.append("Item 3 must be TRIGGER_EVENT_SCRIPTS") - else: - tes = sts_items[3] - if 'items' not in tes: - errors.append("TRIGGER_EVENT_SCRIPTS must have 'items'") - elif len(tes['items']) < 3: - errors.append("TRIGGER_EVENT_SCRIPTS must have 3+ items") - else: - if tes['items'][0].get('nodeName') != 'CONDITION': - errors.append("TRIGGER_EVENT_SCRIPTS[0] must be CONDITION") - if tes['items'][1].get('nodeName') != 'Then': - errors.append("TRIGGER_EVENT_SCRIPTS[1] must be 'Then'") - if tes['items'][2].get('nodeName') != 'BLOCK_STATEMENTS': - errors.append("TRIGGER_EVENT_SCRIPTS[2] must be BLOCK_STATEMENTS") - - return len(errors) == 0, errors - - -def diagnose_rule(rule: Dict[str, Any]) -> str: - """ - Provide diagnostic information about a rule. - - Args: - rule: The rule JSON to diagnose - - Returns: - Diagnostic report string - """ - lines = ["Rule Diagnostic Report", "=" * 40, ""] - - # Basic structure check - is_valid, structure_errors = check_structure(rule) - lines.append(f"Structure Valid: {'Yes' if is_valid else 'No'}") - if structure_errors: - lines.append("Structure Errors:") - for err in structure_errors: - lines.append(f" - {err}") - lines.append("") - - # Extract key information - try: - lines.append("Rule Summary:") - lines.append(f" Event Name: {rule.get('eventName', 'N/A')}") - lines.append(f" Enabled: {rule.get('enabled', 'N/A')}") - - # Get trigger info - sts = rule['items'][0]['choice']['items'][0] - trigger_comp = sts['items'][0].get('value', {}) - trigger_event = sts['items'][1].get('value', 'N/A') - lines.append(f" Trigger: {trigger_comp.get('displayName', 'N/A')} {trigger_event}") - - # Get condition info - tes = sts['items'][3] - condition = tes['items'][0] - if condition.get('choice') is None: - lines.append(" Condition: None (always execute)") - else: - cond_type = condition['choice'].get('nodeName', 'Unknown') - lines.append(f" Condition: {cond_type}") - - # Get action info - then_block = tes['items'][2] - action_count = len(then_block.get('items', [])) - lines.append(f" Then Actions: {action_count}") - for i, action in enumerate(then_block.get('items', [])): - action_name = action.get('choice', {}).get('nodeName', 'Unknown') - lines.append(f" {i+1}. {action_name}") - - # Check for else block - if len(tes['items']) > 4: - else_block = tes['items'][4] - else_count = len(else_block.get('items', [])) - lines.append(f" Else Actions: {else_count}") - for i, action in enumerate(else_block.get('items', [])): - action_name = action.get('choice', {}).get('nodeName', 'Unknown') - lines.append(f" {i+1}. {action_name}") - else: - lines.append(" Else Actions: None") - - except (KeyError, IndexError, TypeError) as e: - lines.append(f" Error extracting summary: {e}") - - return "\n".join(lines) diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/__init__.py deleted file mode 100644 index 65b87c38..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Functions module for loading and managing OOTB and custom functions.""" - -from .loader import ( - load_ootb_functions, - parse_custom_functions, - get_all_functions, - FunctionDefinition -) - -__all__ = [ - 'load_ootb_functions', - 'parse_custom_functions', - 'get_all_functions', - 'FunctionDefinition' -] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/loader.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/loader.py deleted file mode 100644 index 45011718..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/loader.py +++ /dev/null @@ -1,268 +0,0 @@ -""" -Functions loader module for loading OOTB and custom functions. - -This module provides functions to: -1. Load OOTB (out-of-the-box) functions from ootb-functions.json -2. Parse custom function scripts via the bridge CLI -3. Merge OOTB and custom functions, checking for duplicates -""" - -import json -import subprocess -import os -from typing import Dict, List, Optional, Any -from dataclasses import dataclass, field -from pathlib import Path - - -@dataclass -class FunctionArg: - """Represents a function argument.""" - type: str - name: str - description: str - is_mandatory: bool = True - - -@dataclass -class FunctionDefinition: - """Represents a function definition.""" - id: str - display_name: str - type: str - description: str - impl: str - args: List[FunctionArg] = field(default_factory=list) - is_error_handler: bool = False - - @classmethod - def from_dict(cls, data: Dict[str, Any]) -> 'FunctionDefinition': - """Create a FunctionDefinition from a dictionary.""" - args = [ - FunctionArg( - type=arg.get('type', 'STRING'), - name=arg.get('name', ''), - description=arg.get('description', ''), - is_mandatory=arg.get('isMandatory', True) - ) - for arg in data.get('args', []) - ] - return cls( - id=data.get('id', ''), - display_name=data.get('displayName', data.get('id', '')), - type=data.get('type', 'ANY'), - description=data.get('description', ''), - impl=data.get('impl', ''), - args=args, - is_error_handler=data.get('isErrorHandler', False) - ) - - def to_dict(self) -> Dict[str, Any]: - """Convert to dictionary format for rule generation.""" - return { - 'id': self.id, - 'displayName': self.display_name, - 'type': self.type, - 'description': self.description, - 'impl': self.impl, - 'args': [ - { - 'type': arg.type, - 'name': arg.name, - 'description': arg.description, - 'isMandatory': arg.is_mandatory - } - for arg in self.args - ], - 'isDuplicate': False, - 'displayPath': '' - } - - -# Path to the ootb-functions.json file -OOTB_FUNCTIONS_PATH = Path(__file__).parent / 'ootb-functions.json' - -# Path to the bridge CLI -BRIDGE_CLI_PATH = Path(__file__).parent.parent / 'bridge' / 'cli' - - -def load_ootb_functions() -> List[FunctionDefinition]: - """ - Load OOTB functions from ootb-functions.json. - - Returns: - List of FunctionDefinition objects for OOTB functions. - """ - if not OOTB_FUNCTIONS_PATH.exists(): - raise FileNotFoundError(f"OOTB functions file not found: {OOTB_FUNCTIONS_PATH}") - - with open(OOTB_FUNCTIONS_PATH, 'r') as f: - data = json.load(f) - - functions = data.get('functions', []) - return [FunctionDefinition.from_dict(func) for func in functions] - - -def parse_custom_functions(script_path: str) -> Dict[str, Any]: - """ - Parse a custom function script via the bridge CLI. - - Args: - script_path: Path to the custom function JavaScript file. - - Returns: - Dictionary with 'customFunction' and 'imports' keys. - """ - parse_script = BRIDGE_CLI_PATH / 'parse-functions.js' - - if not parse_script.exists(): - raise FileNotFoundError(f"Parse functions CLI not found: {parse_script}") - - if not os.path.exists(script_path): - raise FileNotFoundError(f"Custom function script not found: {script_path}") - - # Run the parse-functions.js CLI - result = subprocess.run( - ['node', str(parse_script), script_path], - capture_output=True, - text=True, - cwd=str(BRIDGE_CLI_PATH.parent) - ) - - if result.returncode != 0: - error_output = result.stderr or result.stdout - raise RuntimeError(f"Failed to parse custom functions: {error_output}") - - try: - output = json.loads(result.stdout) - except json.JSONDecodeError as e: - raise RuntimeError(f"Invalid JSON output from parser: {e}") - - if not output.get('success', False): - raise RuntimeError(f"Parser error: {output.get('error', 'Unknown error')}") - - return { - 'customFunction': output.get('customFunction', []), - 'imports': output.get('imports', []) - } - - -def parse_custom_functions_recursive( - script_path: str, - processed_scripts: Optional[set] = None -) -> List[Dict[str, Any]]: - """ - Parse a custom function script and recursively parse imported scripts. - - Args: - script_path: Path to the custom function JavaScript file. - processed_scripts: Set of already processed script paths (to avoid cycles). - - Returns: - List of all parsed function definitions. - """ - if processed_scripts is None: - processed_scripts = set() - - script_path = os.path.abspath(script_path) - - if script_path in processed_scripts: - return [] - - processed_scripts.add(script_path) - - result = parse_custom_functions(script_path) - all_functions = result.get('customFunction', []) - - # Process imports recursively - imports = result.get('imports', []) - script_dir = os.path.dirname(script_path) - - for import_path in imports: - # Resolve relative import paths - if import_path.startswith('./') or import_path.startswith('../'): - full_path = os.path.normpath(os.path.join(script_dir, import_path)) - else: - full_path = import_path - - if os.path.exists(full_path): - imported_functions = parse_custom_functions_recursive(full_path, processed_scripts) - all_functions.extend(imported_functions) - - return all_functions - - -def get_all_functions( - custom_script_path: Optional[str] = None, - check_duplicates: bool = True -) -> List[FunctionDefinition]: - """ - Get all functions (OOTB + custom), optionally checking for duplicates. - - Args: - custom_script_path: Optional path to custom function script. - check_duplicates: If True, warn about duplicate function IDs. - - Returns: - List of all FunctionDefinition objects. - """ - # Load OOTB functions - all_functions = load_ootb_functions() - ootb_ids = {func.id for func in all_functions} - - # Parse custom functions if provided - if custom_script_path: - custom_funcs = parse_custom_functions_recursive(custom_script_path) - - for func_data in custom_funcs: - func = FunctionDefinition.from_dict(func_data) - - if check_duplicates and func.id in ootb_ids: - print(f"Warning: Custom function '{func.id}' shadows OOTB function") - - all_functions.append(func) - - return all_functions - - -def search_functions( - functions: List[FunctionDefinition], - query: str -) -> List[FunctionDefinition]: - """ - Search functions by name or description. - - Args: - functions: List of functions to search. - query: Search query string. - - Returns: - List of matching functions. - """ - query_lower = query.lower() - return [ - func for func in functions - if query_lower in func.id.lower() or - query_lower in func.display_name.lower() or - query_lower in func.description.lower() - ] - - -def get_function_by_id( - functions: List[FunctionDefinition], - func_id: str -) -> Optional[FunctionDefinition]: - """ - Get a function by its ID. - - Args: - functions: List of functions to search. - func_id: Function ID to find. - - Returns: - FunctionDefinition if found, None otherwise. - """ - for func in functions: - if func.id == func_id: - return func - return None diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/ootb-functions.json b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/ootb-functions.json deleted file mode 100644 index b163725e..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/functions/ootb-functions.json +++ /dev/null @@ -1,814 +0,0 @@ -{ - "searchKey": "displayName", - "displayProps": [ - "displayName", - "description" - ], - "functions": [ - { - "id": "abs", - "displayName": "Absolute Value Of", - "args": [ - { - "type": "NUMBER", - "name": "value", - "description": "value", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the absolute value of the provided argument $value.", - "impl": "$0($1)" - }, - { - "id": "avg", - "displayName": "Average Of", - "args": [ - { - "type": "NUMBER[]", - "name": "elements", - "description": "elements", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the average of the elements in the provided array. An empty array will produce a return value of null.", - "impl": "$0($1)" - }, - { - "id": "ceil", - "displayName": "Ceil", - "args": [ - { - "type": "NUMBER", - "name": "value", - "description": "value", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the next highest integer value by rounding up if necessary.", - "impl": "$0($1)" - }, - { - "id": "contains", - "displayName": "Contains", - "args": [ - { - "type": "STRING[]|NUMBER[]|ARRAY|STRING", - "name": "subject", - "description": "subject", - "isMandatory": true - }, - { - "type": "STRING|BOOLEAN|NUMBER|DATE", - "name": "search", - "description": "search", - "isMandatory": true - } - ], - "type": "BOOLEAN", - "description": "Returns true if the given $subject contains the provided $search string. If $subject is an array, this function returns true if one of the elements in the array is equal to the provided $search value. If the provided $subject is a string, this function returns true if the string contains the provided $search argument.", - "impl": "$0($1,$2)" - }, - { - "id": "endsWith", - "displayName": "Ends With", - "args": [ - { - "type": "STRING", - "name": "subject", - "description": "subject", - "isMandatory": true - }, - { - "type": "STRING", - "name": "prefix", - "description": "prefix", - "isMandatory": true - } - ], - "type": "BOOLEAN", - "description": "Returns true if the $subject ends with the $prefix, otherwise this function returns false.", - "impl": "$0($1,$2)" - }, - { - "id": "floor", - "displayName": "Floor", - "args": [ - { - "type": "NUMBER", - "name": "value", - "description": "value", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the next lowest integer value by rounding down if necessary.", - "impl": "$0($1)" - }, - { - "id": "length", - "displayName": "Length", - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|DATE[]|BOOLEAN[]|FILE[]|ARRAY|OBJECT|PANEL", - "name": "subject", - "description": "subject", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the length of the given argument using the following types rules: string: returns the number of code points in the string array: returns the number of elements in the array object: returns the number of key-value pairs in the object: returns the number instances in panel", - "impl": "$0($1)" - }, - { - "id": "max", - "displayName": "Maximum", - "args": [ - { - "type": "NUMBER[]|STRING[]", - "name": "collection", - "description": "collection", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the highest found number in the provided array argument. An empty array will produce a return value of null.", - "impl": "$0($1)" - }, - { - "id": "startsWith", - "displayName": "Starts With", - "args": [ - { - "type": "STRING", - "name": "subject", - "description": "subject", - "isMandatory": true - }, - { - "type": "STRING", - "name": "prefix", - "description": "prefix", - "isMandatory": true - } - ], - "type": "BOOLEAN", - "description": "Returns true if the $subject starts with the $prefix, otherwise this function returns false.", - "impl": "$0($1,$2)" - }, - { - "id": "defaultErrorHandler", - "displayName": "Default Invoke Service Error Handler", - "args": [ - { - "type": "OBJECT", - "name": "response", - "description": "response", - "isMandatory": true - }, - { - "type": "OBJECT", - "name": "header", - "description": "header", - "isMandatory": true - } - ], - "type": "ANY", - "isErrorHandler": true, - "description": "Default Invoke Service Error Handler", - "impl": "$0($1,$2)" - }, - { - "id": "sum", - "displayName": "Sum", - "args": [ - { - "type": "NUMBER[]", - "name": "collection", - "description": "collection", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the sum of the provided array argument. An empty array will produce a return value of 0.", - "impl": "$0($1)" - }, - { - "id": "min", - "displayName": "Minimum", - "args": [ - { - "type": "NUMBER[]|STRING[]", - "name": "collection", - "description": "collection", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns the lowest found number in the provided $collection argument.", - "impl": "$0($1)" - }, - { - "id": "type", - "displayName": "Type", - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "subject", - "description": "subject", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Returns the JavaScript type of the given $subject argument as a string value. The return value MUST be one of the following: number string boolean array object null", - "impl": "$0($1)" - }, - { - "id": "keys", - "displayName": "Keys", - "args": [ - { - "type": "OBJECT", - "name": "obj", - "description": "obj", - "isMandatory": true - } - ], - "type": "STRING[]", - "description": "Returns an array containing the keys of the provided object. If the passed object is null, the value returned is an empty array", - "impl": "$0($1)" - }, - { - "id": "values", - "displayName": "Values", - "args": [ - { - "type": "OBJECT", - "name": "obj", - "description": "obj", - "isMandatory": true - } - ], - "type": "STRING[]|NUMBER[]|ARRAY", - "description": "Returns the values of the provided object. Note that because JSON hashes are inheritently unordered, the values associated with the provided object obj are inheritently unordered.", - "impl": "$0($1)" - }, - { - "id": "sort", - "displayName": "Sort", - "args": [ - { - "type": "NUMBER[]|STRING[]", - "name": "list", - "description": "list", - "isMandatory": true - } - ], - "type": "NUMBER[]|STRING[]", - "description": "This function accepts an array $list argument and returns the sorted elements of the $list as an array. The array must be a list of strings or numbers. Sorting strings is based on code points. Locale is not taken into account.", - "impl": "$0($1)" - }, - { - "id": "join", - "displayName": "Join", - "args": [ - { - "type": "STRING", - "name": "glue", - "description": "glue", - "isMandatory": true - }, - { - "type": "STRING[]", - "name": "stringsarray", - "description": "stringsarray", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Returns all of the elements from the provided $stringsarray array joined together using the $glue argument as a separator between each.", - "impl": "$0($1,$2)" - }, - { - "id": "reverse", - "displayName": "Reverse", - "args": [ - { - "type": "STRING|STRING[]|NUMBER[]|ARRAY", - "name": "argument", - "description": "argument", - "isMandatory": true - } - ], - "type": "STRING|STRING[]|NUMBER[]|ARRAY", - "description": "Reverses the order of the $argument.", - "impl": "$0($1)" - }, - { - "id": "toArray", - "displayName": "Convert To Array", - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|OBJECT", - "name": "arg", - "description": "arg", - "isMandatory": true - } - ], - "type": "STRING[]|NUMBER[]|ARRAY|DATE[]|BOOLEAN[]", - "description": "Converts the passed arg to an array array - Returns the passed in value. number/string/object/boolean - Returns a one element array containing the passed in argument.", - "impl": "$0($1)" - }, - { - "id": "_toString", - "displayName": "Convert To String", - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "arg", - "description": "arg", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Converts the passed arg to a string string - Returns the passed in value. number/array/object/boolean - The JSON encoded value of the object.", - "impl": "toString($1)" - }, - { - "id": "toNumber", - "displayName": "Convert To Number", - "args": [ - { - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|ARRAY|OBJECT", - "name": "arg", - "description": "arg", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Converts the passed arg to a number string - Returns the parsed number. number - Returns the passed in value. array - null object - null boolean - null null - null", - "impl": "$0($1)" - }, - { - "id": "today", - "type": "DATE", - "displayName": "Get Current Date", - "args": [], - "impl": "$0()", - "description": "Returns current date" - }, - { - "id": "lower", - "displayName": "To Lower Case", - "args": [ - { - "type": "STRING", - "name": "input", - "description": "input string", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Converts all the alphabetic characters in a string to lowercase. If the value is not a string it will be converted into string using the default toString method", - "impl": "$0($1)" - }, - { - "id": "upper", - "displayName": "To Upper Case", - "args": [ - { - "type": "STRING", - "name": "input", - "description": "input string", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Converts all the alphabetic characters in a string to uppercase. If the value is not a string it will be converted into string using the default toString method", - "impl": "$0($1)" - }, - { - "id": "exp", - "displayName": "Exponent of", - "args": [ - { - "type": "NUMBER", - "name": "input", - "description": "number", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Returns e (the base of natural logarithms) raised to a power x", - "impl": "$0()" - }, - { - "id": "power", - "displayName": "Power of", - "args": [ - { - "type": "NUMBER", - "name": "a", - "description": "a", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "x", - "description": "x", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Computes `a` raised to a power `x`", - "impl": "$0($1,$2)" - }, - { - "id": "mid", - "displayName": "Substring Of", - "args": [ - { - "type": "STRING|ARRAY", - "name": "subject", - "description": "subject", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "startPos", - "description": "startPos", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "length", - "description": "length", - "isMandatory": true - } - ], - "type": "STRING|ARRAY|STRING[]|NUMBER[]|FILE[]|DATE[]|BOOLEAN[]", - "description": "Returns extracted text, given an original text, starting position, and length. or in case of array, extracts a subset of the array from start till the length number of elements. Returns null", - "impl": "$0($1,$2,$3)" - }, - { - "id": "mod", - "displayName": "Modulo of", - "args": [ - { - "type": "NUMBER", - "name": "dividend", - "description": "dividend", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "divisor", - "description": "divisor", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Return the remainder when one number is divided by another number.", - "impl": "$0($1,$2)" - }, - { - "id": "proper", - "displayName": "To Uppercase First Letter", - "args": [ - { - "type": "STRING", - "name": "text", - "description": "text", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Return the input string with the first letter of each word converted to an uppercase letter and the rest of the letters in the word converted to lowercase.", - "impl": "$0($1)" - }, - { - "id": "rept", - "displayName": "Repeat String", - "args": [ - { - "type": "STRING", - "name": "text", - "description": "text to repeat", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "count", - "description": "number of times to repeat the text", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Return text repeated Count times. rept('x', 5) returns 'xxxxx'", - "impl": "$0($1,$2)" - }, - { - "id": "replace", - "displayName": "Replace", - "args": [ - { - "type": "STRING", - "name": "text", - "description": "original text", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "start", - "description": "index in the original text from where to begin the replacement.", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "length", - "description": "number of characters to be replaced", - "isMandatory": true - }, - { - "type": "STRING", - "name": "replacement", - "description": "string to replace at the start index", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Returns text where an old text is substituted at a given start position and length, with a new text.", - "impl": "$0($1,$2,$3,$4)" - }, - { - "id": "round", - "displayName": "Round", - "args": [ - { - "type": "NUMBER", - "name": "num", - "description": "number to round off", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "precision", - "description": "number is rounded to the specified precision", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Round a number to a specified precision. If precision is not specified, round to the nearest integer", - "impl": "$0($1,$2)" - }, - { - "id": "sqrt", - "displayName": "Square Root Of", - "args": [ - { - "type": "NUMBER", - "name": "num", - "description": "number whose square root has to be calculated", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Return the square root of a number", - "impl": "$0($1)" - }, - { - "id": "trim", - "displayName": "Trim", - "args": [ - { - "type": "STRING", - "name": "text", - "description": "string to trim", - "isMandatory": true - } - ], - "type": "STRING", - "description": "Remove leading and trailing spaces, and replace all internal multiple spaces with a single space.", - "impl": "$0($1)" - }, - { - "id": "trunc", - "displayName": "Truncate a number", - "args": [ - { - "type": "NUMBER", - "name": "numA", - "description": "number to truncate", - "isMandatory": true - }, - { - "type": "NUMBER", - "name": "numB", - "description": "number of digits to truncate the number to", - "isMandatory": true - } - ], - "type": "NUMBER", - "description": "Truncate a number to a specified number of digits.", - "impl": "$0($1,$2)" - }, - { - "id": "split", - "displayName": "Split a string into array", - "args": [ - { - "type": "STRING", - "name": "string", - "description": "string to split", - "isMandatory": true - }, - { - "type": "STRING", - "name": "separator", - "description": "separator where the split should occur", - "isMandatory": true - } - ], - "type": "STRING[]", - "description": "Split a string into an array, given a separator", - "impl": "$0($1,$2)" - }, - { - "id": "unique", - "displayName": "Unique Values Of", - "args": [ - { - "type": "ARRAY", - "name": "input", - "description": "input array", - "isMandatory": true - } - ], - "type": "ARRAY|STRING[]|NUMBER[]|DATE[]|BOOLEAN[]", - "description": "Takes an array and returns unique elements within it", - "impl": "$0($1)" - }, - { - "id": "_validateForm", - "type": "BOOLEAN", - "displayName": "Validate Form", - "args": [], - "impl": "validate($form).length==0", - "description": "Validate Form" - }, - { - "id": "defaultSubmitSuccessHandler", - "displayName": "Default Submit Form Success Handler", - "args": [], - "type": "ANY", - "description": "Default Submit Form Success Handler", - "impl": "$0()" - }, - { - "id": "defaultSubmitErrorHandler", - "displayName": "Default Submit Form Error Handler", - "args": [ - { - "type": "STRING", - "name": "defaultSubmitErrorMessage", - "description": "Localized error message", - "isMandatory": true - } - ], - "type": "ANY", - "description": "Default Submit Form Error Handler", - "impl": "$0($1)" - }, - { - "id": "getEventPayload", - "type": "STRING|NUMBER|BOOLEAN|DATE|STRING[]|NUMBER[]|DATE[]|BOOLEAN[]|FILE[]|ARRAY|OBJECT", - "displayName": "Get Event Payload", - "args": [ - { - "type": "STRING", - "name": "input", - "description": "input param", - "isMandatory": false - } - ], - "impl": "$event.payload.$1", - "description": "Get Event Payload" - }, - { - "id": "setVariable", - "displayName": "Set Variable Value", - "args": [ - { - "type": "STRING", - "name": "variableName", - "description": "Name of the variable (supports dot notation e.g. 'address.city')", - "isMandatory": true - }, - { - "type": "STRING|NUMBER|BOOLEAN|DATE|AFCOMPONENT|OBJECT|ARRAY", - "name": "variableValue", - "description": "Value to set for the variable", - "isMandatory": true - }, - { - "type": "AFCOMPONENT|FORM", - "name": "normalFieldOrPanel", - "description": "Field or panel component to set the variable on (defaults to actual Form)", - "isMandatory": false - } - ], - "type": "VOID", - "description": "Set variable value on a field or form", - "impl": "$0($1,$2,$3)" - }, - { - "id": "getVariable", - "displayName": "Get Variable Value", - "args": [ - { - "type": "STRING", - "name": "variableName", - "description": "Name of the variable (supports dot notation e.g. 'address.city')", - "isMandatory": true - }, - { - "type": "AFCOMPONENT|FORM", - "name": "normalFieldOrPanel", - "description": "Field or panel component to get the value from (defaults to actual Form)", - "isMandatory": false - } - ], - "type": "STRING|NUMBER|BOOLEAN|DATE|OBJECT|ARRAY|AFCOMPONENT", - "description": "Get field or form variable value", - "impl": "$0($1,$2)" - }, - { - "id": "exportFormData", - "displayName": "Export Form Data", - "args": [ - { - "type": "BOOLEAN", - "name": "stringify", - "description": "Convert the form data to a JSON string, defaults to true", - "isMandatory": false - }, - { - "type": "STRING", - "name": "key", - "description": "The key to get the value for (supports dot notation e.g. 'address.city'), defaults to all form data", - "isMandatory": false - } - ], - "type": "STRING|OBJECT", - "description": "Export form data as a JSON string", - "impl": "$0($1,$2)" - }, - { - "id": "importData", - "displayName": "Import Form Data", - "args": [ - { - "type": "OBJECT", - "name": "data", - "description": "The form data to set", - "isMandatory": true - } - ], - "type": "VOID", - "description": "Import Form Data", - "impl": "importData($1)" - }, - { - "id": "validate", - "type": "BOOLEAN", - "displayName": "Validate", - "args": [ - { - "type": "AFCOMPONENT|FORM", - "name": "field", - "description": "Field, panel or form component to validate", - "isMandatory": true - } - ], - "impl": "$0($1).length==0", - "description": "Validate" - }, - { - "id": "downloadDoR", - "type": "ANY", - "displayName": "Download DoR", - "args": [ - { - "type": "STRING", - "name": "fileName", - "description": "The name of the file to be downloaded. Defaults to 'Downloaded_DoR.pdf' if not specified.", - "isMandatory": false - } - ], - "impl": "$0($1)", - "description": "Download DoR" - } - ] -} diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/grammar/annotated_subset_grammar.json b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/grammar/annotated_subset_grammar.json deleted file mode 100644 index 79420e8d..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/grammar/annotated_subset_grammar.json +++ /dev/null @@ -1,1114 +0,0 @@ -{ - "_INSTRUCTIONS": { - "purpose": "SIMPLIFIED SUBSET of AEM Forms grammar for AI-powered rule generation. This is a SUBSET of annotated_grammar.json - all structures are AEM-compatible.", - "pattern": "When [COMPONENT] [TRIGGER_EVENT] [optional: condition] Then [actions] [optional: Else [actions]]", - "node_types": { - "SEQUENCE": "Contains items in exact order. Must include all items specified in the rule.", - "CHOICE": "Select exactly ONE option based on natural language keywords.", - "ARRAY": "Contains one or more items of the same type (e.g., multiple actions).", - "TERMINAL": "Leaf node containing actual values (form objects, literals, functions).", - "LITERAL_TOKEN": "Words like 'When', 'Then', 'Else', 'to' that appear in rules as structure. Include as nodes with nodeName set to the literal word and value: null." - }, - "critical_rules": { - "VARIABLE_transparency": "When a node has rule: 'VARIABLE', do NOT create a VARIABLE node. Instead, put the actual value directly in the parent node.", - "CONDITION_property": "All CONDITION nodes MUST include property 'nested': false", - "trigger_vs_condition": "Trigger event (click, change) is separate from conditions (field equals value). Never combine them with AND/OR.", - "else_optional": "Only include Else block and second BLOCK_STATEMENTS when else actions are explicitly mentioned in natural language.", - "no_arithmetic_expressions": "For calculations like a + b * c, use FUNCTION_CALL with a custom function instead of BINARY_EXPRESSION.", - "function_for_complexity": "Any complex logic (string concat, API calls, data transformation) should be done via FUNCTION_CALL with custom functions." - }, - "supported_actions": [ - "SHOW_STATEMENT", "HIDE_STATEMENT", "SET_VALUE_STATEMENT", "CLEAR_VALUE_STATEMENT", - "ENABLE_STATEMENT", "DISABLE_STATEMENT", "SET_FOCUS", "DISPATCH_EVENT", - "FUNCTION_CALL", "SET_PROPERTY", "RESET_FORM", "VALIDATE_FORM", - "SUBMIT_FORM", "SAVE_FORM", "NAVIGATE_TO", "ADD_INSTANCE", - "REMOVE_INSTANCE", "NAVIGATE_IN_PANEL", "SET_VARIABLE" - ], - "not_supported": { - "actions": ["WSDL_STATEMENT", "ASYNC_FUNCTION_CALL"], - "expressions": ["BINARY_EXPRESSION (use FUNCTION_CALL)", "STRING_BINARY_EXPRESSION", "ARITHMETIC_EXPRESSION"], - "alternative": "Use FUNCTION_CALL with custom functions for complex logic" - } - }, - "_PATTERN_TEMPLATE": { - "description": "Standard structure for all trigger event rules", - "structure": { - "nodeName": "ROOT", - "items": [{ - "nodeName": "STATEMENT", - "choice": { - "nodeName": "TRIGGER_SCRIPTS", - "items": [{ - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - "COMPONENT (what triggers)", - "TRIGGER_EVENT (standard: 'is clicked', 'is changed', 'is initialised' OR custom event name)", - "{ nodeName: 'When', value: null } (literal token)", - "TRIGGER_EVENT_SCRIPTS (contains condition, then, actions, else, else-actions)" - ] - }] - } - }] - } - }, - "ROOT": { - "rule": "STATEMENT", - "description": "The root node of any rule. Always start here. Contains exactly ONE item: a STATEMENT node.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "ROOT", - "items": ["exactly 1 STATEMENT"] - } - }, - "STATEMENT": { - "rule": "TRIGGER_SCRIPTS", - "description": "Top-level statement type. For trigger event rules, always choose TRIGGER_SCRIPTS.", - "node_type": "CHOICE", - "choice_options": ["TRIGGER_SCRIPTS"], - "how_to_choose": "For When-Then-Else rules, always select TRIGGER_SCRIPTS", - "structure": { - "nodeName": "STATEMENT", - "choice": {"nodeName": "TRIGGER_SCRIPTS", "items": []} - } - }, - "TRIGGER_SCRIPTS": { - "rule": "SINGLE_TRIGGER_SCRIPTS", - "choiceName": "On Trigger Event", - "description": "Container for a single trigger-based rule. Contains exactly ONE item: SINGLE_TRIGGER_SCRIPTS.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "TRIGGER_SCRIPTS", - "items": ["exactly 1 SINGLE_TRIGGER_SCRIPTS"] - } - }, - "SINGLE_TRIGGER_SCRIPTS": { - "rule": "COMPONENT TRIGGER_EVENT When TRIGGER_EVENT_SCRIPTS", - "description": "SEQUENCE NODE with exactly 4 items in order: 1) COMPONENT (what triggers), 2) TRIGGER_EVENT (event type), 3) 'When' literal token, 4) TRIGGER_EVENT_SCRIPTS (condition + actions).", - "node_type": "SEQUENCE", - "items_order": [ - "1. COMPONENT - The form component that triggers the rule", - "2. TRIGGER_EVENT - The event type (standard: 'is clicked', 'is changed', 'is initialised' OR custom event)", - "3. 'When' literal token - {nodeName: 'When', value: null}", - "4. TRIGGER_EVENT_SCRIPTS - Contains condition and actions" - ], - "structure": { - "nodeName": "SINGLE_TRIGGER_SCRIPTS", - "items": [ - "COMPONENT object", - "TRIGGER_EVENT object", - "{nodeName: 'When', value: null}", - "TRIGGER_EVENT_SCRIPTS object" - ] - } - }, - "COMPONENT": { - "rule": "VARIABLE", - "choiceName": "Form Object", - "description": "TERMINAL NODE: A form component (button, text field, etc.). Use VARIABLE transparency rule - put form object directly here, do NOT create VARIABLE node.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "COMPONENT", - "value": { - "id": "$form.componentID", - "displayName": "Component Display Name", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Parent/Component/", - "name": "componentName", - "parent": "$form.parentID", - "metadata": {} - } - }, - "type_reference": "Use full type from treeJson: FORM (for form), AFCOMPONENT|PANEL (for panels), AFCOMPONENT|FIELD|TEXT FIELD|STRING (for text inputs), etc." - }, - "TRIGGER_EVENT": { - "choiceName": "String", - "description": "TERMINAL NODE: The event that triggers the rule. Standard events: 'is clicked', 'is changed', 'is initialised'. Custom events: use exact name provided by user.", - "node_type": "TERMINAL", - "standard_events": { - "is clicked": "When component is clicked", - "is changed": "When component value changes", - "is initialised": "When component initializes/loads" - }, - "custom_events": { - "enabled": true, - "description": "If event doesn't match standard events, use exact name provided by user", - "examples": ["submit", "abc", "myCustomEvent"] - }, - "value_structure": { - "nodeName": "TRIGGER_EVENT", - "value": "is clicked" - } - }, - "TRIGGER_EVENT_SCRIPTS": { - "rule": "CONDITION Then BLOCK_STATEMENTS Else BLOCK_STATEMENTS", - "choiceName": "When", - "description": "SEQUENCE NODE with 5 items: 1) CONDITION (optional), 2) 'Then' literal token, 3) BLOCK_STATEMENTS (actions), 4) 'Else' literal token (only if else actions exist), 5) BLOCK_STATEMENTS for else (only if else actions exist).", - "node_type": "SEQUENCE", - "items_order": [ - "1. CONDITION - Optional condition to check (can be empty/always true)", - "2. 'Then' literal token - {nodeName: 'Then', value: null}", - "3. BLOCK_STATEMENTS - Actions to execute when condition is true", - "4. 'Else' literal token - {nodeName: 'Else', value: null} - ONLY if else actions mentioned", - "5. BLOCK_STATEMENTS - Actions for else - ONLY if else actions mentioned" - ], - "structure_with_else": { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - "CONDITION object", - "{nodeName: 'Then', value: null}", - "BLOCK_STATEMENTS object (then actions)", - "{nodeName: 'Else', value: null}", - "BLOCK_STATEMENTS object (else actions)" - ] - }, - "structure_without_else": { - "nodeName": "TRIGGER_EVENT_SCRIPTS", - "items": [ - "CONDITION object", - "{nodeName: 'Then', value: null}", - "BLOCK_STATEMENTS object (then actions)" - ] - } - }, - "CONDITION": { - "rule": "COMPARISON_EXPRESSION | BOOLEAN_BINARY_EXPRESSION", - "choiceName": "When", - "description": "CHOICE NODE: Select COMPARISON_EXPRESSION for simple single comparisons. Select BOOLEAN_BINARY_EXPRESSION when condition contains AND/OR logic. MUST include 'nested: false' property. For EMPTY/NO condition, use choice: null (NOT {} empty object!).", - "node_type": "CHOICE", - "how_to_choose": { - "COMPARISON_EXPRESSION": "Single comparison: 'field equals 5', 'textinput is empty', 'number > 10'", - "BOOLEAN_BINARY_EXPRESSION": "Multiple conditions with AND/OR: 'field equals 5 AND textinput is not empty'", - "null": "NO condition (always execute) - use choice: null" - }, - "required_property": "nested: false", - "empty_condition": "When there is NO condition (always execute), use choice: null - NOT {} empty object!", - "structure_with_condition": { - "nodeName": "CONDITION", - "nested": false, - "choice": {"nodeName": "COMPARISON_EXPRESSION or BOOLEAN_BINARY_EXPRESSION", "items": []} - }, - "structure_empty": { - "_note": "Use this when there is NO condition - choice is null, NOT {}", - "nodeName": "CONDITION", - "nested": false, - "choice": null - } - }, - "COMPARISON_EXPRESSION": { - "rule": "EXPRESSION OPERATOR EXPRESSION", - "choiceName": "Condition", - "description": "SEQUENCE NODE: Single comparison with 3 items: 1) left EXPRESSION, 2) OPERATOR, 3) right EXPRESSION.", - "node_type": "SEQUENCE", - "items_order": [ - "1. EXPRESSION - Left side (usually a form component)", - "2. OPERATOR - Comparison operator (equals, greater than, is empty, etc.)", - "3. EXPRESSION - Right side (value, literal, or another component) - NOTE: For unary operators like IS_EMPTY, this may be omitted" - ], - "examples": { - "field equals value": ["COMPONENT(numberInput)", "EQUALS_TO", "NUMERIC_LITERAL(10)"], - "field is empty": ["COMPONENT(textInput)", "IS_EMPTY", "(no right expression)"], - "field greater than value": ["COMPONENT(age)", "GREATER_THAN", "NUMERIC_LITERAL(18)"] - }, - "structure": { - "nodeName": "COMPARISON_EXPRESSION", - "items": [ - "EXPRESSION object (left)", - "OPERATOR object", - "EXPRESSION object (right)" - ] - } - }, - "BOOLEAN_BINARY_EXPRESSION": { - "rule": "CONDITION OPERATOR CONDITION", - "description": "SEQUENCE NODE: Combines two conditions with AND/OR. Contains 3 items: 1) left CONDITION, 2) OPERATOR (AND/OR), 3) right CONDITION.", - "node_type": "SEQUENCE", - "items_order": [ - "1. CONDITION - Left condition", - "2. OPERATOR - AND or OR", - "3. CONDITION - Right condition" - ], - "structure": { - "nodeName": "BOOLEAN_BINARY_EXPRESSION", - "items": [ - "CONDITION object (left)", - "OPERATOR object (AND/OR)", - "CONDITION object (right)" - ] - } - }, - "EXPRESSION": { - "rule": "COMPONENT | STRING_LITERAL | NUMERIC_LITERAL | BOOLEAN_LITERAL | DATE_LITERAL | FUNCTION_CALL | UTM_PARAMETER | QUERY_PARAMETER | BROWSER_DETAILS | URL_DETAILS | GET_VARIABLE", - "description": "CHOICE NODE: Select based on value type and source. NOTE: For complex operations (arithmetic, string concat), use FUNCTION_CALL with a custom function.", - "node_type": "CHOICE", - "how_to_choose": { - "COMPONENT": "Form field references (e.g., 'Text Input', 'Button', 'numberInput')", - "STRING_LITERAL": "Text values in quotes or mentioned as text (e.g., 'hello', \"test\")", - "NUMERIC_LITERAL": "Numbers (e.g., 5, 10.5, -3)", - "BOOLEAN_LITERAL": "true or false values", - "DATE_LITERAL": "Date values", - "FUNCTION_CALL": "Function names or any calculated/complex values (e.g., 'calculateTotal()', 'formatName(first, last)')", - "UTM_PARAMETER": "UTM tracking parameters (utm_source, utm_medium, utm_campaign, utm_term, utm_content)", - "QUERY_PARAMETER": "URL query parameters (e.g., 'query param xyz')", - "BROWSER_DETAILS": "Browser info (userAgent, language, platform)", - "URL_DETAILS": "URL components (hostname, pathname)", - "GET_VARIABLE": "Retrieve stored variable value" - }, - "structure": { - "nodeName": "EXPRESSION", - "choice": {"nodeName": "STRING_LITERAL or NUMERIC_LITERAL or other", "value or items": "varies"} - } - }, - "OPERATOR": { - "rule": "LESS_THAN | GREATER_THAN | EQUALS_TO | NOT_EQUALS_TO | CONTAINS | DOES_NOT_CONTAIN | STARTS_WITH | ENDS_WITH | AND | OR | HAS_SELECTED | IS_NOT_EMPTY | IS_EMPTY | IS_TRUE | IS_FALSE | IS_BEFORE | IS_AFTER | IS_VALID | IS_NOT_VALID", - "description": "CHOICE NODE: Select operator based on natural language. NOTE: Arithmetic operators (PLUS, MINUS, MULTIPLY, DIVIDE) are NOT in this subset - use FUNCTION_CALL for calculations.", - "node_type": "CHOICE", - "common_mappings": { - "equals, is equal to, is, same as": "EQUALS_TO", - "not equals, is not equal to, !=, different from": "NOT_EQUALS_TO", - "greater than, more than, >": "GREATER_THAN", - "less than, smaller than, <": "LESS_THAN", - "contains, includes": "CONTAINS", - "does not contain, excludes": "DOES_NOT_CONTAIN", - "starts with, begins with": "STARTS_WITH", - "ends with, finishes with": "ENDS_WITH", - "and, &&": "AND", - "or, ||": "OR", - "is empty, is blank, has no value": "IS_EMPTY", - "is not empty, has value, is filled": "IS_NOT_EMPTY", - "is true, is checked": "IS_TRUE", - "is false, is unchecked": "IS_FALSE", - "is before, before": "IS_BEFORE", - "is after, after": "IS_AFTER", - "has selected, selected": "HAS_SELECTED", - "is valid, valid": "IS_VALID", - "is not valid, invalid": "IS_NOT_VALID" - }, - "structure": { - "nodeName": "OPERATOR", - "choice": { - "nodeName": "EQUALS_TO", - "value": null - } - }, - "structure_examples": { - "equals": {"nodeName": "OPERATOR", "choice": {"nodeName": "EQUALS_TO", "value": null}}, - "not_equals": {"nodeName": "OPERATOR", "choice": {"nodeName": "NOT_EQUALS_TO", "value": null}}, - "and": {"nodeName": "OPERATOR", "choice": {"nodeName": "AND", "value": null}}, - "greater_than": {"nodeName": "OPERATOR", "choice": {"nodeName": "GREATER_THAN", "value": null}} - } - }, - "EQUALS_TO": { - "choiceName": "is equal to", - "description": "Equality comparison. Use when NL says 'equals', 'is equal to', 'is', 'same as'.", - "node_type": "TERMINAL", - "value": null - }, - "NOT_EQUALS_TO": { - "choiceName": "is not equal to", - "description": "Not equal comparison. Use when NL says 'not equals', 'is not equal to', '!=', 'different from'.", - "node_type": "TERMINAL", - "value": null - }, - "GREATER_THAN": { - "choiceName": "is greater than", - "description": "Greater than comparison. Use when NL says 'greater than', 'more than', '>'.", - "node_type": "TERMINAL", - "value": null - }, - "LESS_THAN": { - "choiceName": "is less than", - "description": "Less than comparison. Use when NL says 'less than', 'smaller than', '<'.", - "node_type": "TERMINAL", - "value": null - }, - "CONTAINS": { - "choiceName": "contains", - "description": "Contains check. Use when NL says 'contains', 'includes'.", - "node_type": "TERMINAL", - "value": null - }, - "DOES_NOT_CONTAIN": { - "choiceName": "does not contain", - "description": "Does not contain. Use when NL says 'does not contain', 'excludes'.", - "node_type": "TERMINAL", - "value": null - }, - "STARTS_WITH": { - "choiceName": "starts with", - "description": "String starts with. Use when NL says 'starts with', 'begins with'.", - "node_type": "TERMINAL", - "value": null - }, - "ENDS_WITH": { - "choiceName": "ends with", - "description": "String ends with. Use when NL says 'ends with', 'finishes with'.", - "node_type": "TERMINAL", - "value": null - }, - "AND": { - "choiceName": "And", - "description": "Logical AND. Both conditions must be true. Use when NL says 'and', '&&'.", - "node_type": "TERMINAL", - "value": null - }, - "OR": { - "choiceName": "Or", - "description": "Logical OR. At least one condition must be true. Use when NL says 'or', '||'.", - "node_type": "TERMINAL", - "value": null - }, - "IS_EMPTY": { - "choiceName": "is empty", - "description": "Checks if field is empty/blank. Unary operator (no right expression needed). Use when NL says 'is empty', 'is blank', 'has no value'.", - "node_type": "TERMINAL", - "value": null - }, - "IS_NOT_EMPTY": { - "choiceName": "is not empty", - "description": "Checks if field has value. Unary operator. Use when NL says 'is not empty', 'has value', 'is filled'.", - "node_type": "TERMINAL", - "value": null - }, - "IS_TRUE": { - "choiceName": "is true", - "description": "Checks if boolean is true. Unary operator. Use when NL says 'is true', 'is checked'.", - "node_type": "TERMINAL", - "value": null - }, - "IS_FALSE": { - "choiceName": "is false", - "description": "Checks if boolean is false. Unary operator. Use when NL says 'is false', 'is unchecked'.", - "node_type": "TERMINAL", - "value": null - }, - "IS_BEFORE": { - "choiceName": "is before", - "description": "Date comparison - checks if date is before another. Use when NL says 'is before', 'before'.", - "node_type": "TERMINAL", - "value": null, - "operatorType": [["BOOLEAN", "DATE", "DATE"]] - }, - "IS_AFTER": { - "choiceName": "is after", - "description": "Date comparison - checks if date is after another. Use when NL says 'is after', 'after'.", - "node_type": "TERMINAL", - "value": null, - "operatorType": [["BOOLEAN", "DATE", "DATE"]] - }, - "HAS_SELECTED": { - "choiceName": "has selected", - "description": "Checks if multi-select field has a specific value selected. Use when NL says 'has selected', 'selected'.", - "node_type": "TERMINAL", - "value": null, - "operatorType": [["BOOLEAN", "STRING[]", "STRING"], ["BOOLEAN", "NUMBER[]", "NUMBER"]] - }, - "IS_VALID": { - "choiceName": "is valid", - "description": "Checks if field passes validation. Unary operator. Use when NL says 'is valid', 'valid'.", - "node_type": "TERMINAL", - "value": null, - "operatorType": [["BOOLEAN", "STRING"], ["BOOLEAN", "NUMBER"], ["BOOLEAN", "DATE"]] - }, - "IS_NOT_VALID": { - "choiceName": "is not valid", - "description": "Checks if field fails validation. Unary operator. Use when NL says 'is not valid', 'invalid'.", - "node_type": "TERMINAL", - "value": null, - "operatorType": [["BOOLEAN", "STRING"], ["BOOLEAN", "NUMBER"], ["BOOLEAN", "DATE"]] - }, - "UTM_PARAMETER": { - "rule": null, - "choiceName": "UTM Parameter", - "description": "TERMINAL NODE: Access UTM tracking parameters from URL. Options: utm_source, utm_medium, utm_campaign, utm_term, utm_content.", - "node_type": "TERMINAL", - "dataType": "STRING", - "options": { - "utm_source": "UTM Source", - "utm_medium": "UTM Medium", - "utm_campaign": "UTM Campaign", - "utm_term": "UTM Term", - "utm_content": "UTM Content" - }, - "value_structure": { - "nodeName": "UTM_PARAMETER", - "value": "utm_source" - } - }, - "QUERY_PARAMETER": { - "rule": null, - "choiceName": "Query Parameter", - "description": "TERMINAL NODE: Access URL query parameters. Use when NL mentions 'query param', 'URL parameter', or specific param names.", - "node_type": "TERMINAL", - "dataType": "STRING", - "value_structure": { - "nodeName": "QUERY_PARAMETER", - "value": "paramName" - } - }, - "BROWSER_DETAILS": { - "rule": null, - "choiceName": "Browser Parameter", - "description": "TERMINAL NODE: Access browser information. Options: userAgent, language, platform.", - "node_type": "TERMINAL", - "dataType": "STRING", - "options": { - "userAgent": "Browser Agent", - "language": "Browser Language", - "platform": "Browser Platform" - }, - "value_structure": { - "nodeName": "BROWSER_DETAILS", - "value": "userAgent" - } - }, - "URL_DETAILS": { - "rule": null, - "choiceName": "URL Parameter", - "description": "TERMINAL NODE: Access URL components. Options: hostname, pathname.", - "node_type": "TERMINAL", - "dataType": "STRING", - "options": { - "hostname": "Host name", - "pathname": "Path" - }, - "value_structure": { - "nodeName": "URL_DETAILS", - "value": "hostname" - } - }, - "GET_VARIABLE": { - "rule": "key VARIABLE_NAME from AFCOMPONENT", - "choiceName": "Get Variable Value", - "description": "SEQUENCE NODE: Retrieve a stored variable value. Contains 4 items: 1) 'key' literal, 2) VARIABLE_NAME, 3) 'from' literal, 4) AFCOMPONENT.", - "node_type": "SEQUENCE", - "dataType": "STRING|NUMBER|BOOLEAN|DATE|OBJECT|ARRAY", - "items_order": [ - "1. 'key' literal token - {nodeName: 'key', value: null}", - "2. VARIABLE_NAME - The variable key (string or component value)", - "3. 'from' literal token - {nodeName: 'from', value: null}", - "4. AFCOMPONENT - The component storing the variable" - ], - "structure": { - "nodeName": "GET_VARIABLE", - "items": [ - "{nodeName: 'key', value: null}", - "VARIABLE_NAME object", - "{nodeName: 'from', value: null}", - "AFCOMPONENT object" - ] - } - }, - "VARIABLE_NAME": { - "rule": "AFCOMPONENT | STRING_LITERAL | FUNCTION_CALL | GET_VARIABLE", - "description": "CHOICE NODE: The variable key - can be a string, component value, function result, or another variable.", - "node_type": "CHOICE", - "dataType": "STRING|AFCOMPONENT", - "how_to_choose": { - "STRING_LITERAL": "Direct variable name as string", - "AFCOMPONENT": "Variable name from a form field", - "FUNCTION_CALL": "Variable name from function result", - "GET_VARIABLE": "Variable name from another variable" - } - }, - "VARIABLE_VALUE": { - "rule": "STRING_LITERAL | NUMERIC_LITERAL | BOOLEAN_LITERAL | AFCOMPONENT | FUNCTION_CALL | GET_VARIABLE", - "description": "CHOICE NODE: The value to store in a variable.", - "node_type": "CHOICE", - "dataType": "STRING|NUMBER|BOOLEAN|DATE|AFCOMPONENT|OBJECT|ARRAY", - "how_to_choose": { - "STRING_LITERAL": "Direct string value", - "NUMERIC_LITERAL": "Direct number value", - "BOOLEAN_LITERAL": "Direct boolean value", - "AFCOMPONENT": "Value from a form field", - "FUNCTION_CALL": "Value from function result", - "GET_VARIABLE": "Value from another variable" - } - }, - "MEMBER_EXPRESSION": { - "rule": "PROPERTY_LIST of COMPONENT", - "choiceName": "Object Property", - "description": "SEQUENCE NODE: Access a property of a component. Contains 3 items: 1) PROPERTY_LIST, 2) 'of' literal, 3) COMPONENT. Used in SET_PROPERTY action.", - "node_type": "SEQUENCE", - "items_order": [ - "1. PROPERTY_LIST - The property to access", - "2. 'of' literal token - {nodeName: 'of', value: null}", - "3. COMPONENT - The component whose property to access" - ], - "structure": { - "nodeName": "MEMBER_EXPRESSION", - "items": [ - "PROPERTY_LIST object", - "{nodeName: 'of', value: null}", - "COMPONENT object" - ] - } - }, - "PROPERTY_LIST": { - "rule": null, - "description": "TERMINAL NODE: A property name to access from a component. Common properties: visible, enabled, label, placeholder, required, value, readOnly.", - "node_type": "TERMINAL", - "dataType": "ANY", - "common_properties": ["visible", "enabled", "label", "placeholder", "required", "value", "readOnly"], - "value_structure": { - "nodeName": "PROPERTY_LIST", - "value": { - "displayName": "Property Name" - } - } - }, - "PANEL": { - "rule": "VARIABLE", - "description": "TERMINAL NODE: A panel component. Use VARIABLE transparency - put panel object directly.", - "node_type": "TERMINAL", - "dataType": "PANEL", - "value_structure": { - "nodeName": "PANEL", - "value": { - "id": "$form.panelId", - "displayName": "Panel Name", - "type": "AFCOMPONENT|PANEL", - "name": "panelName", - "parent": "$form" - } - } - }, - "BLOCK_STATEMENTS": { - "rule": "BLOCK_STATEMENT+", - "description": "ARRAY NODE: Contains one or more actions to execute. Each action mentioned in NL becomes a separate BLOCK_STATEMENT item.", - "node_type": "ARRAY", - "structure": { - "nodeName": "BLOCK_STATEMENTS", - "items": [ - "BLOCK_STATEMENT object 1", - "BLOCK_STATEMENT object 2" - ] - } - }, - "BLOCK_STATEMENT": { - "rule": "HIDE_STATEMENT | SHOW_STATEMENT | SET_VALUE_STATEMENT | FUNCTION_CALL | ENABLE_STATEMENT | DISABLE_STATEMENT | CLEAR_VALUE_STATEMENT | SUBMIT_FORM | RESET_FORM | VALIDATE_FORM | SAVE_FORM | NAVIGATE_TO | DISPATCH_EVENT | SET_FOCUS | ADD_INSTANCE | REMOVE_INSTANCE | NAVIGATE_IN_PANEL | SET_VARIABLE | SET_PROPERTY", - "description": "CHOICE NODE: Select action type based on NL keywords. NOTE: WSDL_STATEMENT and ASYNC_FUNCTION_CALL are NOT supported - use FUNCTION_CALL with custom functions instead.", - "node_type": "CHOICE", - "how_to_choose": { - "HIDE_STATEMENT": "hide, make invisible, don't show", - "SHOW_STATEMENT": "show, display, make visible, reveal", - "SET_VALUE_STATEMENT": "set to, assign, make equal, set value", - "FUNCTION_CALL": "call function, invoke, execute function, API call, calculate, or function name", - "ENABLE_STATEMENT": "enable, make editable", - "DISABLE_STATEMENT": "disable, make read-only", - "CLEAR_VALUE_STATEMENT": "clear, reset value, empty field", - "SUBMIT_FORM": "submit form, submit", - "RESET_FORM": "reset form, reset panel, reset", - "VALIDATE_FORM": "validate form, validate panel, validate field", - "SAVE_FORM": "save form, save", - "NAVIGATE_TO": "navigate to, go to URL, open URL", - "DISPATCH_EVENT": "dispatch event, trigger event, fire event", - "SET_FOCUS": "focus, set focus", - "ADD_INSTANCE": "add instance, add repeatable, add row", - "REMOVE_INSTANCE": "remove instance, remove repeatable, remove row", - "NAVIGATE_IN_PANEL": "navigate panel, go to next, go to previous, next panel, previous panel", - "SET_VARIABLE": "set variable, store variable", - "SET_PROPERTY": "set property, change property, update label, change placeholder" - }, - "structure": { - "nodeName": "BLOCK_STATEMENT", - "choice": {"nodeName": "HIDE_STATEMENT or SHOW_STATEMENT or other", "items": []} - } - }, - "HIDE_STATEMENT": { - "rule": "AFCOMPONENT", - "choiceName": "Hide", - "description": "Hides a component. Contains 1 item: AFCOMPONENT to hide. Use VARIABLE transparency - put form object directly.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "HIDE_STATEMENT", - "items": ["AFCOMPONENT object"] - } - }, - "SHOW_STATEMENT": { - "rule": "AFCOMPONENT", - "choiceName": "Show", - "description": "Shows a component. Contains 1 item: AFCOMPONENT to show. Use VARIABLE transparency - put form object directly.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "SHOW_STATEMENT", - "items": ["AFCOMPONENT object"] - } - }, - "ENABLE_STATEMENT": { - "rule": "AFCOMPONENT", - "choiceName": "Enable", - "description": "Enables a component. Contains 1 item: AFCOMPONENT to enable.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "ENABLE_STATEMENT", - "items": ["AFCOMPONENT object"] - } - }, - "DISABLE_STATEMENT": { - "rule": "AFCOMPONENT", - "choiceName": "Disable", - "description": "Disables a component. Contains 1 item: AFCOMPONENT to disable.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "DISABLE_STATEMENT", - "items": ["AFCOMPONENT object"] - } - }, - "CLEAR_VALUE_STATEMENT": { - "rule": "VALUE_FIELD", - "choiceName": "Clear Value of", - "description": "Clears value of a field. Contains 1 item: VALUE_FIELD to clear.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "CLEAR_VALUE_STATEMENT", - "items": ["VALUE_FIELD object"] - } - }, - "SUBMIT_FORM": { - "rule": "", - "choiceName": "Submit Form", - "description": "Submits the form. No items needed - empty items array.", - "node_type": "TERMINAL", - "structure": { - "nodeName": "SUBMIT_FORM", - "items": [] - } - }, - "RESET_FORM": { - "rule": "VARIABLE", - "choiceName": "Reset", - "description": "Resets form, panel, or component to initial state. Contains 1 item: component to reset. Use VARIABLE transparency.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "RESET_FORM", - "items": ["AFCOMPONENT object (form, panel, or field)"] - } - }, - "VALIDATE_FORM": { - "rule": "VARIABLE", - "choiceName": "Validate", - "description": "Validates form, panel, or component. Contains 1 item: component to validate. Use VARIABLE transparency.", - "node_type": "SEQUENCE", - "structure": { - "nodeName": "VALIDATE_FORM", - "items": ["AFCOMPONENT object (form, panel, or field)"] - } - }, - "SAVE_FORM": { - "rule": "", - "choiceName": "Save Form", - "description": "Saves the form data. No items needed - empty items array.", - "node_type": "TERMINAL", - "structure": { - "nodeName": "SAVE_FORM", - "items": [] - } - }, - "NAVIGATE_TO": { - "rule": "NAVIGATE_TO_EXPRESSION in NAVIGATE_METHOD_OPTIONS", - "choiceName": "Navigate to URL", - "description": "Navigates to a URL. SEQUENCE with 3 items: 1) NAVIGATE_TO_EXPRESSION (URL), 2) 'in' literal, 3) NAVIGATE_METHOD_OPTIONS (window type).", - "node_type": "SEQUENCE", - "items_order": [ - "1. NAVIGATE_TO_EXPRESSION - URL to navigate to (URL_LITERAL, COMPONENT, or FUNCTION_CALL)", - "2. 'in' literal token - {nodeName: 'in', value: null}", - "3. NAVIGATE_METHOD_OPTIONS - NEW_WINDOW, NEW_TAB, or SAME_TAB" - ], - "structure": { - "nodeName": "NAVIGATE_TO", - "items": [ - "NAVIGATE_TO_EXPRESSION object", - "{nodeName: 'in', value: null}", - "NAVIGATE_METHOD_OPTIONS object" - ] - } - }, - "NAVIGATE_TO_EXPRESSION": { - "rule": "URL_LITERAL | COMPONENT | FUNCTION_CALL", - "description": "CHOICE NODE: The URL to navigate to - can be literal URL, field value, or function result.", - "node_type": "CHOICE", - "how_to_choose": { - "URL_LITERAL": "Direct URL string like 'https://example.com'", - "COMPONENT": "URL from a form field", - "FUNCTION_CALL": "URL returned by a function" - } - }, - "NAVIGATE_METHOD_OPTIONS": { - "rule": "NEW_WINDOW | NEW_TAB | SAME_TAB", - "description": "CHOICE NODE: How to open the URL.", - "node_type": "CHOICE", - "how_to_choose": { - "NEW_WINDOW": "Open in new browser window", - "NEW_TAB": "Open in new tab (default)", - "SAME_TAB": "Open in current tab" - } - }, - "NEW_WINDOW": { - "choiceName": "New Window", - "description": "Open URL in a new browser window.", - "node_type": "TERMINAL", - "value": null - }, - "NEW_TAB": { - "choiceName": "New Tab", - "description": "Open URL in a new browser tab.", - "node_type": "TERMINAL", - "value": null - }, - "SAME_TAB": { - "choiceName": "Same Tab", - "description": "Open URL in the current browser tab.", - "node_type": "TERMINAL", - "value": null - }, - "URL_LITERAL": { - "choiceName": "URL", - "description": "TERMINAL NODE: A literal URL string.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "URL_LITERAL", - "value": "https://example.com" - } - }, - "SET_FOCUS": { - "rule": "to AFCOMPONENT", - "choiceName": "Set Focus", - "description": "Sets focus to a component. SEQUENCE with 2 items: 1) 'to' literal, 2) AFCOMPONENT.", - "node_type": "SEQUENCE", - "items_order": [ - "1. 'to' literal token - {nodeName: 'to', value: null}", - "2. AFCOMPONENT - The component to focus" - ], - "structure": { - "nodeName": "SET_FOCUS", - "items": [ - "{nodeName: 'to', value: null}", - "AFCOMPONENT object" - ] - } - }, - "ADD_INSTANCE": { - "rule": "of REPEATABLE_COMPONENT", - "choiceName": "Add Instance", - "description": "Adds instance to repeatable panel. SEQUENCE with 2 items: 1) 'of' literal, 2) REPEATABLE_COMPONENT.", - "node_type": "SEQUENCE", - "items_order": [ - "1. 'of' literal token - {nodeName: 'of', value: null}", - "2. REPEATABLE_COMPONENT - The repeatable panel" - ], - "structure": { - "nodeName": "ADD_INSTANCE", - "items": [ - "{nodeName: 'of', value: null}", - "REPEATABLE_COMPONENT object" - ] - } - }, - "REMOVE_INSTANCE": { - "rule": "of REPEATABLE_COMPONENT", - "choiceName": "Remove Instance", - "description": "Removes instance from repeatable panel. SEQUENCE with 2 items: 1) 'of' literal, 2) REPEATABLE_COMPONENT.", - "node_type": "SEQUENCE", - "items_order": [ - "1. 'of' literal token - {nodeName: 'of', value: null}", - "2. REPEATABLE_COMPONENT - The repeatable panel" - ], - "structure": { - "nodeName": "REMOVE_INSTANCE", - "items": [ - "{nodeName: 'of', value: null}", - "REPEATABLE_COMPONENT object" - ] - } - }, - "REPEATABLE_COMPONENT": { - "rule": "VARIABLE", - "description": "TERMINAL NODE: A repeatable panel component. Use VARIABLE transparency.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "REPEATABLE_COMPONENT", - "value": { - "id": "$form.repeatablePanel", - "displayName": "Repeatable Panel", - "type": "AFCOMPONENT", - "name": "repeatablePanel", - "parent": "$form" - } - } - }, - "NAVIGATE_IN_PANEL": { - "rule": "PANEL_FOCUS_OPTION of PANEL", - "choiceName": "Navigate in Panel", - "description": "Navigates within a wizard/tabbed panel. SEQUENCE with 3 items: 1) PANEL_FOCUS_OPTION, 2) 'of' literal, 3) PANEL.", - "node_type": "SEQUENCE", - "items_order": [ - "1. PANEL_FOCUS_OPTION - NEXT_ITEM, PREVIOUS_ITEM, or FIRST_ITEM", - "2. 'of' literal token - {nodeName: 'of', value: null}", - "3. PANEL - The panel to navigate within" - ], - "structure": { - "nodeName": "NAVIGATE_IN_PANEL", - "items": [ - "PANEL_FOCUS_OPTION object", - "{nodeName: 'of', value: null}", - "PANEL object" - ] - } - }, - "PANEL_FOCUS_OPTION": { - "rule": "NEXT_ITEM | PREVIOUS_ITEM | FIRST_ITEM", - "description": "CHOICE NODE: Direction to navigate in panel.", - "node_type": "CHOICE", - "how_to_choose": { - "NEXT_ITEM": "Go to next panel/tab", - "PREVIOUS_ITEM": "Go to previous panel/tab", - "FIRST_ITEM": "Go to first panel/tab" - } - }, - "NEXT_ITEM": { - "choiceName": "Next Item", - "description": "Navigate to the next item in the panel.", - "node_type": "TERMINAL", - "value": null - }, - "PREVIOUS_ITEM": { - "choiceName": "Previous Item", - "description": "Navigate to the previous item in the panel.", - "node_type": "TERMINAL", - "value": null - }, - "FIRST_ITEM": { - "choiceName": "First Item", - "description": "Navigate to the first item in the panel.", - "node_type": "TERMINAL", - "value": null - }, - "SET_VARIABLE": { - "rule": "key VARIABLE_NAME value VARIABLE_VALUE on AFCOMPONENT", - "choiceName": "Set Variable Value", - "description": "Stores a variable value on a component. SEQUENCE with 6 items.", - "node_type": "SEQUENCE", - "items_order": [ - "1. 'key' literal token - {nodeName: 'key', value: null}", - "2. VARIABLE_NAME - The variable key (string or expression)", - "3. 'value' literal token - {nodeName: 'value', value: null}", - "4. VARIABLE_VALUE - The value to store", - "5. 'on' literal token - {nodeName: 'on', value: null}", - "6. AFCOMPONENT - The component to store the variable on" - ], - "structure": { - "nodeName": "SET_VARIABLE", - "items": [ - "{nodeName: 'key', value: null}", - "VARIABLE_NAME object", - "{nodeName: 'value', value: null}", - "VARIABLE_VALUE object", - "{nodeName: 'on', value: null}", - "AFCOMPONENT object" - ] - } - }, - "SET_VALUE_STATEMENT": { - "rule": "VALUE_FIELD to EXPRESSION", - "choiceName": "Set Value of", - "description": "Sets field value. SEQUENCE with 3 items: 1) VALUE_FIELD (target), 2) 'to' literal token, 3) EXPRESSION (new value).", - "node_type": "SEQUENCE", - "items_order": [ - "1. VALUE_FIELD - The field to set", - "2. 'to' literal token - {nodeName: 'to', value: null}", - "3. EXPRESSION - The value to set (use FUNCTION_CALL for calculated values)" - ], - "structure": { - "nodeName": "SET_VALUE_STATEMENT", - "items": [ - "VALUE_FIELD object", - "{nodeName: 'to', value: null}", - "EXPRESSION object" - ] - } - }, - "FUNCTION_CALL": { - "rule": "FUNCTION", - "choiceName": "Function Output", - "description": "TERMINAL NODE: Calls a custom or OOTB function. CRITICAL: Uses 'functionName' (object) + 'params' (array), NOT 'value.args'.", - "node_type": "TERMINAL", - "critical_structure_note": "Structure is {nodeName, parentNodeName, functionName: {id,displayName,type,args,impl}, params: [EXPRESSION...]}. DO NOT use value.args pattern.", - "value_structure": { - "nodeName": "FUNCTION_CALL", - "parentNodeName": "<nodeName of parent node>", - "functionName": { - "id": "funcId", - "displayName": "Function Description", - "type": "RETURN_TYPE", - "isDuplicate": false, - "displayPath": "", - "args": [{"type": "STRING", "name": "param1", "description": "param desc", "isMandatory": true}], - "impl": "$0($1)" - }, - "params": [ - {"nodeName": "EXPRESSION", "choice": {"nodeName": "...", "value": "..."}} - ] - } - }, - "DISPATCH_EVENT": { - "rule": "STRING_LITERAL on AFCOMPONENT", - "choiceName": "Dispatch Event", - "description": "SEQUENCE NODE: Fires a custom event on a component. Contains 3 items: 1) STRING_LITERAL (event name), 2) 'on' literal token, 3) AFCOMPONENT (target component or form).", - "node_type": "SEQUENCE", - "items_order": [ - "1. STRING_LITERAL - The event name to dispatch", - "2. 'on' literal token - {nodeName: 'on', value: null}", - "3. AFCOMPONENT - The target component or form to dispatch event on" - ], - "structure": { - "nodeName": "DISPATCH_EVENT", - "items": [ - {"nodeName": "STRING_LITERAL", "value": "myCustomEvent"}, - {"nodeName": "on", "value": null}, - {"nodeName": "AFCOMPONENT", "value": {"id": "$form.componentID", "displayName": "Component Name", "type": "AFCOMPONENT"}} - ] - } - }, - "SET_PROPERTY": { - "rule": "MEMBER_EXPRESSION to EXTENDED_EXPRESSION", - "choiceName": "Set Property", - "description": "SEQUENCE NODE: Sets a property of a component. Contains 3 items: 1) MEMBER_EXPRESSION (property of component), 2) 'to' literal token, 3) EXTENDED_EXPRESSION (new value).", - "node_type": "SEQUENCE", - "items_order": [ - "1. MEMBER_EXPRESSION - The property to set (e.g., 'visible of TextInput', 'label of Email')", - "2. 'to' literal token - {nodeName: 'to', value: null}", - "3. EXTENDED_EXPRESSION - The value to set the property to" - ], - "structure": { - "nodeName": "SET_PROPERTY", - "items": [ - {"nodeName": "MEMBER_EXPRESSION", "items": ["PROPERTY_LIST", "of literal", "COMPONENT"]}, - {"nodeName": "to", "value": null}, - {"nodeName": "EXTENDED_EXPRESSION", "choice": "value"} - ] - } - }, - "EXTENDED_EXPRESSION": { - "rule": "COMPONENT | DATE_LITERAL | STRING_LITERAL | BOOLEAN_LITERAL | NUMERIC_LITERAL | FUNCTION_CALL", - "description": "CHOICE NODE: Extended expression type used in SET_PROPERTY. Similar to EXPRESSION but used for property values.", - "node_type": "CHOICE", - "how_to_choose": { - "COMPONENT": "Form field references", - "STRING_LITERAL": "Text values in quotes", - "NUMERIC_LITERAL": "Numbers", - "BOOLEAN_LITERAL": "true or false", - "DATE_LITERAL": "Date values", - "FUNCTION_CALL": "Function result or calculated value" - }, - "structure": { - "nodeName": "EXTENDED_EXPRESSION", - "choice": {"nodeName": "STRING_LITERAL or other", "value": "varies"} - } - }, - "STRING_LITERAL": { - "choiceName": "String", - "description": "TERMINAL NODE: A literal string value. Value is the string without quotes.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "STRING_LITERAL", - "value": "actual string value" - } - }, - "NUMERIC_LITERAL": { - "choiceName": "Number", - "description": "TERMINAL NODE: A literal number value.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "NUMERIC_LITERAL", - "value": 42 - } - }, - "BOOLEAN_LITERAL": { - "rule": "True | False", - "choiceName": "Boolean", - "description": "CHOICE NODE: Boolean value. Select True or False.", - "node_type": "CHOICE", - "value_structure": { - "nodeName": "BOOLEAN_LITERAL", - "choice": { - "nodeName": "True", - "value": null - } - } - }, - "DATE_LITERAL": { - "choiceName": "Date", - "description": "TERMINAL NODE: A date value in ISO format.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "DATE_LITERAL", - "value": "2024-01-15" - } - }, - "AFCOMPONENT": { - "rule": "VARIABLE", - "choiceName": "Form Object", - "description": "TERMINAL NODE: Any form component (used in actions like HIDE/SHOW). Use VARIABLE transparency - put form object directly here. Type should be 'AFCOMPONENT'.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "AFCOMPONENT", - "value": { - "id": "$form.componentID", - "displayName": "Component Display Name", - "type": "AFCOMPONENT", - "isDuplicate": false, - "displayPath": "FORM/Parent/Component/", - "name": "componentName", - "parent": "$form.parentID", - "metadata": {} - } - } - }, - "VALUE_FIELD": { - "rule": "VARIABLE", - "description": "TERMINAL NODE: A field that can have its value set. Use VARIABLE transparency - put form object directly. Use full type from treeJson.", - "node_type": "TERMINAL", - "value_structure": { - "nodeName": "VALUE_FIELD", - "value": { - "id": "$form.componentID", - "displayName": "Component Display Name", - "type": "AFCOMPONENT|FIELD|TEXT FIELD|STRING", - "isDuplicate": false, - "displayPath": "FORM/Parent/Component/", - "name": "componentName", - "parent": "$form.parentID", - "metadata": {} - } - }, - "type_reference": "Use full type from treeJson: AFCOMPONENT|FIELD|TEXT FIELD|STRING (for text inputs), AFCOMPONENT|FIELD|NUMBER FIELD|NUMBER (for number inputs), etc." - }, - "is clicked": { - "rule": null, - "choiceName": "is clicked", - "description": "TERMINAL NODE: Event trigger operator for button click. Used in TRIGGER_EVENT to specify that the rule triggers when a button is clicked.", - "node_type": "TERMINAL", - "operatorType": [["BOOLEAN", "BUTTON"]], - "applies_to": "BUTTON components", - "value": null - }, - "is initialized": { - "rule": null, - "choiceName": "is initialized", - "description": "TERMINAL NODE: Event trigger operator for component initialization. Used in TRIGGER_EVENT to specify that the rule triggers when a component is initialized/loaded.", - "node_type": "TERMINAL", - "operatorType": [["BOOLEAN", "ANY"]], - "applies_to": "Any component", - "value": null - }, - "is changed": { - "rule": null, - "choiceName": "is changed", - "description": "TERMINAL NODE: Event trigger operator for value change. Used in TRIGGER_EVENT to specify that the rule triggers when a field's value changes.", - "node_type": "TERMINAL", - "operatorType": [["BOOLEAN", "STRING|NUMBER|DATE|BOOLEAN|FILE ATTACHMENT|FILE"]], - "applies_to": "Fields with values (text input, number, date, checkbox, file attachment)", - "value": null - } -} diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/__init__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/__init__.py deleted file mode 100644 index 1de53251..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Validator module for rule JSON validation.""" - -from .models import ValidationResult, RuleNode -from .rule_validator import RuleValidator, validate_rule -from .grammar_loader import load_grammar, get_supported_actions, get_supported_node_names - -__all__ = [ - 'ValidationResult', - 'RuleNode', - 'RuleValidator', - 'validate_rule', - 'load_grammar', - 'get_supported_actions', - 'get_supported_node_names' -] diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/__main__.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/__main__.py deleted file mode 100644 index 3392878a..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/__main__.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python3 -"""CLI entry point for rule validator. - -Usage: - python -m tools.rule_coder.validator <rule.json> [--form <form.json>] - -Examples: - # Validate rule without form context - python -m tools.rule_coder.validator test-eds.VIS-01.rule.json - - # Validate rule with form context (checks component references) - python -m tools.rule_coder.validator test-eds.VIS-01.rule.json --form test-eds.form.json -""" - -import sys -import json -import argparse -from pathlib import Path - -from .rule_validator import validate_rule - - -def main(): - parser = argparse.ArgumentParser( - description='Validate AEM Forms rule JSON against subset grammar', - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=__doc__ - ) - parser.add_argument( - 'rule_file', - type=str, - help='Path to the rule JSON file to validate' - ) - parser.add_argument( - '--form', - type=str, - help='Optional path to form JSON for component reference validation' - ) - - args = parser.parse_args() - - # Check rule file exists - rule_path = Path(args.rule_file) - if not rule_path.exists(): - print(f"ERROR: Rule file not found: {args.rule_file}", file=sys.stderr) - sys.exit(1) - - # Load rule JSON - try: - with open(rule_path, 'r') as f: - rule = json.load(f) - except json.JSONDecodeError as e: - print(f"ERROR: Invalid JSON in rule file: {e}", file=sys.stderr) - sys.exit(1) - - # Load form context if provided - form_context = None - if args.form: - form_path = Path(args.form) - if not form_path.exists(): - print(f"ERROR: Form file not found: {args.form}", file=sys.stderr) - sys.exit(1) - # TODO: Load FormContext when needed - # from ..context import FormContext - # form_context = FormContext.load_from_form_json(form_path) - - # Validate - result = validate_rule(rule, form_context) - - # Output results - print(f"Valid: {result.valid}") - - for error in result.errors: - print(f"ERROR: {error}") - - for warning in result.warnings: - print(f"WARNING: {warning}") - - # Exit with appropriate code - sys.exit(0 if result.valid else 1) - - -if __name__ == '__main__': - main() diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/grammar_loader.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/grammar_loader.py deleted file mode 100644 index eee0e4d9..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/grammar_loader.py +++ /dev/null @@ -1,213 +0,0 @@ -"""Grammar loader for the annotated subset grammar.""" - -import json -from pathlib import Path -from typing import Dict, Any, List, Set, Optional - -# Path to the annotated subset grammar -GRAMMAR_PATH = Path(__file__).parent.parent / 'grammar' / 'annotated_subset_grammar.json' - -# Cached grammar -_grammar_cache: Optional[Dict[str, Any]] = None - - -def load_grammar() -> Dict[str, Any]: - """ - Load the annotated subset grammar from JSON file. - - Returns: - The grammar dictionary. - - Raises: - FileNotFoundError: If the grammar file doesn't exist. - """ - global _grammar_cache - - if _grammar_cache is not None: - return _grammar_cache - - if not GRAMMAR_PATH.exists(): - raise FileNotFoundError(f"Grammar file not found: {GRAMMAR_PATH}") - - with open(GRAMMAR_PATH, 'r') as f: - _grammar_cache = json.load(f) - - return _grammar_cache - - -def get_supported_actions() -> List[str]: - """ - Get list of supported action types from grammar. - - Returns: - List of supported action node names. - """ - grammar = load_grammar() - instructions = grammar.get('_INSTRUCTIONS', {}) - return instructions.get('supported_actions', []) - - -def get_not_supported_actions() -> List[str]: - """ - Get list of actions that are NOT supported. - - Returns: - List of unsupported action node names. - """ - grammar = load_grammar() - instructions = grammar.get('_INSTRUCTIONS', {}) - not_supported = instructions.get('not_supported', {}) - return not_supported.get('actions', []) - - -def get_not_supported_expressions() -> List[str]: - """ - Get list of expression types that are NOT supported. - - Returns: - List of unsupported expression node names. - """ - grammar = load_grammar() - instructions = grammar.get('_INSTRUCTIONS', {}) - not_supported = instructions.get('not_supported', {}) - return not_supported.get('expressions', []) - - -def get_supported_node_names() -> Set[str]: - """ - Get all node names defined in the grammar (excluding instructions/metadata). - - Returns: - Set of valid node names. - """ - grammar = load_grammar() - - # Exclude special keys that start with underscore - node_names = {key for key in grammar.keys() if not key.startswith('_')} - - return node_names - - -def get_node_definition(node_name: str) -> Optional[Dict[str, Any]]: - """ - Get the definition for a specific node. - - Args: - node_name: Name of the node. - - Returns: - Node definition dictionary or None if not found. - """ - grammar = load_grammar() - return grammar.get(node_name) - - -def get_node_type(node_name: str) -> Optional[str]: - """ - Get the type of a node (SEQUENCE, CHOICE, ARRAY, TERMINAL, LITERAL_TOKEN). - - Args: - node_name: Name of the node. - - Returns: - Node type string or None if not found. - """ - definition = get_node_definition(node_name) - if definition: - return definition.get('node_type') - return None - - -def get_choice_options(node_name: str) -> List[str]: - """ - Get the valid choice options for a CHOICE node. - - Args: - node_name: Name of the choice node. - - Returns: - List of valid choice option names. - """ - definition = get_node_definition(node_name) - if definition: - # Check for explicit choice_options - if 'choice_options' in definition: - return definition['choice_options'] - - # Parse from rule string (format: "OPTION1 | OPTION2 | OPTION3") - rule = definition.get('rule', '') - if '|' in rule: - options = [opt.strip() for opt in rule.split('|')] - return options - - # Check how_to_choose keys - how_to_choose = definition.get('how_to_choose', {}) - if how_to_choose: - return list(how_to_choose.keys()) - - return [] - - -def get_sequence_items(node_name: str) -> List[str]: - """ - Get the expected items for a SEQUENCE node. - - Args: - node_name: Name of the sequence node. - - Returns: - List of item descriptions/names. - """ - definition = get_node_definition(node_name) - if definition: - return definition.get('items_order', []) - return [] - - -def is_valid_operator(operator_name: str) -> bool: - """ - Check if an operator name is valid. - - Args: - operator_name: The operator name to check. - - Returns: - True if valid, False otherwise. - """ - grammar = load_grammar() - operator_def = grammar.get('OPERATOR', {}) - - # Get valid operators from rule string - rule = operator_def.get('rule', '') - valid_operators = [opt.strip() for opt in rule.split('|')] - - return operator_name in valid_operators - - -def get_operator_mappings() -> Dict[str, str]: - """ - Get mapping of natural language to operator names. - - Returns: - Dictionary mapping NL phrases to operator node names. - """ - grammar = load_grammar() - operator_def = grammar.get('OPERATOR', {}) - return operator_def.get('common_mappings', {}) - - -def is_unary_operator(operator_name: str) -> bool: - """ - Check if an operator is unary (doesn't need right operand). - - Args: - operator_name: The operator name. - - Returns: - True if unary, False otherwise. - """ - unary_operators = { - 'IS_EMPTY', 'IS_NOT_EMPTY', 'IS_TRUE', 'IS_FALSE', - 'IS_VALID', 'IS_NOT_VALID' - } - return operator_name in unary_operators diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/models.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/models.py deleted file mode 100644 index 0fa85c3a..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/models.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Pydantic models for rule validation.""" - -from typing import List, Optional, Dict, Any -from pydantic import BaseModel, Field - - -class RuleNode(BaseModel): - """A node in the rule tree.""" - nodeName: str = Field(..., description="Name of the grammar node") - items: Optional[List[Any]] = Field(default=None, description="Child items (for sequence/array nodes)") - choice: Optional[Dict[str, Any]] = Field(default=None, description="Choice node (for choice nodes)") - value: Optional[Any] = Field(default=None, description="Terminal value (for terminal nodes)") - rule: Optional[str] = Field(default=None, description="Rule string (for some nodes)") - nested: Optional[bool] = Field(default=None, description="Nested flag (for CONDITION nodes)") - functionName: Optional[Dict[str, Any]] = Field(default=None, description="Function definition (for FUNCTION_CALL)") - params: Optional[List[Any]] = Field(default=None, description="Function parameters (for FUNCTION_CALL)") - parentNodeName: Optional[str] = Field(default=None, description="Parent node name (for FUNCTION_CALL)") - - class Config: - extra = "allow" # Allow additional fields like isValid, enabled, eventName, etc. - - -class ValidationResult(BaseModel): - """Result of rule validation.""" - valid: bool = Field(..., description="Whether the rule is valid") - errors: List[str] = Field(default_factory=list, description="List of validation errors") - warnings: List[str] = Field(default_factory=list, description="List of validation warnings") - - -class ComponentReference(BaseModel): - """A component reference in a rule.""" - id: str = Field(..., description="Component ID") - displayName: Optional[str] = Field(default=None, description="Display name") - type: Optional[str] = Field(default=None, description="Component type") - name: Optional[str] = Field(default=None, description="Component name") - parent: Optional[str] = Field(default=None, description="Parent component ID") - displayPath: Optional[str] = Field(default=None, description="Display path") - isDuplicate: Optional[bool] = Field(default=False, description="Whether this is a duplicate") - metadata: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata") - - class Config: - extra = "allow" - - -class FunctionReference(BaseModel): - """A function reference in a rule.""" - id: str = Field(..., description="Function ID") - displayName: Optional[str] = Field(default=None, description="Display name") - type: Optional[str] = Field(default=None, description="Return type") - args: Optional[List[Dict[str, Any]]] = Field(default=None, description="Function arguments") - impl: Optional[str] = Field(default=None, description="Implementation pattern") - isDuplicate: Optional[bool] = Field(default=False, description="Whether this is a duplicate") - displayPath: Optional[str] = Field(default="", description="Display path") - - class Config: - extra = "allow" diff --git a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/rule_validator.py b/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/rule_validator.py deleted file mode 100644 index 83de9149..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/rule_coder/validator/rule_validator.py +++ /dev/null @@ -1,420 +0,0 @@ -""" -Rule validation service for AI-generated rules. - -Validates rule JSON against: -1. Structure - correct node hierarchy (ROOT → STATEMENT → TRIGGER_SCRIPTS → ...) -2. Grammar - all nodes exist in subset grammar -3. Subset - only allowed nodes used (no WSDL_STATEMENT, etc.) -4. References - component and function references exist in form context -""" - -import logging -from typing import Dict, List, Any, Optional, Set - -from .models import ValidationResult -from .grammar_loader import ( - get_supported_actions, - get_supported_node_names, - get_not_supported_actions, - get_node_type, - get_choice_options, - is_unary_operator -) - -logger = logging.getLogger(__name__) - - -# Nodes that are NOT allowed in the simplified subset -NOT_SUPPORTED_NODES = { - 'WSDL_STATEMENT', - 'ASYNC_FUNCTION_CALL', - 'BINARY_EXPRESSION', - 'STRING_BINARY_EXPRESSION', - 'ARITHMETIC_EXPRESSION', - 'MEMBER_ACCESS_EXPRESSION', - 'WSDL_OUTPUT_EXPRESSION' -} - -# Literal token nodes (these don't need to be in the grammar as separate definitions) -LITERAL_TOKENS = { - 'When', 'Then', 'Else', 'to', 'of', 'in', 'on', 'key', 'value', 'from' -} - -# Nodes that can have value property -VALUE_NODES = { - 'COMPONENT', 'AFCOMPONENT', 'VALUE_FIELD', 'PANEL', 'REPEATABLE_COMPONENT', - 'STRING_LITERAL', 'NUMERIC_LITERAL', 'BOOLEAN_LITERAL', 'DATE_LITERAL', - 'TRIGGER_EVENT', 'UTM_PARAMETER', 'QUERY_PARAMETER', 'BROWSER_DETAILS', - 'URL_DETAILS', 'URL_LITERAL', 'PROPERTY_LIST' -} - - -class RuleValidator: - """Validates generated rule JSON against grammar and context.""" - - def __init__(self, form_context: Optional[Any] = None): - """ - Initialize validator. - - Args: - form_context: Optional FormContext for reference validation. - """ - self.form_context = form_context - self._supported_actions = set(get_supported_actions()) - self._supported_nodes = get_supported_node_names() - - def validate(self, rule: Dict[str, Any]) -> ValidationResult: - """ - Validate a rule JSON. - - Args: - rule: The rule JSON to validate. - - Returns: - ValidationResult with validation status and errors. - """ - errors: List[str] = [] - warnings: List[str] = [] - - # Basic structure validation - if not isinstance(rule, dict): - errors.append("Rule must be a JSON object") - return ValidationResult(valid=False, errors=errors, warnings=warnings) - - # Validate ROOT structure - errors.extend(self._validate_root(rule)) - - # Validate against subset grammar (no unsupported nodes) - errors.extend(self._validate_subset_compliance(rule)) - - # Validate references if form context is available - if self.form_context: - ref_errors, ref_warnings = self._validate_references(rule) - errors.extend(ref_errors) - warnings.extend(ref_warnings) - - return ValidationResult( - valid=len(errors) == 0, - errors=errors, - warnings=warnings - ) - - def _validate_root(self, rule: Dict[str, Any]) -> List[str]: - """Validate ROOT node structure.""" - errors = [] - - # Check nodeName is ROOT - if rule.get('nodeName') != 'ROOT': - errors.append("Rule must have root node with nodeName='ROOT'") - return errors - - # Check ROOT has items - if 'items' not in rule or not isinstance(rule['items'], list): - errors.append("ROOT node must have 'items' array") - return errors - - if len(rule['items']) == 0: - errors.append("ROOT node must have at least one item") - return errors - - # Validate STATEMENT node - statement = rule['items'][0] - errors.extend(self._validate_statement(statement)) - - return errors - - def _validate_statement(self, node: Dict[str, Any]) -> List[str]: - """Validate STATEMENT node.""" - errors = [] - - if not isinstance(node, dict): - errors.append("STATEMENT must be a JSON object") - return errors - - if node.get('nodeName') != 'STATEMENT': - errors.append("First item in ROOT must be STATEMENT node") - return errors - - if 'choice' not in node: - errors.append("STATEMENT node must have 'choice' property") - return errors - - choice = node['choice'] - if not isinstance(choice, dict): - errors.append("STATEMENT.choice must be a JSON object") - return errors - - if choice.get('nodeName') != 'TRIGGER_SCRIPTS': - errors.append("STATEMENT choice must be TRIGGER_SCRIPTS for trigger event rules") - return errors - - # Validate TRIGGER_SCRIPTS structure - if 'items' in choice and isinstance(choice['items'], list) and len(choice['items']) > 0: - trigger_scripts = choice['items'][0] - if isinstance(trigger_scripts, dict) and trigger_scripts.get('nodeName') == 'SINGLE_TRIGGER_SCRIPTS': - errors.extend(self._validate_single_trigger_scripts(trigger_scripts)) - - return errors - - def _validate_single_trigger_scripts(self, node: Dict[str, Any]) -> List[str]: - """Validate SINGLE_TRIGGER_SCRIPTS node.""" - errors = [] - - if 'items' not in node or not isinstance(node['items'], list): - errors.append("SINGLE_TRIGGER_SCRIPTS must have 'items' array") - return errors - - items = node['items'] - - # Should have at least 4 items: COMPONENT, TRIGGER_EVENT, "When" token, TRIGGER_EVENT_SCRIPTS - if len(items) < 4: - errors.append(f"SINGLE_TRIGGER_SCRIPTS must have at least 4 items, found {len(items)}") - return errors - - # Check COMPONENT - if not isinstance(items[0], dict) or items[0].get('nodeName') != 'COMPONENT': - errors.append("First item in SINGLE_TRIGGER_SCRIPTS must be COMPONENT") - elif 'value' not in items[0]: - errors.append("COMPONENT node must have 'value' property") - - # Check TRIGGER_EVENT - if not isinstance(items[1], dict) or items[1].get('nodeName') != 'TRIGGER_EVENT': - errors.append("Second item in SINGLE_TRIGGER_SCRIPTS must be TRIGGER_EVENT") - elif 'value' not in items[1]: - errors.append("TRIGGER_EVENT node must have 'value' property") - - # Check "When" token - if not isinstance(items[2], dict) or items[2].get('nodeName') != 'When': - errors.append("Third item in SINGLE_TRIGGER_SCRIPTS must be 'When' literal token") - - # Check TRIGGER_EVENT_SCRIPTS - if not isinstance(items[3], dict) or items[3].get('nodeName') != 'TRIGGER_EVENT_SCRIPTS': - errors.append("Fourth item in SINGLE_TRIGGER_SCRIPTS must be TRIGGER_EVENT_SCRIPTS") - else: - errors.extend(self._validate_trigger_event_scripts(items[3])) - - return errors - - def _validate_trigger_event_scripts(self, node: Dict[str, Any]) -> List[str]: - """Validate TRIGGER_EVENT_SCRIPTS node.""" - errors = [] - - if 'items' not in node or not isinstance(node['items'], list): - errors.append("TRIGGER_EVENT_SCRIPTS must have 'items' array") - return errors - - items = node['items'] - - # Must have at least 3 items: CONDITION, "Then" token, BLOCK_STATEMENTS - if len(items) < 3: - errors.append(f"TRIGGER_EVENT_SCRIPTS must have at least 3 items, found {len(items)}") - return errors - - # Check CONDITION - if not isinstance(items[0], dict) or items[0].get('nodeName') != 'CONDITION': - errors.append("First item in TRIGGER_EVENT_SCRIPTS must be CONDITION") - else: - # Validate CONDITION has nested property - if items[0].get('nested') is None: - errors.append("CONDITION node must have 'nested' property (should be false)") - - # Check "Then" token - if not isinstance(items[1], dict) or items[1].get('nodeName') != 'Then': - errors.append("Second item in TRIGGER_EVENT_SCRIPTS must be 'Then' literal token") - - # Check BLOCK_STATEMENTS (then actions) - if not isinstance(items[2], dict) or items[2].get('nodeName') != 'BLOCK_STATEMENTS': - errors.append("Third item in TRIGGER_EVENT_SCRIPTS must be BLOCK_STATEMENTS") - else: - errors.extend(self._validate_block_statements(items[2])) - - # If there are more items, check for Else block - if len(items) > 3: - # Check "Else" token - if not isinstance(items[3], dict) or items[3].get('nodeName') != 'Else': - errors.append("Fourth item in TRIGGER_EVENT_SCRIPTS must be 'Else' literal token") - - # Check BLOCK_STATEMENTS (else actions) - if len(items) > 4: - if not isinstance(items[4], dict) or items[4].get('nodeName') != 'BLOCK_STATEMENTS': - errors.append("Fifth item in TRIGGER_EVENT_SCRIPTS must be BLOCK_STATEMENTS") - else: - errors.extend(self._validate_block_statements(items[4])) - - return errors - - def _validate_block_statements(self, node: Dict[str, Any]) -> List[str]: - """Validate BLOCK_STATEMENTS node.""" - errors = [] - - if 'items' not in node or not isinstance(node['items'], list): - errors.append("BLOCK_STATEMENTS must have 'items' array") - return errors - - if len(node['items']) == 0: - errors.append("BLOCK_STATEMENTS must have at least one action") - return errors - - # Validate each BLOCK_STATEMENT - for i, item in enumerate(node['items']): - if not isinstance(item, dict): - errors.append(f"BLOCK_STATEMENTS item {i} must be a JSON object") - continue - - if item.get('nodeName') != 'BLOCK_STATEMENT': - errors.append(f"BLOCK_STATEMENTS item {i} must have nodeName='BLOCK_STATEMENT'") - continue - - if 'choice' not in item: - errors.append(f"BLOCK_STATEMENT {i} must have 'choice' property") - continue - - choice = item['choice'] - if not isinstance(choice, dict): - errors.append(f"BLOCK_STATEMENT {i}.choice must be a JSON object") - continue - - action_name = choice.get('nodeName') - if not action_name: - errors.append(f"BLOCK_STATEMENT {i}.choice must have 'nodeName'") - continue - - # Check if action is in supported actions - if action_name not in self._supported_actions: - errors.append(f"Action '{action_name}' is not supported in simplified grammar") - - return errors - - def _validate_subset_compliance(self, node: Any) -> List[str]: - """ - Recursively validate that no unsupported nodes are used. - - Args: - node: The node to validate. - - Returns: - List of errors for unsupported nodes. - """ - errors = [] - - if isinstance(node, dict): - node_name = node.get('nodeName') - - if node_name: - # Check if node is explicitly not supported - if node_name in NOT_SUPPORTED_NODES: - errors.append(f"Node '{node_name}' is not supported in simplified grammar. Use FUNCTION_CALL instead.") - - # Check if node is a known node (or literal token) - if node_name not in self._supported_nodes and node_name not in LITERAL_TOKENS: - # Reject unknown node names - NEVER allow invented nodeNames - if not self._is_known_pattern(node_name): - errors.append(f"Unknown node name '{node_name}' - not in grammar whitelist. Only use nodeNames from annotated_subset_grammar.json") - - # Recurse into child nodes - for key, val in node.items(): - if key in ['items', 'choice', 'params']: - errors.extend(self._validate_subset_compliance(val)) - - elif isinstance(node, list): - for item in node: - errors.extend(self._validate_subset_compliance(item)) - - return errors - - def _is_known_pattern(self, node_name: str) -> bool: - """Check if a node name matches a known pattern.""" - # Operator names - operators = { - 'EQUALS_TO', 'NOT_EQUALS_TO', 'GREATER_THAN', 'LESS_THAN', - 'CONTAINS', 'DOES_NOT_CONTAIN', 'STARTS_WITH', 'ENDS_WITH', - 'AND', 'OR', 'IS_EMPTY', 'IS_NOT_EMPTY', 'IS_TRUE', 'IS_FALSE', - 'IS_BEFORE', 'IS_AFTER', 'HAS_SELECTED', 'IS_VALID', 'IS_NOT_VALID' - } - - # Navigation options - nav_options = {'NEW_WINDOW', 'NEW_TAB', 'SAME_TAB', 'NEXT_ITEM', 'PREVIOUS_ITEM', 'FIRST_ITEM'} - - # Boolean literal rules - bool_rules = {'True', 'False'} - - return node_name in operators or node_name in nav_options or node_name in bool_rules - - def _validate_references(self, node: Any) -> tuple: - """ - Recursively validate component and function references. - - Args: - node: The node to validate. - - Returns: - Tuple of (errors, warnings). - """ - errors = [] - warnings = [] - - if isinstance(node, dict): - node_name = node.get('nodeName') - - # Check component references - if node_name in ['COMPONENT', 'AFCOMPONENT', 'VALUE_FIELD', 'PANEL', 'REPEATABLE_COMPONENT']: - value = node.get('value') - if isinstance(value, dict): - comp_id = value.get('id') - if comp_id: - # CRITICAL: Check for $parent references - these cannot be validated - # at design time and won't appear in the Rule Editor Form Object dropdown - if '$parent' in comp_id: - errors.append( - f"$parent reference not allowed: {comp_id}. " - f"Child fragments cannot directly reference parent fields. " - f"Use events for cross-fragment communication instead." - ) - elif self.form_context: - component = self.form_context.get_component(comp_id) - if component is None: - errors.append(f"Component not found: {comp_id}") - - # Check function references - elif node_name == 'FUNCTION_CALL': - func_name = node.get('functionName') - if isinstance(func_name, dict): - func_id = func_name.get('id') - if func_id and self.form_context: - function = self.form_context.get_function_info(func_id) - if function is None: - warnings.append(f"Function not found in context: {func_id} (may be custom function)") - - # Recurse into child nodes - for key, val in node.items(): - if key in ['items', 'choice', 'params']: - child_errors, child_warnings = self._validate_references(val) - errors.extend(child_errors) - warnings.extend(child_warnings) - - elif isinstance(node, list): - for item in node: - child_errors, child_warnings = self._validate_references(item) - errors.extend(child_errors) - warnings.extend(child_warnings) - - return errors, warnings - - -# Convenience function -def validate_rule( - rule: Dict[str, Any], - form_context: Optional[Any] = None -) -> ValidationResult: - """ - Validate a rule JSON. - - Args: - rule: The rule JSON to validate. - form_context: Optional FormContext for reference validation. - - Returns: - ValidationResult with validation status and errors. - """ - validator = RuleValidator(form_context) - return validator.validate(rule) diff --git a/skills/aem/forms/forms-orchestrator/scripts/setup.sh b/skills/aem/forms/forms-orchestrator/scripts/setup.sh deleted file mode 100755 index 88079d29..00000000 --- a/skills/aem/forms/forms-orchestrator/scripts/setup.sh +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env bash -# ───────────────────────────────────────────────────────────────────────────── -# AEM Forms Skills — Environment Setup -# Usage: setup.sh [--force] [--skip-deps] [--help] -# -# Sets up a Python virtual environment, installs Python dependencies, -# and installs the Node.js bridge dependencies for the rule-coder tool. -# -# This script lives inside the plugin directory (forms-orchestrator/scripts/) -# and creates .venv at the project root (alongside pyproject.toml) so the -# plugin package directory stays clean and distributable. -# -# Layout: -# SCRIPTS_DIR = forms-orchestrator/scripts/ (where this file lives) -# PLUGIN_ROOT = forms-orchestrator/ (the plugin package) -# PROJECT_ROOT = forms/ (has pyproject.toml, .venv) -# -# Options: -# --force Remove an existing .venv and recreate it from scratch -# --skip-deps Create/activate the venv but skip package installation -# --help Show this help message and exit -# ───────────────────────────────────────────────────────────────────────────── -set -e - -# ── Colour helpers (no-op when stdout is not a terminal) ───────────────────── -if [ -t 1 ]; then - GREEN="\033[0;32m" - YELLOW="\033[0;33m" - RED="\033[0;31m" - CYAN="\033[0;36m" - BOLD="\033[1m" - RESET="\033[0m" -else - GREEN="" YELLOW="" RED="" CYAN="" BOLD="" RESET="" -fi - -ok() { echo -e "${GREEN}✓${RESET} $*"; } -warn() { echo -e "${YELLOW}⚠${RESET} $*"; } -fail() { echo -e "${RED}❌${RESET} $*"; } -info() { echo -e "${CYAN}ℹ${RESET} $*"; } - -# ── Resolve paths ──────────────────────────────────────────────────────────── -SCRIPTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PLUGIN_ROOT="$(cd "$SCRIPTS_DIR/.." && pwd)" -PROJECT_ROOT="$(cd "$PLUGIN_ROOT/.." && pwd)" -VENV_PATH="$PROJECT_ROOT/.venv" -BRIDGE_DIR="$SCRIPTS_DIR/rule_coder/bridge" - -# ── Parse CLI arguments ────────────────────────────────────────────────────── -FORCE=false -SKIP_DEPS=false - -for arg in "$@"; do - case "$arg" in - --force) - FORCE=true - ;; - --skip-deps) - SKIP_DEPS=true - ;; - --help|-h) - echo "Usage: setup.sh [--force] [--skip-deps] [--help]" - echo "" - echo "Options:" - echo " --force Remove existing .venv and recreate from scratch" - echo " --skip-deps Create/activate venv but skip package installation" - echo " --help Show this help message" - exit 0 - ;; - *) - fail "Unknown option: $arg" - echo "Run setup.sh --help for usage information." - exit 1 - ;; - esac -done - -echo "" -echo -e "${BOLD}AEM Forms Skills — Environment Setup${RESET}" -echo "─────────────────────────────────────" -echo "" - -# ── Handle --force: tear down existing venv ────────────────────────────────── -if [ "$FORCE" = true ] && [ -d "$VENV_PATH" ]; then - warn "Removing existing virtual environment (--force) …" - rm -rf "$VENV_PATH" -fi - -# ── Create virtual environment ─────────────────────────────────────────────── -if [ -d "$VENV_PATH" ]; then - ok "Virtual environment already exists at .venv/" -else - info "Creating virtual environment …" - - if command -v uv &>/dev/null; then - info "Using ${BOLD}uv${RESET} to create venv (Python 3.13)" - uv venv --python 3.13 --seed "$VENV_PATH" - elif command -v python3 &>/dev/null; then - info "uv not found — falling back to ${BOLD}python3 -m venv${RESET}" - python3 -m venv "$VENV_PATH" - else - fail "Neither uv nor python3 found. Please install Python 3.10+ first." - exit 1 - fi - - ok "Virtual environment created at .venv/" -fi - -# ── Activate the virtual environment ───────────────────────────────────────── -# shellcheck disable=SC1091 -source "$VENV_PATH/bin/activate" -ok "Virtual environment activated ($(python3 --version))" - -# ── Install dependencies ───────────────────────────────────────────────────── -if [ "$SKIP_DEPS" = true ]; then - warn "Skipping dependency installation (--skip-deps)" -else - # ── Python deps (editable install from project root where pyproject.toml lives) - info "Installing Python project in editable mode …" - pip install --upgrade pip --quiet - pip install -e "$PROJECT_ROOT[dev]" - ok "Python dependencies installed" - - # ── Node.js bridge deps ─────────────────────────────────────────────────── - if [ -d "$BRIDGE_DIR" ]; then - if command -v npm &>/dev/null; then - info "Installing Node.js bridge dependencies …" - (cd "$BRIDGE_DIR" && npm install) - ok "Node.js bridge dependencies installed" - else - warn "npm not found — skipping Node.js bridge dependency installation." - warn "Install Node.js (https://nodejs.org) and re-run, or run:" - echo " cd forms-orchestrator/scripts/rule_coder/bridge && npm install" - fi - else - warn "Bridge directory not found at $BRIDGE_DIR — skipping npm install." - fi -fi - -# ── Done! ──────────────────────────────────────────────────────────────────── -echo "" -echo -e "${BOLD}${GREEN}Setup complete!${RESET}" -echo "" -echo " Shared CLI tools (forms-orchestrator/scripts/):" -echo -e " ${CYAN}api-manager${RESET} — Manage OpenAPI specifications" -echo -e " ${CYAN}rule-transform${RESET} — Transform form JSON for rule editing" -echo -e " ${CYAN}rule-validate${RESET} — Validate rule JSON against grammar" -echo -e " ${CYAN}rule-save${RESET} — Save compiled rules back to form" -echo -e " ${CYAN}rule-grammar${RESET} — Print the rule grammar reference" -echo -e " ${CYAN}parse-functions${RESET} — Parse custom function JSDoc annotations" -echo "" -echo " Skill-embedded CLI tools:" -echo -e " ${CYAN}form-validate${RESET} — Validate form JSON (build/create-form)" -echo -e " ${CYAN}cct-create${RESET} — Scaffold custom component (build/create-component)" -echo -e " ${CYAN}api-skill${RESET} — Generate API from cURL (integration/manage-apis)" -echo -e " ${CYAN}form-sync${RESET} — Sync forms with AEM (infra/sync-forms)" -echo -e " ${CYAN}eds-code-sync${RESET} — Sync EDS code via GitHub (infra/sync-eds-code)" -echo -e " ${CYAN}git-sandbox${RESET} — Isolated Git workspace (infra/git-sandbox)" -echo -e " ${CYAN}scaffold-form${RESET} — Scaffold empty form JSON (build/scaffold-form)" -echo "" -echo " To activate the environment in a new shell:" -echo -e " ${BOLD}source .venv/bin/activate${RESET}" -echo "" diff --git a/skills/aem/forms/pyproject.toml b/skills/aem/forms/pyproject.toml deleted file mode 100644 index 8c6d2ddd..00000000 --- a/skills/aem/forms/pyproject.toml +++ /dev/null @@ -1,46 +0,0 @@ -[build-system] -requires = ["setuptools>=68.0", "wheel"] -build-backend = "setuptools.build_meta" - -[project] -name = "aem-forms-skills" -version = "0.1.0" -description = "CLI tools for AEM Forms Skills plugin" -requires-python = ">=3.10" -license = "Apache-2.0" -dependencies = [ - "click>=8.0.0", - "python-dotenv>=1.0.0", - "requests>=2.28.0", - "pydantic>=2.0", - "PyYAML>=6.0.0", - "Jinja2>=3.0.0", - "apispec>=6.0.0", - "openapi-spec-validator>=0.7.0", - "PyGithub>=2.1.1", -] - -[project.optional-dependencies] -dev = [ - "pytest>=7.0", - "pytest-cov>=4.0", -] - -[project.scripts] -form-sync = "form_sync.cli:cli" -eds-code-sync = "eds_code_sync.cli:cli" -api-manager = "api_manager.cli:cli" -cct = "cct.cli:cli" -git-sandbox = "git_sandbox.cli:cli" - -[tool.setuptools.packages.find] -where = [ - "forms-orchestrator/scripts", - "forms-orchestrator/references/domain-registry/references/build/references/create-component/scripts", - "forms-orchestrator/references/domain-registry/references/build/references/create-form/scripts", - "forms-orchestrator/references/domain-registry/references/build/references/scaffold-form/scripts", - "forms-orchestrator/references/domain-registry/references/infra/references/sync-forms/scripts", - "forms-orchestrator/references/domain-registry/references/infra/references/sync-eds-code/scripts", - "forms-orchestrator/references/domain-registry/references/infra/references/git-sandbox/scripts", - "forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/scripts", -] diff --git a/skills/aem/forms/setup.sh b/skills/aem/forms/setup.sh deleted file mode 100755 index 6294797a..00000000 --- a/skills/aem/forms/setup.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# ───────────────────────────────────────────────────────────────────────────── -# AEM Forms Skills — Setup (wrapper) -# -# The canonical setup script lives inside the plugin directory at -# forms-orchestrator/scripts/setup.sh. This wrapper forwards to it -# for backwards compatibility. -# ───────────────────────────────────────────────────────────────────────────── -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -exec "$SCRIPT_DIR/forms-orchestrator/scripts/setup.sh" "$@" diff --git a/skills/aem/forms/tests/README.md b/skills/aem/forms/tests/README.md deleted file mode 100644 index a6c80104..00000000 --- a/skills/aem/forms/tests/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# AEM Forms Plugin — Tests - -## Structure - -Tests are organized at two levels: - -### Plugin-level tests (this directory) - -| File | Type | Description | -|------|------|-------------| -| `test_plugin_structure.sh` | Automated | Validates plugin metadata, skill files, and package structure | -| `e2e-test-plan.md` | Manual | End-to-end test plan covering the full form lifecycle | -| `error-handling-guide.md` | Reference | Error reporting and recovery patterns for all tools | - -### Skill-level evals (`forms-orchestrator/.../eval/`) - -Each skill with testable scripts has its own `eval/` directory inside the skill folder. The full path pattern is `forms-orchestrator/references/domain-registry/references/<domain>/references/<skill>/eval/`. - -| Skill | Domain | Eval contents | -|-------|--------|---------------| -| `create-form` | `build` | Form validator smoke test + form fixture | -| `add-rules` | `logic` | Rule transform/validate/save smoke tests + rule fixtures | -| `create-function` | `logic` | Parse-functions smoke test + function fixture | -| `manage-apis` | `integration` | API Manager smoke test | -| `analyze-requirements` | `analysis` | Requirements fixture + manual eval plan | - -## Running Tests - -### Plugin structure validation - -```bash -bash tests/test_plugin_structure.sh -``` - -### Skill evals - -All eval paths are relative to the plugin root (`skills/aem/forms/`). The base path for skill evals is `forms-orchestrator/references/domain-registry/references`. - -```bash -# Build domain -bash forms-orchestrator/references/domain-registry/references/build/references/create-form/eval/eval-form-validate.sh - -# Logic domain -bash forms-orchestrator/references/domain-registry/references/logic/references/add-rules/eval/eval-rule-tools.sh -bash forms-orchestrator/references/domain-registry/references/logic/references/create-function/eval/eval-parse-functions.sh - -# Integration domain -bash forms-orchestrator/references/domain-registry/references/integration/references/manage-apis/eval/eval-api-manager.sh -``` - -### Prerequisites - -- Node.js 18+ (for form validator, rule bridge scripts) -- Python 3.10+ (for rule validator, API manager) -- `npm install` in `forms-orchestrator/scripts/rule_coder/bridge/` (for lodash dependency) -- Run `./forms-orchestrator/scripts/setup.sh` first to create the `.venv` and install Python dependencies - -## Python Environment - -All Python tools run through the central `forms-orchestrator/scripts/python3` wrapper, which: - -1. Lazily bootstraps `.venv` at the project root on first use (via `forms-orchestrator/scripts/setup.sh`) -2. Sets `PYTHONPATH` for all plugin Python packages — no individual script needs to manage paths -3. Execs the venv Python with the correct environment - -This means eval scripts that invoke Python tools (directly or via CLI wrappers) automatically get the right Python environment without any manual setup beyond the initial `setup.sh` run. \ No newline at end of file diff --git a/skills/aem/forms/tests/e2e-test-plan.md b/skills/aem/forms/tests/e2e-test-plan.md deleted file mode 100644 index 374991c3..00000000 --- a/skills/aem/forms/tests/e2e-test-plan.md +++ /dev/null @@ -1,226 +0,0 @@ -# End-to-End Test Plan: AEM Forms Plugin - -> **Task:** P4.5 — Full form lifecycle test -> **Plugin:** aem-forms (skills-only, no MCP server) -> **Duration:** ~30-45 minutes -> **Prerequisites:** Claude Code with aem-forms plugin installed, Node.js 18+, Python 3.10+ - ---- - -## Test Environment Setup - -### 1. Install the Plugin -``` -/plugin install aem-forms@adobe-skills -``` - -### 2. Verify Plugin Installation -- Run `/skills` and verify all 4 skills appear: - - `analyze-requirements` - - `create-form` - - `add-rules` - - `create-function` - -### 3. Create a Test Workspace -Create a fresh project directory with this structure: -``` -test-workspace/ -├── form/ (empty — forms will be created here) -├── code/ -│ └── blocks/ -│ └── form/ -│ └── scripts/ -│ ├── form/ (form-level scripts) -│ └── fragment/ (fragment scripts) -├── refs/ -│ ├── metadata.json (empty JSON object: {}) -│ └── apis/ -│ └── generated/ -│ └── spec/ (empty — no APIs for this test) -└── scripts -> <path-to-plugin>/scripts/ -``` - -The `scripts` symlink should point to the installed plugin's `scripts/` directory so that tool commands work from the workspace root. - ---- - -## Test Scenario: Contact Us Form - -### Requirements -A simple contact form for website visitors with: -- Full Name (required, 2-50 chars) -- Email (required, valid email) -- Phone (optional) -- Inquiry Type (dropdown: General, Support, Sales) -- Message (multiline, required when Inquiry Type is "Support") -- On form submit, show thank-you message - ---- - -## Test Steps - -### Step 1: Analyze Requirements (skill: analyze-requirements) - -**Prompt to Claude:** -> Here are the requirements for a Contact Us form. Please analyze them using the analyze-requirements skill. -> -> [paste the requirements from above] - -**Expected Behavior:** -- Claude reads the requirements -- Produces a structured specification with: - - Form name and title - - Field inventory (5 fields with types, validation) - - Panel structure (2 panels: Contact Info, Inquiry) - - Rule requirements (1 visibility rule for message field) - - API dependencies (none) -- Does NOT ask clarifying questions for fields that are clearly specified -- Marks any unknowns as TBD - -**Validation Checklist:** -- [ ] Output has all 11 sections from the skill's template -- [ ] Field inventory lists all 5 fields with correct types -- [ ] Rule requirements mention show/hide for message based on inquiry type -- [ ] No hallucinated APIs or extra fields - ---- - -### Step 2: Create Form (skill: create-form) - -**Prompt to Claude:** -> Now create the form JSON based on the specification you just produced. - -**Expected Behavior:** -- Claude creates `form/contact-us.form.json` -- File contains: - - Form root with `fieldType: "form"`, proper `sling:resourceType` - - `contactInfoPanel` with fullName, email, phone fields - - `inquiryPanel` with inquiryType dropdown, message textarea - - Proper field types (text-input, email, telephone-input, drop-down) - - Correct validation constraints (required, minLength, maxLength) - - colspan layout values -- Claude runs the validator after creation: - ``` - node scripts/eds_form_validator/validate.cjs form/contact-us.form.json --json - ``` - -**Validation Checklist:** -- [ ] `form/contact-us.form.json` was created -- [ ] JSON is valid and parseable -- [ ] All 5 fields present with correct types -- [ ] Validator command was run -- [ ] Validator reports no errors (or only warnings) -- [ ] No `fd:rules` in form.json (rules are separate) -- [ ] Drop-down has correct enum values - ---- - -### Step 3: Add Rules (skill: add-rules) - -**Prompt to Claude:** -> Add the business rules: when inquiry type is "Support", show the message field prominently. When inquiry type changes away from "Support", hide the message field. - -**Expected Behavior:** -- Claude runs transform-form to get the component tree: - ``` - node scripts/rule_coder/bridge/cli/transform-form.js form/contact-us.form.json - ``` -- Creates a rule JSON for the visibility toggle -- Validates the rule: - ``` - python3 -m rule_coder.validator <rule-file> --form form/contact-us.form.json - ``` -- Saves the rule: - ``` - node scripts/rule_coder/bridge/cli/save-rule.js <rule-file> --rule-store form/contact-us.rule.json --form form/contact-us.form.json - ``` - -**Validation Checklist:** -- [ ] transform-form was called first to get field qualified names -- [ ] Rule JSON uses correct grammar nodes (IF_ELSE_STATEMENT, CONDITION, COMPARISON_EXPRESSION, SHOW_STATEMENT/HIDE_STATEMENT) -- [ ] Validator was run BEFORE save -- [ ] Validator reports valid -- [ ] Rule was saved to `form/contact-us.rule.json` -- [ ] Rule store file contains the new rule entry -- [ ] Rule uses field names from transform-form output (not guessed names) - ---- - -### Step 4: Create Function (skill: create-function) - -**Prompt to Claude:** -> Create a custom function that prefills the message field with "I'm interested in learning more about..." when the inquiry type is "Sales". - -**Expected Behavior:** -- Claude creates a function file at the appropriate script path -- Function has proper JSDoc annotations: - ```javascript - /** - * Prefill Sales Message - * @name prefillSalesMessage Sets default message for Sales inquiries - * @param {scope} globals - */ - ``` -- Claude verifies with parse-functions: - ``` - node scripts/rule_coder/bridge/cli/parse-functions.js <function-file> - ``` -- Claude may also add a rule to invoke the function on inquiryType change - -**Validation Checklist:** -- [ ] Function file was created at correct path -- [ ] Function has complete JSDoc annotations -- [ ] Function uses `globals` parameter (no DOM access) -- [ ] parse-functions was called and returned success -- [ ] Function is exported properly -- [ ] If rule was added, it was validated and saved - ---- - -### Step 5: Full Validation Pass - -**Prompt to Claude:** -> Run a final validation pass on the entire form — validate the form JSON and all rules. - -**Expected Behavior:** -- Claude validates form JSON: - ``` - node scripts/eds_form_validator/validate.cjs form/contact-us.form.json --json - ``` -- Claude validates each rule in the rule store (or the whole file) -- Reports final status - -**Validation Checklist:** -- [ ] Form validator reports valid -- [ ] All rules validate successfully -- [ ] No orphan rules (rules reference fields that exist in form.json) - ---- - -## Success Criteria - -The E2E test **passes** if: - -1. All 4 skills were used in sequence without errors -2. `form/contact-us.form.json` is valid AEM Adaptive Form JSON -3. `form/contact-us.rule.json` contains at least one visibility rule -4. A custom function file exists with proper JSDoc annotations -5. All validator commands return success -6. The agent did not hallucinate field names, APIs, or grammar nodes -7. The agent followed the tool command patterns from the SKILL.md files (not inventing its own commands) - -## Known Limitations - -- **No AEM connection:** form_sync tools (pull/push/list/create) cannot be tested without AEM credentials -- **No API integration:** api_manager `list`/`show` require a populated `refs/apis/generated/spec/` directory -- **Script paths:** The agent needs the `scripts/` directory accessible from the workspace. With plugin install, this is handled automatically. - -## Troubleshooting - -| Issue | Cause | Fix | -|-------|-------|-----| -| `node: command not found` | Node.js not installed | Install Node.js 18+ | -| `python3: command not found` | Python not installed | Install Python 3.10+ | -| `Cannot find module 'lodash'` | node_modules missing | Run `npm install` in `scripts/rule_coder/bridge/` | -| Validator says "Invalid" | Rule grammar error | Check grammar-reference.md for valid nodeNames | -| `No such file or directory` | Wrong working directory | Ensure running from workspace root | \ No newline at end of file diff --git a/skills/aem/forms/tests/error-handling-guide.md b/skills/aem/forms/tests/error-handling-guide.md deleted file mode 100644 index b19388d0..00000000 --- a/skills/aem/forms/tests/error-handling-guide.md +++ /dev/null @@ -1,225 +0,0 @@ -# Error Handling Guide for AEM Forms Skills - -> **Task:** P6.2 — Define how tool errors are communicated across skills -> **Audience:** Skill authors and AI agents using the aem-forms plugin - ---- - -## Overview - -Each skill in the aem-forms plugin references CLI tools in `scripts/`. These tools can fail in various ways. This guide defines: - -1. How each tool reports errors -2. How the AI agent should interpret and recover from errors -3. Standard patterns for error communication in SKILL.md files - ---- - -## Error Reporting by Tool - -### 1. Form Validator (`node scripts/eds_form_validator/validate.cjs`) - -| Signal | Meaning | -|--------|---------| -| Exit code 0 | Validation ran (check JSON output for results) | -| Exit code 1 | File not found or JSON parse error | -| `--json` output `{ "valid": true }` | Form is valid | -| `--json` output `{ "valid": false, "errors": [...] }` | Form has validation errors | - -**Agent behavior:** -- Always use `--json` flag for machine-readable output -- If `valid: false`, read the `errors` array — each entry has `field`, `message`, and `severity` -- Fix all `error`-severity issues before proceeding; `warning`-severity items are advisory -- If exit code 1: check the file path exists and contains valid JSON - -**Common errors:** -| Error message | Cause | Fix | -|---------------|-------|-----| -| `Unknown fieldType: <type>` | Invalid field type in form.json | Check `references/field-types.md` for valid types | -| `Missing required property: name` | Field missing `name` key | Add `name` property matching the JSON key | -| `ENOENT: no such file` | Wrong file path | Verify path from workspace root | - ---- - -### 2. Transform Form (`node scripts/rule_coder/bridge/cli/transform-form.js`) - -| Signal | Meaning | -|--------|---------| -| Exit code 0 + JSON to stdout | Success — treeJson with component info | -| Exit code 1 + error to stderr | Form parse failure | - -**Agent behavior:** -- Capture stdout (JSON) separately from stderr -- If exit code 1: the form.json is likely malformed — validate it first with the form validator -- The output JSON contains the component tree with qualified names — use these names (not guessed names) for rules - -**Common errors:** -| Error message | Cause | Fix | -|---------------|-------|-----| -| `Cannot read properties of undefined` | Missing `sling:resourceType` on a field | Add the correct `sling:resourceType` | -| `Unexpected token` | form.json is not valid JSON | Fix JSON syntax | -| `Cannot find module 'lodash'` | node_modules not installed | Run `npm install` in `scripts/rule_coder/bridge/` | - ---- - -### 3. Rule Validator (`python3 -m rule_coder.validator`) - -| Signal | Meaning | -|--------|---------| -| Exit code 0 | Rule is valid | -| Exit code 1 | Rule is invalid — errors printed to stdout | -| Output line: `Valid: True` | Rule passes all grammar checks | -| Output line: `Valid: False` | Rule has grammar violations | -| Output lines: `ERROR: <msg>` | Specific grammar error | -| Output lines: `WARNING: <msg>` | Non-blocking issue | - -**Agent behavior:** -- **MUST** validate before saving. Never save an invalid rule. -- If `Valid: False`, read the ERROR lines: - - `Unknown nodeName: X` → Check `references/grammar-reference.md` for valid nodeNames - - `Missing required field: X in Y` → The grammar node requires a specific child - - `Invalid operator: X` → Use a valid operator from the grammar -- Fix errors and re-validate until `Valid: True` -- If form path is available, always use `--form <form.json>` to also validate component references - -**Common errors:** -| Error message | Cause | Fix | -|---------------|-------|-----| -| `Unknown nodeName: <name>` | Using a grammar node that doesn't exist | Consult `grammar-reference.md` — only whitelisted nodeNames are valid | -| `Component not found: <name>` | Rule references a field not in the form | Run transform-form.js to get actual field names | -| `Missing required field` | Incomplete rule AST node | Check the grammar for required children of each node type | -| `ModuleNotFoundError` | PYTHONPATH not set correctly | Ensure `scripts/` is in PYTHONPATH | - ---- - -### 4. Save Rule (`node scripts/rule_coder/bridge/cli/save-rule.js`) - -| Signal | Meaning | -|--------|---------| -| Exit code 0 | Rule saved successfully | -| Exit code 1 | Save failed — error to stderr | - -**Agent behavior:** -- **NEVER** call save-rule without validating first -- Use `--rule-store` mode (not legacy form mode) for form-sync compatibility -- If save fails, use `DEBUG=true` prefix to get a stack trace: - ``` - DEBUG=true node scripts/rule_coder/bridge/cli/save-rule.js ... - ``` -- After a successful save, the rule store file is updated atomically - -**Common errors:** -| Error message | Cause | Fix | -|---------------|-------|-----| -| `Component not found in form` | Rule references unknown component | Verify field names with transform-form.js | -| `Rule store file not found` | First rule for this form | The file will be created automatically | -| `ENOENT` | form.json path is wrong | Check the --form path | - ---- - -### 5. Parse Functions (`node scripts/rule_coder/bridge/cli/parse-functions.js`) - -| Signal | Meaning | -|--------|---------| -| Exit code 0 + `{ "success": true }` | Functions parsed successfully | -| Exit code 0 + `{ "success": false }` | Parse completed but found issues | -| Exit code 1 | File not found or critical error | - -**Agent behavior:** -- Check `success` field in JSON output, not just exit code -- If `success: false`, the `customFunction` array may be empty — indicates JSDoc annotation issues -- Each function in `customFunction` has `name`, `params`, `returnType` -- If a function is missing from the output, its JSDoc is malformed - -**Common errors:** -| Error message | Cause | Fix | -|---------------|-------|-----| -| `No functions found` | Missing JSDoc `@name` annotation | Add `@name` tag to JSDoc block | -| `ENOENT` | File path wrong | Verify the script file exists | - ---- - -### 6. API Manager (`python3 scripts/api_manager/cli.py`) - -| Signal | Meaning | -|--------|---------| -| Exit code 0 | Command succeeded | -| Exit code 1 | Error (message to stderr) | -| Exit code 2 | Usage error (wrong arguments) | - -**Agent behavior:** -- Use `--json` flag for `list` and `show` subcommands for machine-readable output -- `list` with no specs returns empty array (not an error) -- `build` requires at least one YAML spec in `refs/apis/generated/spec/` -- `sync` requires AEM credentials (online mode only) - -**Common errors:** -| Error message | Cause | Fix | -|---------------|-------|-----| -| `No API specs found` | Empty spec directory | Use `add` to create specs, or `sync` to fetch from AEM | -| `API not found: <name>` | Wrong API name in `show` | Use `list` first to see available APIs | -| `Connection refused` | AEM not reachable | Check AEM_HOST and AEM_TOKEN | - ---- - -## Standard Error Recovery Pattern - -All skills should follow this pattern when a tool command fails: - -``` -1. READ the error message (stdout + stderr) -2. IDENTIFY the error category: - a. Input error (bad file path, malformed JSON) → Fix input, retry - b. Grammar/schema error (invalid nodeName, wrong field type) → Consult reference docs, fix, retry - c. Missing dependency (node_modules, PYTHONPATH) → Report to user with fix command - d. AEM connection error → Inform user, switch to offline workflow -3. FIX and RETRY (max 2 attempts per error) -4. If still failing after 2 retries, REPORT to user with: - - The exact command that was run - - The full error output - - What was attempted to fix it - - Suggested next steps -``` - ---- - -## Exit Code Convention - -All tools follow Unix conventions: -- **0** = success -- **1** = failure (recoverable — read error message) -- **2** = usage error (wrong arguments — read help) - -**Important:** Exit code 0 from the form validator does NOT mean the form is valid — it means the validator ran successfully. Always check the JSON output for the actual validation result. - ---- - -## Environment & Path Requirements - -| Requirement | Needed for | How to set | -|-------------|-----------|------------| -| `PYTHONPATH` includes `scripts/` | Python tools (rule_coder, api_manager) | `PYTHONPATH="<plugin-root>/scripts"` prefix | -| `node_modules/` in `rule_coder/bridge/` | All Node.js bridge scripts | `npm install` in that directory | -| `AEM_HOST` + `AEM_TOKEN` env vars | form_sync tools | Set in shell or MCP config | -| Working directory = workspace root | All tools (relative paths) | `cd` to workspace before running | - ---- - -## Skill-Specific Error Handling Notes - -### analyze-requirements -No tool commands — this skill is pure reasoning. Errors are about output quality, not tool failures. - -### create-form -**Critical pattern:** Always run the validator after every form edit. The validator is the gate — no proceeding until it passes. - -### add-rules -**Critical pattern:** validate → save (never reverse). If the validator says invalid, do NOT attempt to save. Fix first. - -**Retry budget:** Grammar errors get 2 retry attempts. If the agent can't construct a valid rule after 2 tries, it should: -1. Show the user the rule it's trying to create -2. Show the validation error -3. Ask for guidance - -### create-function -**Critical pattern:** Run parse-functions after writing. If `success: false` or a function is missing from output, the JSDoc is wrong — fix annotations and re-run. \ No newline at end of file diff --git a/skills/aem/forms/tests/test_plugin_structure.sh b/skills/aem/forms/tests/test_plugin_structure.sh deleted file mode 100755 index 00d5052b..00000000 --- a/skills/aem/forms/tests/test_plugin_structure.sh +++ /dev/null @@ -1,249 +0,0 @@ -#!/usr/bin/env bash -# Plugin Structure Integration Test -# Validates that the aem-forms plugin has all required files and references. -# Run from: forms-skills/skills/aem/forms/ -# -# Usage: bash tests/test_plugin_structure.sh - -set -euo pipefail - -PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)" -PASS=0 -FAIL=0 -TOTAL=0 - -pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo " ✅ $1"; } -fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo " ❌ $1"; } -section() { echo ""; echo "── $1 ──"; } - -cd "$PLUGIN_ROOT" - -echo "Plugin Structure Integration Test" -echo "=================================" -echo "Plugin root: $PLUGIN_ROOT" - -# ── Plugin Metadata ── - -section "Plugin Metadata" - -if [[ -f ".claude-plugin/plugin.json" ]]; then - pass "plugin.json exists" -else - fail "plugin.json missing at .claude-plugin/plugin.json" -fi - -if grep -q '"name": "aem-forms"' ".claude-plugin/plugin.json" 2>/dev/null; then - pass "plugin.json contains name \"aem-forms\"" -else - fail "plugin.json does not contain name \"aem-forms\"" -fi - -if grep -q '"skills"' ".claude-plugin/plugin.json" 2>/dev/null; then - pass "plugin.json contains \"skills\" array" -else - fail "plugin.json does not contain \"skills\" array" -fi - -SKILL_COUNT=$(grep -c '\./skills/' ".claude-plugin/plugin.json" 2>/dev/null || echo "0") -if [[ "$SKILL_COUNT" -eq 14 ]]; then - pass "plugin.json skills array has exactly 14 entries" -else - fail "plugin.json skills array has $SKILL_COUNT entries (expected 14)" -fi - -# ── Marketplace Registration ── - -section "Marketplace Registration" - -MARKETPLACE="$PLUGIN_ROOT/../../../.claude-plugin/marketplace.json" -if [[ -f "$MARKETPLACE" ]]; then - pass "marketplace.json exists at repo root" -else - fail "marketplace.json missing at repo root (.claude-plugin/marketplace.json)" -fi - -if grep -q '"aem-forms"' "$MARKETPLACE" 2>/dev/null; then - pass "marketplace.json contains \"aem-forms\" entry" -else - fail "marketplace.json does not contain \"aem-forms\" entry" -fi - -# ── Skill Definitions ── - -section "Skill Definitions" - -SKILLS=("analyze-requirements" "create-form" "add-rules" "create-function" "create-component" "manage-apis" "optimize-rules" "analyze-v1-form" "review-screen-doc" "sync-forms" "sync-eds-code" "git-sandbox" "scaffold-form" "create-screen-doc") - -for skill in "${SKILLS[@]}"; do - skill_file="skills/$skill/SKILL.md" - if [[ -f "$skill_file" ]]; then - pass "$skill_file exists" - else - fail "$skill_file missing" - fi - - if [[ -f "$skill_file" ]]; then - file_size=$(wc -c < "$skill_file" | tr -d ' ') - if [[ "$file_size" -ge 100 ]]; then - pass "$skill_file is non-empty (${file_size} bytes)" - else - fail "$skill_file is too small (${file_size} bytes, expected >= 100)" - fi - fi -done - -# ── Skill References ── - -section "Skill References" - -REFERENCES=( - "skills/create-form/references/field-types.md" - "skills/add-rules/references/grammar-reference.md" - "skills/add-rules/references/rule-types.md" - "skills/add-rules/references/examples/visibility/show-on-dropdown.json" - "skills/create-function/references/api-patterns.md" - "skills/create-function/references/implementation-patterns.md" - "skills/create-function/references/scope-functions-reference.md" - "skills/create-component/references/field-html-structure.md" -) - -for ref in "${REFERENCES[@]}"; do - if [[ -f "$ref" ]]; then - pass "$ref exists" - else - fail "$ref missing" - fi -done - -# ── Script Directories ── - -section "Script Directories" - -# Shared script directories (remain in scripts/) -SHARED_SCRIPT_DIRS=("api_manager" "rule_coder") - -for dir in "${SHARED_SCRIPT_DIRS[@]}"; do - script_dir="scripts/$dir" - if [[ -d "$script_dir" ]]; then - pass "$script_dir/ exists and is a directory" - else - fail "$script_dir/ missing or not a directory" - fi -done - -# Skill-local script directories -SKILL_SCRIPT_DIRS=( - "skills/create-form/scripts/eds_form_validator" - "skills/create-component/scripts/cct" - "skills/manage-apis/scripts/api_skill" - "skills/sync-forms/scripts/form_sync" - "skills/sync-eds-code/scripts/eds_code_sync" - "skills/git-sandbox/scripts/git_sandbox" - "skills/scaffold-form/scripts/scaffold_form" -) - -for script_dir in "${SKILL_SCRIPT_DIRS[@]}"; do - if [[ -d "$script_dir" ]]; then - pass "$script_dir/ exists and is a directory" - else - fail "$script_dir/ missing or not a directory" - fi -done - -# ── Critical Script Files ── - -section "Critical Script Files" - -CRITICAL_SCRIPTS=( - # Shared scripts - "scripts/rule_coder/bridge/cli/transform-form.js" - "scripts/rule_coder/bridge/cli/parse-functions.js" - "scripts/rule_coder/bridge/cli/save-rule.js" - "scripts/rule_coder/bridge/cli/summary.js" - "scripts/rule_coder/bridge/cli/rule-metadata.js" - "scripts/rule_coder/bridge/cli/merge.js" - "scripts/rule_coder/bridge/cli/generate-formula.js" - "scripts/rule_coder/validator/__main__.py" - "scripts/rule_coder/validator/rule_validator.py" - "scripts/rule_coder/grammar/annotated_subset_grammar.json" - "scripts/rule_coder/functions/ootb-functions.json" - "scripts/rule_coder/bridge/package.json" - "scripts/api_manager/cli.py" - "scripts/api_manager/__init__.py" - # Skill-local scripts - "skills/create-form/scripts/eds_form_validator/validate.cjs" - "skills/create-form/scripts/eds_form_validator/FormFieldValidator.cjs" - "skills/create-component/scripts/cct/cli.py" - "skills/create-component/scripts/cct/__init__.py" - "skills/manage-apis/scripts/api_skill/__init__.py" - "skills/manage-apis/scripts/api_skill/cli.py" - "skills/sync-forms/scripts/form_sync/__init__.py" - "skills/sync-forms/scripts/form_sync/cli.py" - "skills/sync-eds-code/scripts/eds_code_sync/cli.py" - "skills/sync-eds-code/scripts/eds_code_sync/__init__.py" - "skills/git-sandbox/scripts/git_sandbox/cli.py" - "skills/git-sandbox/scripts/git_sandbox/__init__.py" - "skills/scaffold-form/scripts/scaffold_form/__init__.py" - "skills/scaffold-form/scripts/scaffold_form/cli.py" -) - -for script in "${CRITICAL_SCRIPTS[@]}"; do - if [[ -f "$script" ]]; then - pass "$script exists" - else - fail "$script missing" - fi -done - -# ── Python Package Structure ── - -section "Python Package Structure" - -PYTHON_INITS=( - # Shared packages - "scripts/rule_coder/__init__.py" - "scripts/rule_coder/validator/__init__.py" - "scripts/rule_coder/context/__init__.py" - "scripts/rule_coder/functions/__init__.py" - "scripts/api_manager/__init__.py" - # Skill-local packages - "skills/create-component/scripts/cct/__init__.py" - "skills/manage-apis/scripts/api_skill/__init__.py" - "skills/sync-forms/scripts/form_sync/__init__.py" - "skills/sync-eds-code/scripts/eds_code_sync/__init__.py" - "skills/git-sandbox/scripts/git_sandbox/__init__.py" - "skills/scaffold-form/scripts/scaffold_form/__init__.py" -) - -for init in "${PYTHON_INITS[@]}"; do - if [[ -f "$init" ]]; then - pass "$init exists" - else - fail "$init missing" - fi -done - -# ── Node.js Dependencies ── - -section "Node.js Dependencies" - -if [[ -d "scripts/rule_coder/bridge/node_modules" ]]; then - pass "scripts/rule_coder/bridge/node_modules/ exists" -else - fail "scripts/rule_coder/bridge/node_modules/ missing (run: cd scripts/rule_coder/bridge && npm install)" -fi - -# ── Summary ── - -echo "" -echo "════════════════════════════════" -echo " $PASS/$TOTAL tests passed, $FAIL failed" -echo "════════════════════════════════" - -if [[ "$FAIL" -gt 0 ]]; then - exit 1 -else - echo "" - echo "All checks passed ✅" - exit 0 -fi