Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

model-apps 2.12.0: forms converge to their layout, verify checks form state, page names and models kept, stricter readers (#657)

Akshay Malooec678a8b96da
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.yml
index 45d4df1ff..7f111f254 100644
--- a/.github/workflows/model-apps-script-tests.yml
+++ b/.github/workflows/model-apps-script-tests.yml
@@ -101,11 +101,21 @@ jobs:
node-version: 20
# The eval harness lives at the repo root (evals/model-apps/**) but is
- # owned by this plugin, so it is gated by the same path filter. These are
- # the offline scoring/fixture tests only — the Layer 1/2 runners need a
- # live Dataverse org and are run manually. `evals/model-apps/tests/` holds
+ # owned by this plugin, so it is gated by the same path filter. First the
+ # unit tests of the scoring/fixture code: `evals/model-apps/tests/` holds
# tests for code shared by the app-builder and genpage runners; a new test
# directory has to be added here or it silently never runs.
- name: run-model-apps-eval-tests
shell: bash
run: node --test evals/model-apps/tests/*.test.js evals/model-apps/app-builder/tests/*.test.js evals/model-apps/genpage/tests/*.test.js
+
+ # Then the runners themselves. They score the COMMITTED fixtures — captured
+ # plans, transcripts and specs — offline, in about a second, with no
+ # Dataverse org. Left to manual runs, four genpage fixtures fell out of step
+ # with a newly required plan section and nothing noticed.
+ - name: run-model-apps-eval-runners
+ shell: bash
+ run: |
+ node evals/model-apps/genpage/run-layer-1.js
+ node evals/model-apps/genpage/run-layer-2.js
+ node evals/model-apps/app-builder/run-app-builder.js
diff --git a/.github/workflows/shared-telemetry-tests.yml b/.github/workflows/shared-telemetry-tests.yml
new file mode 100644
index 000000000..20f8d420c
--- /dev/null
+++ b/.github/workflows/shared-telemetry-tests.yml
@@ -0,0 +1,74 @@
+# Unit tests for the shared telemetry library, plus a check that every adopting plugin's
+# bundled copy (plugins/<plugin>/scripts/lib/telemetry/lib) still matches it. Adopting
+# plugins keep their own path-filtered workflows, which run only when the plugin changes,
+# so this workflow runs on a change to the source or to any copy.
+#
+# The glob is expanded by bash (shell: bash), including on Windows runners, where
+# PowerShell would pass the wildcard through to node unexpanded.
+name: shared-telemetry-tests
+
+on:
+ pull_request:
+ branches:
+ - main
+ paths:
+ - "shared/telemetry/**"
+ - "plugins/*/scripts/lib/telemetry/lib/**"
+ - ".github/workflows/shared-telemetry-tests.yml"
+ push:
+ branches:
+ - main
+ paths:
+ - "shared/telemetry/**"
+ - "plugins/*/scripts/lib/telemetry/lib/**"
+ - ".github/workflows/shared-telemetry-tests.yml"
+
+# The job only reads the checkout; the token needs nothing more.
+permissions:
+ contents: read
+
+# A new push to the same PR supersedes the run in flight.
+concurrency:
+ group: shared-telemetry-tests-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test-shared-telemetry:
+ name: test-shared-telemetry (${{ matrix.os }}, node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ # The suite is small, but a child waiting on stdin would otherwise hold the
+ # job for the six-hour default.
+ timeout-minutes: 15
+ # Every plugin that ships an ikey.json is an adopter. The opt-out name is
+ # POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT, with <PLUGIN> the plugin's
+ # manifest `name` uppercased and non-alphanumerics collapsed to "_"
+ # (telemetryOptOutEnvVarName in shared/telemetry/lib/user-config.js) — not its
+ # directory: plugins/mobile-apps is named "mobile-app". Set each one so a test
+ # that forgets to isolate emission cannot POST to a real collector.
+ # Transmission only — local diagnostic mirrors are unaffected.
+ env:
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: "1"
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1"
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ - windows-latest
+ - macos-latest
+ node:
+ - 20
+ - 22
+ steps:
+ - name: checkout
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+
+ - name: setup-node
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ with:
+ node-version: ${{ matrix.node }}
+
+ - name: run-shared-telemetry-tests
+ shell: bash
+ run: node --test shared/telemetry/tests/*.test.js
diff --git a/AGENTS.md b/AGENTS.md
index 81b6de5e9..642edf13d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -92,8 +92,9 @@ No root-level build, lint, or test commands exist. Build/test tooling lives insi
**Only two workflows run on every PR** — `validate-keyword-case` and `validate-repository-metadata`.
Both are repo-wide and enforce metadata/marketplace rules, not behavior.
-**Every test workflow is path-filtered to a single plugin** (`power-pages` → `plugins/power-pages/**`;
-`model-apps` → `plugins/model-apps/**` + `evals/model-apps/**` + the `shared/` sources it bundles).
+**Every test workflow is path-filtered** — to a single plugin (`power-pages` → `plugins/power-pages/**`;
+`model-apps` → `plugins/model-apps/**` + `evals/model-apps/**` + the `shared/` sources it bundles), or,
+for code no plugin owns, to that code (`shared-telemetry-tests` → `shared/telemetry/**`).
This is deliberate — a PR should not spend CI on a plugin it never touched — but it has a corollary:
*a green PR does not mean the repo is green*, only that the paths you touched are. A plugin that ships
copies of `shared/` sources may list those sources too, so a change to one runs that plugin's drift
@@ -146,7 +147,7 @@ Edit `shared/telemetry/` first, then refresh every adopting plugin's copied `scr
This invariant is CI-enforced: `node scripts/validate-telemetry-ikeys.js` (wired into the `validate-repository-metadata` workflow) scans every `plugins/*/**/ikey.json`, ignores placeholder/empty values, and fails if the same instrumentation key or `event_stream_name` appears under two different plugins. A single plugin reusing one key across regions is allowed; only cross-plugin reuse fails. Run it locally after touching any plugin's `ikey.json`.
-Per-plugin iKey/collector routing is pluggable via a `resolver.js` placed next to the plugin's `ikey.json` (implementing the `resolve`/`isProvisioned` contract); the shared library ships only that contract plus a static-key fallback, not any routing logic. A per-plugin opt-out env var `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (derived as the uppercased plugin name with non-alphanumerics collapsed to `_`, suffixed `_OPTOUT`) disables transmission for automation when set to `1`/`true` (dotnet `*_TELEMETRY_OPTOUT` convention); it has the **highest precedence**, overriding both the persisted `config.json` choice and `/<plugin>:telemetry on`.
+Per-plugin iKey/collector routing is pluggable via a `resolver.js` placed next to the plugin's `ikey.json` (implementing the `resolve`/`isProvisioned` contract); the shared library ships only that contract plus a static-key fallback, not any routing logic. A per-plugin opt-out env var `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (derived as the uppercased plugin name with non-alphanumerics collapsed to `_`, suffixed `_OPTOUT`; the name is the manifest's `name`, not the directory — `plugins/mobile-apps` is `mobile-app`, so its variable ends `_MOBILE_APP_OPTOUT`) disables transmission for automation when set to `1`/`true` (dotnet `*_TELEMETRY_OPTOUT` convention); it has the **highest precedence**, overriding both the persisted `config.json` choice and `/<plugin>:telemetry on`.
### CI must opt out of telemetry transmission
@@ -165,7 +166,7 @@ jobs:
This opt-out suppresses **transmission only** (the local diagnostic mirror is still written), so it is safe and has no effect on what the job actually tests. Tests that need to assert that emission *happens* clear the var in their own spawned-process env and route the event to a local `POWER_PLATFORM_SKILLS_FAKE_HTTPS` probe instead of the real collector — so the job-level opt-out never breaks them. Existing reference: `.github/workflows/power-pages-script-tests.yml`. When you add a new such workflow (or a new emitting step to an existing one), add this env var in the same change; treat a CI job that runs the tests without it as a production-telemetry leak.
-Current adopters: `power-pages` and `mobile-apps` (transmitting), and `model-apps` (bundled, with its committed `ikey.json` still `disabled: true`). Others adopt on demand. power-pages and model-apps each keep a `scripts/tests/telemetry-lib-copy.test.js` that fails when the bundled copy differs from `shared/telemetry/lib`. model-apps also lists `shared/telemetry/**` in its test workflow's path filter, so an edit to the source alone still runs that test.
+Current adopters: `power-pages` and `mobile-apps` (transmitting), and `model-apps` (bundled, with its committed `ikey.json` still `disabled: true`). Others adopt on demand. The library's own tests (`shared/telemetry/tests`) run in `.github/workflows/shared-telemetry-tests.yml` on a change to the source or to any bundled copy, and its `bundled-copies.test.js` fails when any adopter's `plugins/<plugin>/scripts/lib/telemetry/lib` differs from `shared/telemetry/lib`. The workflow sets every adopter's opt-out — add a new adopter's variable there too. power-pages and model-apps also keep a `scripts/tests/telemetry-lib-copy.test.js` that runs the same comparison in their own suites (model-apps also checks its shared skill copies, and lists `shared/telemetry/**` in its workflow's path filter so a source edit runs it too).
## Legacy Marketplace Compatibility
diff --git a/evals/model-apps/app-builder/EVAL_GUIDE.md b/evals/model-apps/app-builder/EVAL_GUIDE.md
index 7a45e9e0d..15052e4eb 100644
--- a/evals/model-apps/app-builder/EVAL_GUIDE.md
+++ b/evals/model-apps/app-builder/EVAL_GUIDE.md
@@ -5,23 +5,31 @@
## What we evaluate
-**Structural per-stage facts** — not `.tsx` snapshots, not live Dataverse state. Each fixture is an App Spec (`app-spec.json`); the runner loads it offline, computes deterministic facts for every build stage, and grades them against assertions in `evals.json`.
+**Offline per-stage facts**, not live Dataverse state or execution of the skill's prompts. Each fixture contains an App Spec (`app-spec.json`); some also contain baseline specs, hand-authored deployed FormXML, downloaded PAC page files, or before/after `.tsx` bytes. The runner computes deterministic facts using the current plugin helpers and grades them against independent expectations in `evals.json`.
### Stage → oracle table
| Stage | Oracle | Plugin primitive |
|---|---|---|
-| **author** | `validateAppSpec(plan profile)` passes · spec-lint clean | `app-spec.js`, `spec-lint.js` |
+| **author** | `validateAppSpec(plan profile)` passes · no lint errors · artifact names are table/type-scoped · ASCII page-quote warnings stay visible without changing approved names. Other advisories remain non-fatal. | `app-spec.js`, `spec-lint.js` |
| **plan** | Every planned item targets a known engine phase | `sdk-build.js` `planFor` + `PHASES` |
| **data** | Normalized data-model facts match the `expect.tables/relationships` block | `schema-facts.js` `schemaFacts` |
-| **ui** | Normalized view/chart/form facts match the `expect.views/charts` block · enriched **default views** keep parent lookups (#2) and drop `createdon` (#7) · each **sub-grid** is a full-width 1-column section titled by the child display name (#5) | `sdk-build.js` `viewDef` / `chartDef` / `compileFormIntent` / `defaultViewColumns` / `subgridLabel` · `artifact-intent.js` `subgridSectionIntent` |
+| **ui** | View/chart names match `expect.views/charts` · explicit tab/section names, topology, percentage widths, display flags, field state and spans match authored input · enriched **default views** keep parent lookups (#2) and drop `createdon` (#7) · each **sub-grid** is a full-width 1-column section titled by the child display name (#5) | `sdk-build.js` `viewDef` / `chartDef` / `compileFormIntent` / `defaultViewColumns` / `subgridLabel` · `artifact-intent.js` `subgridSectionIntent` |
| **app** | Every sitemap subarea resolves to a concrete target · no dangling `navigatesTo` keys | `sdk-build.js` `appDef` |
| **security** | Each declared persona maps to exactly one role · the role **injects** `appmodule` read for app-access personas (and only those) · every persona privilege on an **app-owned** table (the app's own publisher prefix) resolves to a provisioned entity (JTBD coverage) · the role grants **exactly** its jobs' declared privileges — no extra entity, access token, or inflated scope beyond the declared union + the documented `appmodule` injection (least privilege) | `sdk-build.js` `personaRoleSpecFor` |
-| **verify** | Reconcile against a synthetic all-present reader returns `ok: true` | `verify-spec.js` `verifySpec` |
+| **verify** | Required verification succeeds, reports no missing artifacts, and actually runs each applicable check kind. Fixture 7 supplies independent deployed XML and served Main form order instead of compiler-rendered XML. | `verify-spec.js` `verifySpec` |
| **process** | Declarative logic binds real columns — every business-rule clause/action and every BPF step resolves to a column the spec creates (or a lookup its relationships create) | `sdk-build.js` `businessRuleDef` + `bpfDef` |
-| **generate-pages** | No `PAGEREF_` nav targets unresolved (Plan 3 — degrades to SKIP if absent) | `pageref-resolver.js` `resolvePageRefs` |
+| **generate-pages** | Declared navigation edges resolve in canonical synthesized call sites; this does not inspect a page's actual source. See compatibility skips below. | `pageref-resolver.js` `resolvePageRefs` |
| **teardown** | The reverse-of-build delete plan is dependency-safe (solution last · web resources after tables · every table, business rule and process flow has a step) | `sdk-teardown.js` `planTeardown` |
-| **round-trip** | The download→rebuild is lossless — a synthetic deployed read hydrates back the same solution / tables / page-keys / sitemap subareas (incl. classic dashboards) | `hydrate-spec.js` `hydrateSpec` |
+| **round-trip** | The compared hydration subset preserves solution identity, table names, page keys/names/models, authored direct-entry behavior and ordered sitemap target references. Fixture 8 also reads PAC page/config files, unescapes names and diagnoses an omitted invalid model. | `hydrate-spec.js` `hydrateSpec` · `download-model-app.js` `parseDownloadedPages` / `assignPageKeys` · `genpage-cli.js` `unescapePacName` |
+| **changed-only** | Real source-byte hashes and an eligible serialized snapshot produce exactly the expected `fast`, `full` or `noop` verdict, changed phases, page identities and full-build reasons. | `content-hash.js`, `apply-snapshot.js`, `classify-changes.js` |
+
+These are **bounded helper-level oracles**, not proof that download followed by rebuild is lossless.
+Most readers are synthetic; views, charts, forms and commands are not structurally reconstructed by
+the hydrator, and entity column fidelity is checked separately by the metadata projection. Fixture 7
+checks a declared before/after layout and its independently authored deployed evidence; it does not
+run SDK reconciliation. Fixture 9 exercises the real decision core and pure snapshot lifecycle, not
+the build CLI's flag handoff, workspace lease, live identity discovery or partial-apply side effects.
The **process** oracle exists because both surfaces share a failure mode nothing downstream detects:
the platform *accepts* a definition whose column bindings are wrong or missing, and the artifact then
@@ -33,6 +41,9 @@ would stay green through both, so the assertions grade the **bindings** the pure
Each fixture lives in `fixtures/<id>-<slug>/` and contains `app-spec.json`.
Naming is numeric-prefix; `fixture-loader.js` matches `^(\d+)(?:-(.+))?$`.
+Optional `evidence.json` selects fixture evidence, `baseline-app-spec.json` supplies the prior spec,
+and `entity-edit-app-spec.json` supplies fixture 9's schema-only edit. FormXML file references are
+confined to the fixture directory, including when the fixtures root is a junction or symlink.
| # | Slug | What it tests |
|---|---|---|
@@ -41,15 +52,20 @@ Naming is numeric-prefix; `fixture-loader.js` matches `^(\d+)(?:-(.+))?$`.
| 3 | `3-assets-dashboard` | Global choice + column binding, on-click command, and a classic **dashboard** pinned to the nav — exercises teardown (dashboard/command/web-resource/global-choice steps) + the dashboard round-trip |
| 4 | `4-hardening` | The 2026-07-15 review fixes: a lookup-heavy child (8 scalars + a 1:N parent lookup) proves the default view keeps the lookup (#2) and drops `createdon` (#7); an N:N proves the alphabetically-sorted schema name `new_tag_new_ticket` (#3); a no-label sub-grid proves the own-section + pluralName title (#5); relational sample data proves `validateAppSpec` accepts a resolvable `$parent` match and declared Choice labels (#1/#4) |
| 5 | `5-process-logic` | The two declarative-logic surfaces: a 3-stage **business process flow** whose steps bind both the table's own columns and a **relationship lookup** (`new_customerid`, which is absent from `columns[]`), plus two **business rules** — one multi-action, one multi-condition including a value-less presence operator. Grades stage order, step bindings, clause/action survival, and one teardown step each |
+| 6 | `6-form-layout` | Fresh explicit forms: 65/35 form-column widths, grid columns, spans, collapsed tab, read-only reviewer and a polymorphic Customer lookup. Authored shape/state facts are independent of compiler output. |
+| 7 | `7-form-reconcile` | Before/desired specs plus independent FormXML: inserted/reordered tabs, reordered sections, hidden tab/section/field, suppressed labels, read-only fields, 50/50 default widths, spans, Quick View binding and stored/served Main form order. |
+| 8 | `8-page-roundtrip` | PAC-stored escaped own name differs from navigation title; actual downloaded files preserve a valid model, keep an absent model absent, and omit an invalid one with loss diagnostics. |
+| 9 | `9-changed-only` | Baseline and edited `.tsx` bytes: only `overview` is a page-content fast change; adding a column is full with a data-model reason; identical spec and bytes are noop. Real hash, snapshot and classifier helpers run offline. |
+| 10 | `10-name-scope` | The same form/view/chart names on two tables do not collide. A straight double quote warns without a rename; apostrophe and typographic-quote controls do not. Same-table duplicates and missing/spurious warnings are negative unit probes, not red corpus fixtures. |
-> **Fixture 2 note:** `appShell.subAreas[].page` references use the page's **key** (e.g. `"overview"`). For `schemaVersion: 2`, `validateAppSpec` validates `sa.page` against `pages[].key`, while `lintAppSpec` validates against `pages[].name`. Setting `p.key === p.name` (lowercase identifiers) satisfies both validators without modifying plugin code.
+> **Fixture 2 note:** `appShell.subAreas[].page` references use the page's **key** (e.g. `"overview"`), not its display name (`"Overview"`). The v2 validator requires keys, and the linter accepts valid key references; `key === name` is neither required nor used by this fixture.
## `evals.json`
- `skill_name` — identifies this suite.
- `eval_instructions` — description used by eval runners.
- `common_stage_assertions` — run for every fixture; registered in `lib/assertions.js`.
-- `evals[].expect` — per-eval expected counts/names (tables, rels, views, charts, pages).
+- `evals[].expect` — independent per-eval counts/names plus form-edit, rejected-model, changed-only and name-scope contracts.
- `evals[].expectations` — additional per-eval assertion texts (can be empty).
- `evals[].tier` — `smoke` (fast subset) or `full`.
@@ -97,6 +113,12 @@ ok 2 - 2-orders-multipage
2. Add an entry to `evals.json` with matching `id`, an `expect` block, and any extra `expectations`.
3. If you need a new assertion, add it to `lib/assertions.js` (text must match exactly).
+Keep positive fixtures green. Demonstrate each new or strengthened check with a passing control and
+a failing mutation in `tests/facts.test.js`. Do not derive an expected value from the compiler output
+being graded. The unit suite also checks fixture/manifest IDs and registered assertion texts, and
+`evals/model-apps/tests/eval-coverage-contract.test.js` fails when an assertion returns SKIP on every
+fixture it runs on (so it verifies nothing) or when this guide's fixture table misses a fixture.
+
## Adding an assertion
Register the check in `lib/assertions.js`:
@@ -111,16 +133,27 @@ ASSERTIONS.set('my-stage: my assertion text', ({ facts, spec, eval: ev }) => {
Then add the text to `evals.json` `common_stage_assertions` (applies to all) or `evals[].expectations` (per-eval).
-## Page oracle graceful degrade
+## Failures, skips and advisories
+
+An unexpected verifier exception is a **FAIL**, never a skip. A successful `ok` flag without the
+required check kinds is also a failure. Topology reads are required for explicit layouts; a throwing
+or missing topology reader cannot certify them.
+
+The optional `servedMainForms` capability is named explicitly: when absent, its own assertion skips;
+when present, its checks must run and failures remain failures. Checks with no applicable artifact
+also emit a named skip. The legacy PAGEREF compatibility path can skip a resolver that an older
+plugin does not supply; the current verifier itself requires that module, so it is not optional on
+current plugin versions.
-`pageref-resolver.js` (Plan 3) is loaded inside a `try/catch`. If it's absent:
-- `pageFacts(spec)` returns `null`.
-- The `'generate-pages: …'` assertion emits `SKIP` for all fixtures.
-- No other assertion is affected.
+Lint warnings are printed as TAP comments without blanket-failing legitimate advisories. Assertions
+check page-quote warning coverage, and fixture 10 rejects wrong name-scope warnings. Invalid downloaded
+models are also printed as omission diagnostics. Failing assertions or stage-fact computation return
+exit 1; malformed fixtures and argument errors return exit 2.
## Live evals
-The live tier (`plugins/model-apps/scripts/smoke-eval.js`) is the thin live smoke; a multi-page live eval case is a follow-up. These offline evals are complementary: they grade structural facts (no live env needed) while the live smoke grades real Dataverse provisioning.
+The live smoke (`plugins/model-apps/scripts/smoke-eval.js`) grades actual Dataverse provisioning.
+These offline evals complement it; they do not certify live deployment, SDK serialization or runtime UI behavior.
## Cross-links
diff --git a/evals/model-apps/app-builder/evals.json b/evals/model-apps/app-builder/evals.json
index 5701a1a53..7992ba732 100644
--- a/evals/model-apps/app-builder/evals.json
+++ b/evals/model-apps/app-builder/evals.json
@@ -4,6 +4,7 @@
"common_stage_assertions": [
"author: validateAppSpec(plan profile) passes with no errors",
"author: spec-lint reports no errors",
+ "author: page quote warnings remain visible without rewriting approved names",
"plan: every planned item targets a known engine phase",
"security: the plan authors exactly one role per declared persona",
"security: each app-access persona role injects app-module read; opted-out personas do not",
@@ -14,9 +15,12 @@
"data: schema-facts provision exactly the expected tables",
"data: schema-facts provision exactly the expected relationships",
"ui: wire-facts build exactly the expected views and charts",
+ "ui: explicit container names display flags and field state match authored intent",
"app: every sitemap subarea resolves to a concrete target (no dangling entity/page/dashboard)",
"app: every navigatesTo target resolves to a known page key",
"verify: reconcile against an all-present reader returns ok with no missing",
+ "verify: every required check kind actually ran",
+ "verify: served Main form order is checked or explicitly unavailable",
"generate-pages: no PAGEREF_ navigation target is left unresolved",
"teardown: the solution container is deleted last",
"teardown: every declared table has a teardown step",
@@ -24,6 +28,7 @@
"round-trip: download hydrate recovers the same solution and tables",
"round-trip: the sitemap round-trips with the same subareas",
"round-trip: generative pages preserve their keys",
+ "round-trip: generative pages preserve their names and models",
"round-trip: authored directEntry survives unchanged",
"teardown: every declared dashboard has a teardown step",
"teardown: every declared command bar has a teardown step",
@@ -191,6 +196,100 @@
"ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)",
"ui: an authored colspan and rowspan survive into the compiled cell"
]
+ },
+ {
+ "id": 7,
+ "tier": "full",
+ "spec": "app-spec.json",
+ "prompt": "Reconcile a delivery form: insert Intake, reorder the Details and Administration tabs and the Notes and Execution sections, hide containers and fields, keep read-only state, split omitted column widths equally, preserve the Project Quick View, and serve Work Item before Work Item Review.",
+ "expect": {
+ "tables": ["cnt_project", "cnt_workitem"],
+ "relationships": ["cnt_project_cnt_workitem"],
+ "views": [],
+ "charts": [],
+ "formReconcile": {
+ "entity": "cnt_workitem",
+ "form": "Work Item",
+ "beforeTabs": ["tab_admin", "tab_details"],
+ "afterTabs": ["tab_intake", "tab_details", "tab_admin"],
+ "insertedTabs": ["tab_intake"],
+ "sectionTab": "tab_details",
+ "beforeSections": ["section_execution", "section_notes"],
+ "afterSections": ["section_notes", "section_execution"],
+ "beforeMainFormOrder": ["Work Item Review", "Work Item"],
+ "afterMainFormOrder": ["Work Item", "Work Item Review"],
+ "quickViews": 1
+ }
+ },
+ "expectations": [
+ "ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)",
+ "ui: an authored colspan and rowspan survive into the compiled cell",
+ "verify: form reconciliation exercises an inserted tab and reordered existing containers",
+ "verify: Quick View bindings survive form reconciliation"
+ ]
+ },
+ {
+ "id": 8,
+ "tier": "full",
+ "spec": "app-spec.json",
+ "prompt": "Download order pages whose own names differ from their sitemap titles. Unescape the PAC-stored Revenue \\\"FY\\\" name, preserve its gpt-4.1 model and table source, leave an absent model absent, and omit an invalid model with an explicit diagnostic.",
+ "expect": {
+ "tables": ["cnt_order"],
+ "relationships": [],
+ "views": [],
+ "charts": [],
+ "pages": ["revenue", "help", "archive"],
+ "unkeptModels": [
+ { "pageId": "00000000-0000-0000-0000-000000000803", "model": "model with spaces" }
+ ]
+ },
+ "expectations": [
+ "round-trip: invalid downloaded models are omitted with explicit diagnostics"
+ ]
+ },
+ {
+ "id": 9,
+ "tier": "full",
+ "spec": "app-spec.json",
+ "prompt": "Compare an identity-bound last-applied Orders baseline with edited page bytes. Only overview changed: classify a fast re-upload of that page alone. Adding cnt_priority instead requires a full data-model build, and comparing identical spec and source bytes must report noop.",
+ "expect": {
+ "tables": ["cnt_order"],
+ "relationships": [],
+ "views": [],
+ "charts": [],
+ "pages": ["overview", "detail"],
+ "changedOnly": [
+ { "name": "page-only", "verdict": "fast", "changedPhases": ["pages"],
+ "fastChanges": [{ "shape": "page", "phase": "pages", "identity": "overview" }], "fullReasons": [] },
+ { "name": "column-edit", "verdict": "full", "changedPhases": ["data-model"],
+ "fastChanges": [], "fullReasons": ["data-model: changed"] },
+ { "name": "identical", "verdict": "noop", "changedPhases": [], "fastChanges": [], "fullReasons": [] }
+ ]
+ },
+ "expectations": [
+ "changed-only: page bytes use a page-only fast path data-model edits use full and identical inputs are noop"
+ ]
+ },
+ {
+ "id": 10,
+ "tier": "full",
+ "spec": "app-spec.json",
+ "prompt": "Give Orders and Tickets the same Information form, Queue view, and Status Summary chart names without cross-table duplicate warnings. Preserve approved page names verbatim: warn for Revenue \"FY\", but not for Clerk's Queue or Revenue \u201cFY\u201d. Same-table duplicates remain invalid for this fixture.",
+ "expect": {
+ "tables": ["cnt_order", "cnt_ticket"],
+ "relationships": [],
+ "views": ["Queue", "Queue"],
+ "charts": ["Status Summary", "Status Summary"],
+ "pages": ["straight-quote", "apostrophe", "typographic"],
+ "nameScope": [
+ { "kind": "form", "name": "Information", "formType": "Main", "entities": ["cnt_order", "cnt_ticket"] },
+ { "kind": "view", "name": "Queue", "entities": ["cnt_order", "cnt_ticket"] },
+ { "kind": "chart", "name": "Status Summary", "entities": ["cnt_order", "cnt_ticket"] }
+ ]
+ },
+ "expectations": [
+ "author: artifact-name warnings use per-table and form-type scope"
+ ]
}
]
}
diff --git a/evals/model-apps/app-builder/fixtures/10-name-scope/app-spec.json b/evals/model-apps/app-builder/fixtures/10-name-scope/app-spec.json
new file mode 100644
index 000000000..151ef3a13
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/10-name-scope/app-spec.json
@@ -0,0 +1,37 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoNameScope", "publisherPrefix": "cnt" },
+ "app": { "name": "Scoped Names", "description": "Reuse artifact display names on different tables without changing approved page names" },
+ "entities": [
+ { "schemaName": "cnt_order", "displayName": "Order", "pluralName": "Orders",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] }] },
+ { "schemaName": "cnt_ticket", "displayName": "Ticket", "pluralName": "Tickets",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] }] }
+ ],
+ "forms": [
+ { "entity": "cnt_order", "name": "Information", "layout": "auto" },
+ { "entity": "cnt_ticket", "name": "Information", "layout": "auto" }
+ ],
+ "views": [
+ { "entity": "cnt_order", "name": "Queue", "columns": ["cnt_name", "cnt_status"], "activeOnly": true },
+ { "entity": "cnt_ticket", "name": "Queue", "columns": ["cnt_name", "cnt_status"], "activeOnly": true }
+ ],
+ "charts": [
+ { "entity": "cnt_order", "name": "Status Summary", "groupBy": "cnt_status", "measure": "count", "chartType": "Pie" },
+ { "entity": "cnt_ticket", "name": "Status Summary", "groupBy": "cnt_status", "measure": "count", "chartType": "Pie" }
+ ],
+ "pages": [
+ { "key": "straight-quote", "name": "Revenue \"FY\"", "source": { "kind": "intent" } },
+ { "key": "apostrophe", "name": "Clerk's Queue", "source": { "kind": "intent" } },
+ { "key": "typographic", "name": "Revenue \u201cFY\u201d", "source": { "kind": "intent" } }
+ ],
+ "appShell": { "areas": [{ "label": "Names", "groups": [{ "label": "Review", "subAreas": [
+ { "entity": "cnt_order", "title": "Orders" },
+ { "entity": "cnt_ticket", "title": "Tickets" },
+ { "page": "straight-quote", "title": "Revenue Navigation" },
+ { "page": "apostrophe", "title": "Clerk Navigation" },
+ { "page": "typographic", "title": "Typographic Navigation" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/7-form-reconcile/app-spec.json b/evals/model-apps/app-builder/fixtures/7-form-reconcile/app-spec.json
new file mode 100644
index 000000000..2018fe0da
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/7-form-reconcile/app-spec.json
@@ -0,0 +1,56 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoFormReconcile", "publisherPrefix": "cnt" },
+ "app": { "name": "Delivery Review", "description": "Reorder existing forms while preserving display state and related cards" },
+ "entities": [
+ { "schemaName": "cnt_project", "displayName": "Project", "pluralName": "Projects",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_code", "displayName": "Code", "type": "Text" }] },
+ { "schemaName": "cnt_workitem", "displayName": "Work Item", "pluralName": "Work Items",
+ "primaryAttribute": { "schemaName": "cnt_title", "displayName": "Title" },
+ "columns": [
+ { "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] },
+ { "schemaName": "cnt_notes", "displayName": "Notes", "type": "Memo" },
+ { "schemaName": "cnt_reviewer", "displayName": "Reviewer", "type": "Text" },
+ { "schemaName": "cnt_approved", "displayName": "Approved", "type": "Boolean" }
+ ],
+ "mainFormOrder": ["Work Item", "Work Item Review"] }
+ ],
+ "relationships": [
+ { "type": "OneToMany", "referenced": "cnt_project", "referencing": "cnt_workitem",
+ "lookup": { "schemaName": "cnt_ProjectId", "displayName": "Project" } }
+ ],
+ "forms": [
+ { "entity": "cnt_workitem", "name": "Work Item Review", "layout": "auto" },
+ { "entity": "cnt_workitem", "name": "Work Item",
+ "tabs": [
+ { "name": "tab_intake", "label": "Intake",
+ "sections": [{ "name": "section_intake", "label": "Intake", "columns": 1, "fields": ["cnt_approved"] }] },
+ { "name": "tab_details", "label": "Details",
+ "columns": [
+ { "sections": [
+ { "name": "section_notes", "label": "Notes", "columns": 1, "visible": false,
+ "fields": [{ "name": "cnt_notes", "hidden": true, "rowspan": 2 }] },
+ { "name": "section_execution", "label": "Execution", "columns": 2, "showLabel": false,
+ "fields": [{ "name": "cnt_title", "colspan": 2 }, "cnt_status", { "name": "cnt_reviewer", "readOnly": true }] }
+ ] },
+ { "sections": [
+ { "name": "section_context", "label": "Context", "columns": 1,
+ "fields": [{ "name": "cnt_projectid", "hidden": true, "readOnly": true }] }
+ ] }
+ ] },
+ { "name": "tab_admin", "label": "Administration", "visible": false, "expanded": false,
+ "sections": [{ "name": "section_admin", "label": "Administration", "showLabel": false, "fields": [] }] }
+ ],
+ "quickViews": [{ "lookup": "cnt_projectid", "targetEntity": "cnt_project", "form": "Project Card", "label": "Project Snapshot" }] },
+ { "entity": "cnt_project", "name": "Project Card", "formType": "QuickView",
+ "tabs": [{ "name": "tab_card", "label": "Project",
+ "sections": [{ "name": "section_card", "label": "Project", "fields": ["cnt_name", "cnt_code"] }] }] }
+ ],
+ "views": [],
+ "charts": [],
+ "appShell": { "areas": [{ "label": "Delivery", "groups": [{ "label": "Work", "subAreas": [
+ { "entity": "cnt_workitem", "title": "Work Items" },
+ { "entity": "cnt_project", "title": "Projects" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/7-form-reconcile/baseline-app-spec.json b/evals/model-apps/app-builder/fixtures/7-form-reconcile/baseline-app-spec.json
new file mode 100644
index 000000000..887b8c53e
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/7-form-reconcile/baseline-app-spec.json
@@ -0,0 +1,51 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoFormReconcile", "publisherPrefix": "cnt" },
+ "app": { "name": "Delivery Review", "description": "Reorder existing forms while preserving display state and related cards" },
+ "entities": [
+ { "schemaName": "cnt_project", "displayName": "Project", "pluralName": "Projects",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_code", "displayName": "Code", "type": "Text" }] },
+ { "schemaName": "cnt_workitem", "displayName": "Work Item", "pluralName": "Work Items",
+ "primaryAttribute": { "schemaName": "cnt_title", "displayName": "Title" },
+ "columns": [
+ { "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] },
+ { "schemaName": "cnt_notes", "displayName": "Notes", "type": "Memo" },
+ { "schemaName": "cnt_reviewer", "displayName": "Reviewer", "type": "Text" },
+ { "schemaName": "cnt_approved", "displayName": "Approved", "type": "Boolean" }
+ ],
+ "mainFormOrder": ["Work Item Review", "Work Item"] }
+ ],
+ "relationships": [
+ { "type": "OneToMany", "referenced": "cnt_project", "referencing": "cnt_workitem",
+ "lookup": { "schemaName": "cnt_ProjectId", "displayName": "Project" } }
+ ],
+ "forms": [
+ { "entity": "cnt_workitem", "name": "Work Item Review", "layout": "auto" },
+ { "entity": "cnt_workitem", "name": "Work Item",
+ "tabs": [
+ { "name": "tab_admin", "label": "Administration",
+ "sections": [{ "name": "section_admin", "label": "Administration", "fields": ["cnt_reviewer"] }] },
+ { "name": "tab_details", "label": "Details",
+ "columns": [
+ { "width": "65%", "sections": [
+ { "name": "section_execution", "label": "Execution", "columns": 2, "fields": ["cnt_title", "cnt_status"] },
+ { "name": "section_notes", "label": "Notes", "fields": ["cnt_notes"] }
+ ] },
+ { "width": "35%", "sections": [
+ { "name": "section_context", "label": "Context", "fields": ["cnt_projectid"] }
+ ] }
+ ] }
+ ],
+ "quickViews": [{ "lookup": "cnt_projectid", "targetEntity": "cnt_project", "form": "Project Card", "label": "Project Snapshot" }] },
+ { "entity": "cnt_project", "name": "Project Card", "formType": "QuickView",
+ "tabs": [{ "name": "tab_card", "label": "Project",
+ "sections": [{ "name": "section_card", "label": "Project", "fields": ["cnt_name", "cnt_code"] }] }] }
+ ],
+ "views": [],
+ "charts": [],
+ "appShell": { "areas": [{ "label": "Delivery", "groups": [{ "label": "Work", "subAreas": [
+ { "entity": "cnt_workitem", "title": "Work Items" },
+ { "entity": "cnt_project", "title": "Projects" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/7-form-reconcile/evidence.json b/evals/model-apps/app-builder/fixtures/7-form-reconcile/evidence.json
new file mode 100644
index 000000000..d73f4f561
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/7-form-reconcile/evidence.json
@@ -0,0 +1,15 @@
+{
+ "formReconcile": {
+ "forms": [
+ { "id": "00000000-0000-0000-0000-000000000701", "entity": "cnt_workitem", "name": "Work Item", "formType": "Main", "xmlFile": "work-item.xml" },
+ { "id": "00000000-0000-0000-0000-000000000702", "entity": "cnt_workitem", "name": "Work Item Review", "formType": "Main", "xmlFile": "work-item-review.xml" },
+ { "id": "00000000-0000-0000-0000-000000000703", "entity": "cnt_project", "name": "Project Card", "formType": "QuickView", "xmlFile": "project-card.xml" }
+ ],
+ "servedMainForms": {
+ "cnt_workitem": [
+ { "id": "00000000-0000-0000-0000-000000000701", "name": "Work Item" },
+ { "id": "00000000-0000-0000-0000-000000000702", "name": "Work Item Review" }
+ ]
+ }
+ }
+}
diff --git a/evals/model-apps/app-builder/fixtures/7-form-reconcile/project-card.xml b/evals/model-apps/app-builder/fixtures/7-form-reconcile/project-card.xml
new file mode 100644
index 000000000..974e52d51
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/7-form-reconcile/project-card.xml
@@ -0,0 +1,16 @@
+<form>
+ <tabs>
+ <tab name="tab_card" visible="true" expanded="true">
+ <labels><label description="Project" languagecode="1033"/></labels>
+ <columns><column width="100%"><sections>
+ <section name="section_card" columns="1" visible="true" showlabel="true">
+ <labels><label description="Project" languagecode="1033"/></labels>
+ <rows>
+ <row><cell><control datafieldname="cnt_name"/></cell></row>
+ <row><cell><control datafieldname="cnt_code"/></cell></row>
+ </rows>
+ </section>
+ </sections></column></columns>
+ </tab>
+ </tabs>
+</form>
diff --git a/evals/model-apps/app-builder/fixtures/7-form-reconcile/work-item-review.xml b/evals/model-apps/app-builder/fixtures/7-form-reconcile/work-item-review.xml
new file mode 100644
index 000000000..3efbadee9
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/7-form-reconcile/work-item-review.xml
@@ -0,0 +1,4 @@
+<form>
+ <tabs/>
+ <DisplayConditions Order="1" FallbackForm="true"><Everyone/></DisplayConditions>
+</form>
diff --git a/evals/model-apps/app-builder/fixtures/7-form-reconcile/work-item.xml b/evals/model-apps/app-builder/fixtures/7-form-reconcile/work-item.xml
new file mode 100644
index 000000000..5e0f7bdad
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/7-form-reconcile/work-item.xml
@@ -0,0 +1,55 @@
+<form>
+ <tabs>
+ <tab name="tab_intake" visible="true" expanded="true">
+ <labels><label description="Intake" languagecode="1033"/></labels>
+ <columns><column width="100%"><sections>
+ <section name="section_intake" columns="1" visible="true" showlabel="true">
+ <labels><label description="Intake" languagecode="1033"/></labels>
+ <rows><row><cell><control datafieldname="cnt_approved"/></cell></row></rows>
+ </section>
+ </sections></column></columns>
+ </tab>
+ <tab name="tab_details" visible="true" expanded="true">
+ <labels><label description="Details" languagecode="1033"/></labels>
+ <columns>
+ <column width="50%"><sections>
+ <section name="section_quickview" columns="1" visible="true" showlabel="true">
+ <labels><label description="Project Snapshot" languagecode="1033"/></labels>
+ <rows><row><cell id="quickview_cell" visible="false">
+ <control id="project_quickview" classid="{5C5600E0-1D6E-4205-A272-BE80DA87FD42}" datafieldname="cnt_projectid" disabled="true">
+ <parameters><QuickForms><QuickFormIds><QuickFormId entityname="cnt_project">00000000-0000-0000-0000-000000000703</QuickFormId></QuickFormIds></QuickForms><ControlMode>Edit</ControlMode></parameters>
+ </control>
+ </cell></row></rows>
+ </section>
+ <section name="section_notes" columns="1" visible="false" showlabel="true">
+ <labels><label description="Notes" languagecode="1033"/></labels>
+ <rows><row><cell visible="false" rowspan="2"><control datafieldname="cnt_notes"/></cell></row></rows>
+ </section>
+ <section name="section_execution" columns="11" visible="true" showlabel="false">
+ <labels><label description="Execution" languagecode="1033"/></labels>
+ <rows>
+ <row><cell colspan="2"><control datafieldname="cnt_title"/></cell></row>
+ <row><cell><control datafieldname="cnt_status"/></cell><cell><control datafieldname="cnt_reviewer" disabled="true"/></cell></row>
+ </rows>
+ </section>
+ </sections></column>
+ <column width="50%"><sections>
+ <section name="section_context" columns="1" visible="true" showlabel="true">
+ <labels><label description="Context" languagecode="1033"/></labels>
+ <rows><row><cell id="lookup_cell" visible="false"><control id="project_lookup" datafieldname="cnt_projectid" disabled="true"/></cell></row></rows>
+ </section>
+ </sections></column>
+ </columns>
+ </tab>
+ <tab name="tab_admin" visible="false" expanded="false">
+ <labels><label description="Administration" languagecode="1033"/></labels>
+ <columns><column width="100%"><sections>
+ <section name="section_admin" columns="1" visible="true" showlabel="false">
+ <labels><label description="Administration" languagecode="1033"/></labels>
+ <rows/>
+ </section>
+ </sections></column></columns>
+ </tab>
+ </tabs>
+ <DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>
+</form>
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/app-spec.json b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/app-spec.json
new file mode 100644
index 000000000..efaaf4705
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/app-spec.json
@@ -0,0 +1,27 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoPageRoundtrip", "publisherPrefix": "cnt" },
+ "app": { "name": "Order Pages", "description": "Keep a page's own name and model separate from its navigation title" },
+ "entities": [
+ { "schemaName": "cnt_order", "displayName": "Order", "pluralName": "Orders",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] }] }
+ ],
+ "forms": [],
+ "views": [],
+ "charts": [],
+ "pages": [
+ { "key": "revenue", "name": "Revenue \"FY\"", "pageId": "00000000-0000-0000-0000-000000000801",
+ "dataSources": ["cnt_order"], "model": "gpt-4.1", "source": { "kind": "intent" } },
+ { "key": "help", "name": "Clerk's Guide", "pageId": "00000000-0000-0000-0000-000000000802",
+ "source": { "kind": "intent" } },
+ { "key": "archive", "name": "Archived Orders", "pageId": "00000000-0000-0000-0000-000000000803",
+ "dataSources": ["cnt_order"], "source": { "kind": "intent" } }
+ ],
+ "appShell": { "areas": [{ "label": "Orders", "groups": [{ "label": "Pages", "subAreas": [
+ { "page": "revenue", "title": "Revenue Navigation" },
+ { "page": "help", "title": "Help Navigation" },
+ { "page": "archive", "title": "Archive Navigation" },
+ { "entity": "cnt_order", "title": "Orders" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/evidence.json b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/evidence.json
new file mode 100644
index 000000000..929690a49
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/evidence.json
@@ -0,0 +1,9 @@
+{
+ "pageRoundTrip": {
+ "envPages": [
+ { "pageId": "00000000-0000-0000-0000-000000000801", "name": "Revenue \\\"FY\\\"" },
+ { "pageId": "00000000-0000-0000-0000-000000000802", "name": "Clerk's Guide" },
+ { "pageId": "00000000-0000-0000-0000-000000000803", "name": "Archived Orders" }
+ ]
+ }
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000801/config.json b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000801/config.json
new file mode 100644
index 000000000..6eac20dfc
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000801/config.json
@@ -0,0 +1,4 @@
+{
+ "dataSources": ["cnt_order"],
+ "model": "gpt-4.1"
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000801/page.tsx b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000801/page.tsx
new file mode 100644
index 000000000..64971ac1c
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000801/page.tsx
@@ -0,0 +1,3 @@
+export default function Revenue() {
+ return null;
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000802/config.json b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000802/config.json
new file mode 100644
index 000000000..d501e5623
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000802/config.json
@@ -0,0 +1,3 @@
+{
+ "dataSources": []
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000802/page.tsx b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000802/page.tsx
new file mode 100644
index 000000000..1dbd607e0
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000802/page.tsx
@@ -0,0 +1,3 @@
+export default function Help() {
+ return null;
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000803/config.json b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000803/config.json
new file mode 100644
index 000000000..ee7cd2a1d
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000803/config.json
@@ -0,0 +1,4 @@
+{
+ "dataSources": ["cnt_order"],
+ "model": "model with spaces"
+}
diff --git a/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000803/page.tsx b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000803/page.tsx
new file mode 100644
index 000000000..e57e4348a
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/8-page-roundtrip/pages/00000000-0000-0000-0000-000000000803/page.tsx
@@ -0,0 +1,3 @@
+export default function Archive() {
+ return null;
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/app-spec.json b/evals/model-apps/app-builder/fixtures/9-changed-only/app-spec.json
new file mode 100644
index 000000000..f76636c5f
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/app-spec.json
@@ -0,0 +1,24 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoChangedOnly", "publisherPrefix": "cnt" },
+ "app": { "name": "Orders", "uniqueName": "cnt_orders", "description": "Classify safe partial applies from an identity-bound baseline" },
+ "entities": [
+ { "schemaName": "cnt_order", "displayName": "Order", "pluralName": "Orders",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] }] }
+ ],
+ "forms": [],
+ "views": [],
+ "charts": [],
+ "pages": [
+ { "key": "overview", "name": "Order Overview", "pageId": "00000000-0000-0000-0000-000000000901",
+ "dataSources": ["cnt_order"], "source": { "kind": "tsx", "codeFile": "overview.tsx" } },
+ { "key": "detail", "name": "Order Detail", "pageId": "00000000-0000-0000-0000-000000000902",
+ "dataSources": ["cnt_order"], "source": { "kind": "tsx", "codeFile": "detail.tsx" } }
+ ],
+ "appShell": { "areas": [{ "label": "Orders", "groups": [{ "label": "Pages", "subAreas": [
+ { "page": "overview", "title": "Overview" },
+ { "page": "detail", "title": "Detail" },
+ { "entity": "cnt_order", "title": "Orders" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/baseline-app-spec.json b/evals/model-apps/app-builder/fixtures/9-changed-only/baseline-app-spec.json
new file mode 100644
index 000000000..f76636c5f
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/baseline-app-spec.json
@@ -0,0 +1,24 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoChangedOnly", "publisherPrefix": "cnt" },
+ "app": { "name": "Orders", "uniqueName": "cnt_orders", "description": "Classify safe partial applies from an identity-bound baseline" },
+ "entities": [
+ { "schemaName": "cnt_order", "displayName": "Order", "pluralName": "Orders",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [{ "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] }] }
+ ],
+ "forms": [],
+ "views": [],
+ "charts": [],
+ "pages": [
+ { "key": "overview", "name": "Order Overview", "pageId": "00000000-0000-0000-0000-000000000901",
+ "dataSources": ["cnt_order"], "source": { "kind": "tsx", "codeFile": "overview.tsx" } },
+ { "key": "detail", "name": "Order Detail", "pageId": "00000000-0000-0000-0000-000000000902",
+ "dataSources": ["cnt_order"], "source": { "kind": "tsx", "codeFile": "detail.tsx" } }
+ ],
+ "appShell": { "areas": [{ "label": "Orders", "groups": [{ "label": "Pages", "subAreas": [
+ { "page": "overview", "title": "Overview" },
+ { "page": "detail", "title": "Detail" },
+ { "entity": "cnt_order", "title": "Orders" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/baseline/detail.tsx b/evals/model-apps/app-builder/fixtures/9-changed-only/baseline/detail.tsx
new file mode 100644
index 000000000..5437372e3
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/baseline/detail.tsx
@@ -0,0 +1,3 @@
+export default function Detail() {
+ return <main>Order detail</main>;
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/baseline/overview.tsx b/evals/model-apps/app-builder/fixtures/9-changed-only/baseline/overview.tsx
new file mode 100644
index 000000000..e15c1cfff
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/baseline/overview.tsx
@@ -0,0 +1,3 @@
+export default function Overview() {
+ return <main>Original order overview</main>;
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/detail.tsx b/evals/model-apps/app-builder/fixtures/9-changed-only/detail.tsx
new file mode 100644
index 000000000..5437372e3
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/detail.tsx
@@ -0,0 +1,3 @@
+export default function Detail() {
+ return <main>Order detail</main>;
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/entity-edit-app-spec.json b/evals/model-apps/app-builder/fixtures/9-changed-only/entity-edit-app-spec.json
new file mode 100644
index 000000000..5627f76bb
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/entity-edit-app-spec.json
@@ -0,0 +1,27 @@
+{
+ "schemaVersion": 2,
+ "solution": { "uniqueName": "ContosoChangedOnly", "publisherPrefix": "cnt" },
+ "app": { "name": "Orders", "uniqueName": "cnt_orders", "description": "Classify safe partial applies from an identity-bound baseline" },
+ "entities": [
+ { "schemaName": "cnt_order", "displayName": "Order", "pluralName": "Orders",
+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },
+ "columns": [
+ { "schemaName": "cnt_status", "displayName": "Status", "type": "Choice", "options": ["Open", "Done"] },
+ { "schemaName": "cnt_priority", "displayName": "Priority", "type": "Integer" }
+ ] }
+ ],
+ "forms": [],
+ "views": [],
+ "charts": [],
+ "pages": [
+ { "key": "overview", "name": "Order Overview", "pageId": "00000000-0000-0000-0000-000000000901",
+ "dataSources": ["cnt_order"], "source": { "kind": "tsx", "codeFile": "overview.tsx" } },
+ { "key": "detail", "name": "Order Detail", "pageId": "00000000-0000-0000-0000-000000000902",
+ "dataSources": ["cnt_order"], "source": { "kind": "tsx", "codeFile": "detail.tsx" } }
+ ],
+ "appShell": { "areas": [{ "label": "Orders", "groups": [{ "label": "Pages", "subAreas": [
+ { "page": "overview", "title": "Overview" },
+ { "page": "detail", "title": "Detail" },
+ { "entity": "cnt_order", "title": "Orders" }
+ ] }] }] }
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/evidence.json b/evals/model-apps/app-builder/fixtures/9-changed-only/evidence.json
new file mode 100644
index 000000000..e4e5a7092
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/evidence.json
@@ -0,0 +1,12 @@
+{
+ "changedOnly": {
+ "identity": {
+ "orgId": "00000000-0000-0000-0000-000000000900",
+ "envUrl": "https://contoso.crm.dynamics.com",
+ "appUniqueName": "cnt_orders",
+ "appId": "00000000-0000-0000-0000-000000000909",
+ "solutionUniqueName": "ContosoChangedOnly"
+ },
+ "generation": "offline-fixture-baseline"
+ }
+}
diff --git a/evals/model-apps/app-builder/fixtures/9-changed-only/overview.tsx b/evals/model-apps/app-builder/fixtures/9-changed-only/overview.tsx
new file mode 100644
index 000000000..f486fc6cb
--- /dev/null
+++ b/evals/model-apps/app-builder/fixtures/9-changed-only/overview.tsx
@@ -0,0 +1,3 @@
+export default function Overview() {
+ return <main>Updated order overview</main>;
+}
diff --git a/evals/model-apps/app-builder/lib/assertions.js b/evals/model-apps/app-builder/lib/assertions.js
index 0ae3b46f0..8972907ee 100644
--- a/evals/model-apps/app-builder/lib/assertions.js
+++ b/evals/model-apps/app-builder/lib/assertions.js
@@ -31,6 +31,39 @@ ASSERTIONS.set('author: spec-lint reports no errors', ({ facts }) =>
? PASS
: fail(`lint errors: ${facts.author.lint.errors.join('; ')}`));
+ASSERTIONS.set('author: artifact-name warnings use per-table and form-type scope', ({ facts, eval: ev }) => {
+ const f = facts.author;
+ if (!Array.isArray(f.artifactNameCollisions) || !Array.isArray(f.artifactNames)) return fail('no independent artifact-name scope facts');
+ if (f.artifactNameCollisions.length) {
+ return fail(`same-table duplicate ${f.artifactNameCollisions.map((c) => `${c.kind} on ${c.entity}: ${c.name}`).join('; ')}`);
+ }
+ const duplicateWarnings = f.lint.warnings.filter((w) => /^Duplicate (?:form|view|chart) name\b/.test(w));
+ if (duplicateWarnings.length) return fail(`lint falsely flags per-table scoped names: ${duplicateWarnings.join('; ')}`);
+ const expected = ev.expect && ev.expect.nameScope;
+ if (!Array.isArray(expected) || !expected.length) return fail('no independent repeated-name scope expectations');
+ for (const group of expected) {
+ const actual = f.artifactNames.filter((a) => a.kind === group.kind && a.name === group.name
+ && (group.kind !== 'form' || a.formType === group.formType)).map((a) => a.entity).sort();
+ if (!eq(actual, sortedLc(group.entities))) return fail(`${group.kind} ${group.name}: expected tables [${group.entities}], got [${actual}]`);
+ }
+ return PASS;
+});
+
+ASSERTIONS.set('author: page quote warnings remain visible without rewriting approved names', ({ facts }) => {
+ const approved = facts.author.approvedPageNames;
+ if (!Array.isArray(approved)) return fail('no independent approved page-name snapshot');
+ if (!approved.length) return skip('spec declares no pages');
+ const actual = (facts.author.pageNames || []).map((p) => p.name);
+ if (!eq(actual, approved)) return fail(`approved page names were rewritten: expected ${JSON.stringify(approved)}, got ${JSON.stringify(actual)}`);
+ const quoted = approved.filter((name) => typeof name === 'string' && name.includes('"'));
+ const warnings = facts.author.lint.warnings.filter((w) => /^Page '/.test(w) && w.includes('ASCII double quote'));
+ if (warnings.length !== quoted.length) return fail(`page quote warnings: expected ${quoted.length}, got ${warnings.length}`);
+ for (const name of quoted) if (!warnings.some((w) => w.startsWith(`Page '${name}':`))) {
+ return fail(`page ${JSON.stringify(name)} is missing its ASCII double quote warning`);
+ }
+ return PASS;
+});
+
// plan stage -----------------------------------------------------------------
ASSERTIONS.set('plan: every planned item targets a known engine phase', ({ facts }) => {
@@ -222,10 +255,59 @@ ASSERTIONS.set('app: every navigatesTo target resolves to a known page key', ({
// verify stage ---------------------------------------------------------------
ASSERTIONS.set('verify: reconcile against an all-present reader returns ok with no missing', ({ facts }) => {
- if (facts.verify.skipped) return skip(`verifySpec needs a reader method not synthesized here (Plan 3): ${facts.verify.skipped}`);
- return facts.verify.ok
+ if (facts.verify.error) return fail(`verifySpec threw: ${facts.verify.error}`);
+ if (facts.verify.skipped) return fail(`required verifySpec was skipped: ${facts.verify.skipped}`);
+ return facts.verify.ok === true && facts.verify.missing.length === 0
? PASS
- : fail(`verify missing: ${facts.verify.missing.map((m) => `${m.kind} ${m.name}`).join(', ')}`);
+ : fail(`verify missing: ${facts.verify.missing.map((m) => `${m.kind} ${m.name}${m.detail ? ` (${m.detail})` : ''}`).join(', ')}`);
+});
+
+ASSERTIONS.set('verify: every required check kind actually ran', ({ facts }) => {
+ const v = facts.verify;
+ if (!v.requiredChecks) return fail('no required verification check manifest was computed');
+ for (const [kind, expected] of Object.entries(v.requiredChecks)) {
+ const ran = (v.checks || []).filter((c) => c.kind === kind).length;
+ if (ran < expected) return fail(`required ${kind} check(s): expected at least ${expected}, ran ${ran}`);
+ }
+ return PASS;
+});
+
+ASSERTIONS.set('verify: served Main form order is checked or explicitly unavailable', ({ facts }) => {
+ const v = facts.verify;
+ if (v.error || v.skipped) return fail(`verification failed: ${v.error || v.skipped}`);
+ const unavailable = (v.optionalUnavailable || []).find((c) => c.capability === 'servedMainForms');
+ if (unavailable) return skip(unavailable.reason);
+ const expected = (v.requiredChecks && v.requiredChecks['form-order-served']) || 0;
+ if (!expected) return skip('no spec-declared Main form order to serve');
+ const checks = (v.checks || []).filter((c) => c.kind === 'form-order-served');
+ if (checks.length < expected) return fail(`form-order-served: expected ${expected} check(s), ran ${checks.length}`);
+ const bad = checks.filter((c) => !c.present);
+ return bad.length ? fail(bad.map((c) => `${c.kind} ${c.name}: ${c.detail}`).join('; ')) : PASS;
+});
+
+ASSERTIONS.set('changed-only: page bytes use a page-only fast path data-model edits use full and identical inputs are noop', ({ facts, eval: ev }) => {
+ const f = facts.changedOnly;
+ if (!f || f.error) return fail(f && f.error ? f.error : 'no real changed-only classification facts');
+ if (!f.baselineVerified) return fail('changed-only baseline was not verified');
+ if (!f.snapshot || f.snapshot.eligible !== true) return fail(`changed-only snapshot is not eligible: ${f.snapshot && f.snapshot.reason}`);
+ const expected = ev.expect && ev.expect.changedOnly;
+ if (!Array.isArray(expected) || !Array.isArray(f.cases) || f.cases.length !== expected.length) {
+ return fail('changed-only case roster does not match the independent expectations');
+ }
+ for (const wanted of expected) {
+ const actual = f.cases.find((c) => c.name === wanted.name);
+ if (!actual) return fail(`changed-only case ${wanted.name} is missing`);
+ if (actual.verdict !== wanted.verdict) return fail(`${wanted.name} verdict: expected ${wanted.verdict}, got ${actual.verdict}`);
+ if (!eq(actual.changedPhases, wanted.changedPhases)) return fail(`${wanted.name} phases: expected [${wanted.changedPhases}], got [${actual.changedPhases}]`);
+ const fast = (actual.fastChanges || []).map(({ shape, phase, identity }) => ({ shape, phase, identity }));
+ if (!eq(fast, wanted.fastChanges)) return fail(`${wanted.name} fast changes: expected ${JSON.stringify(wanted.fastChanges)}, got ${JSON.stringify(fast)}`);
+ if (!Array.isArray(actual.fullReasons) || actual.fullReasons.length !== wanted.fullReasons.length
+ || wanted.fullReasons.some((prefix, i) => !actual.fullReasons[i].startsWith(prefix))) {
+ return fail(`${wanted.name} full reason: expected ${JSON.stringify(wanted.fullReasons)}, got ${JSON.stringify(actual.fullReasons)}`);
+ }
+ if (!Array.isArray(actual.debt) || actual.debt.length) return fail(`${wanted.name}: unexpected changed-only debt ${JSON.stringify(actual.debt)}`);
+ }
+ return PASS;
});
// generate-pages stage -------------------------------------------------------
@@ -300,6 +382,36 @@ ASSERTIONS.set('round-trip: generative pages preserve their keys', ({ facts, spe
return eq(expKeys, facts.roundTrip.pageKeys) ? PASS : fail(`page keys: expected [${expKeys}] got [${facts.roundTrip.pageKeys}]`);
});
+ASSERTIONS.set('round-trip: generative pages preserve their names and models', ({ facts, spec }) => {
+ const f = facts.roundTrip;
+ if (f.error) return fail(`hydrate threw: ${f.error}`);
+ if (!(spec.pages || []).length) return skip('spec declares no pages');
+ for (const expected of spec.pages) {
+ const key = expected.key || expected.name;
+ const actual = (f.pageMetadata || []).find((p) => p.key === key);
+ if (!actual) return fail(`page ${key}: name/model metadata is missing`);
+ if (actual.name !== expected.name) return fail(`page ${key} name: expected ${JSON.stringify(expected.name)}, got ${JSON.stringify(actual.name)}`);
+ const model = expected.model === undefined ? null : expected.model;
+ if (actual.model !== model) return fail(`page ${key} model: expected ${JSON.stringify(model)}, got ${JSON.stringify(actual.model)}`);
+ }
+ return PASS;
+});
+
+ASSERTIONS.set('round-trip: invalid downloaded models are omitted with explicit diagnostics', ({ facts, eval: ev }) => {
+ const f = facts.roundTrip;
+ if (f.error) return fail(`hydrate threw: ${f.error}`);
+ if (f.source !== 'pac-download-fixture') return fail('no real downloaded page/config fixture was read');
+ if ((f.unreadableConfigs || []).length) return fail(`unreadable page config: ${JSON.stringify(f.unreadableConfigs)}`);
+ const expected = ev.expect && ev.expect.unkeptModels;
+ if (!Array.isArray(expected)) return fail('no independent invalid-model expectation');
+ if (!eq(expected, f.unkeptModels)) return fail(`page model loss diagnostics: expected ${JSON.stringify(expected)}, got ${JSON.stringify(f.unkeptModels)}`);
+ for (const dropped of expected) {
+ const page = (f.pageMetadata || []).find((p) => p.pageId === dropped.pageId);
+ if (!page || page.model !== null) return fail(`page ${dropped.pageId}: invalid model must be omitted, got ${JSON.stringify(page && page.model)}`);
+ }
+ return PASS;
+});
+
ASSERTIONS.set('teardown: every declared dashboard has a teardown step', ({ facts, spec }) => {
const declared = (spec.dashboards || []).length;
if (!declared) return skip('spec declares no dashboards');
@@ -505,10 +617,11 @@ ASSERTIONS.set('ui: an explicit layout compiles to the authored tab, form-column
if (at.label !== ct.label) return fail(`${where}: label became ${JSON.stringify(ct.label)}`);
if (at.expanded !== ct.expanded) return fail(`${where}: expanded ${at.expanded} became ${ct.expanded}`);
if (at.columnCount !== ct.columnCount) return fail(`${where}: ${at.columnCount} form-column(s) authored, ${ct.columnCount} compiled — a multi-column tab was collapsed`);
- // Only the widths the author actually WROTE. An omitted width is split evenly by the compiler,
- // and grading that split here would compare the compiler against a copy of itself.
- for (let wi = 0; wi < at.declaredWidths.length; wi++) {
- const w = at.declaredWidths[wi];
+ // The authored projection includes the default percentage split, independently of the
+ // compiler. Omission must not excuse a missing width or a 100/100 two-column layout.
+ const widths = at.expectedWidths || at.declaredWidths;
+ for (let wi = 0; wi < widths.length; wi++) {
+ const w = widths[wi];
if (w !== null && w !== ct.declaredWidths[wi]) return fail(`${where} form-column ${wi}: authored width ${w}, compiled ${ct.declaredWidths[wi]}`);
}
if (at.sectionsByColumn.length !== ct.sectionsByColumn.length) return fail(`${where}: ${at.sectionsByColumn.length} form-column(s) of sections authored, ${ct.sectionsByColumn.length} compiled`);
@@ -530,6 +643,75 @@ ASSERTIONS.set('ui: an explicit layout compiles to the authored tab, form-column
return PASS;
});
+ASSERTIONS.set('ui: explicit container names display flags and field state match authored intent', ({ facts }) => {
+ const explicit = (facts.ui.forms || []).filter((f) => f.authoredShape);
+ if (!explicit.length) return skip('no form in this fixture declares an explicit layout');
+ for (const f of explicit) {
+ for (const [ti, tab] of f.authoredShape.entries()) {
+ const compiled = (f.compiledShape || [])[ti];
+ if (!compiled) return fail(`form ${f.name}: tab ${tab.name} was not compiled`);
+ for (const key of ['name', 'visible']) if (tab[key] !== compiled[key]) {
+ return fail(`form ${f.name} tab ${tab.name}: ${key} expected ${JSON.stringify(tab[key])}, got ${JSON.stringify(compiled[key])}`);
+ }
+ for (const [ci, sections] of tab.sectionsByColumn.entries()) for (const [si, section] of sections.entries()) {
+ const actual = ((compiled.sectionsByColumn || [])[ci] || [])[si];
+ if (!actual) return fail(`form ${f.name}: section ${section.name} was not compiled`);
+ for (const key of ['name', 'visible', 'showLabel']) if (section[key] !== actual[key]) {
+ return fail(`form ${f.name} section ${section.name}: ${key} expected ${JSON.stringify(section[key])}, got ${JSON.stringify(actual[key])}`);
+ }
+ }
+ }
+ for (const wanted of f.authoredPlacements || []) {
+ const actual = (f.placements || []).find((p) => p.field === wanted.field && p.tab === wanted.tab && p.section === wanted.section);
+ if (!actual) return fail(`form ${f.name}: field ${wanted.field} is missing from ${wanted.tab}/${wanted.section}`);
+ for (const key of ['hidden', 'readOnly']) if (wanted[key] !== actual[key]) {
+ return fail(`form ${f.name} field ${wanted.field}: ${key} expected ${wanted[key]}, got ${actual[key]}`);
+ }
+ }
+ }
+ return PASS;
+});
+
+ASSERTIONS.set('verify: form reconciliation exercises an inserted tab and reordered existing containers', ({ facts, eval: ev }) => {
+ const f = facts.formReconcile;
+ if (!f || f.error) return fail(f && f.error ? f.error : 'no independent form reconciliation baseline');
+ if (!f.baselineValidation.ok) return fail(`baseline validation: ${f.baselineValidation.errors.join('; ')}`);
+ const wanted = ev.expect && ev.expect.formReconcile;
+ if (!wanted) return fail('no expected form reconciliation transition');
+ const edit = f.edits.find((e) => e.entity === wanted.entity && e.name === wanted.form);
+ if (!edit || !edit.before) return fail(`no baseline form ${wanted.form}`);
+ const before = edit.before.map((t) => t.name), after = edit.after.map((t) => t.name);
+ if (!eq(before, wanted.beforeTabs)) return fail(`baseline tab order: expected [${wanted.beforeTabs}], got [${before}]`);
+ if (!eq(after, wanted.afterTabs)) return fail(`reconciled tab order: expected [${wanted.afterTabs}], got [${after}]`);
+ const inserted = after.filter((t) => !before.includes(t));
+ if (!eq(inserted, wanted.insertedTabs)) return fail(`inserted tabs: expected [${wanted.insertedTabs}], got [${inserted}]`);
+ const sections = (shape) => shape.find((t) => t.name === wanted.sectionTab).sectionsByColumn[0].map((s) => s.name);
+ if (!eq(sections(edit.before), wanted.beforeSections)) return fail('baseline section order does not exercise the requested reorder');
+ if (!eq(sections(edit.after), wanted.afterSections)) return fail('reconciled section order does not match the requested reorder');
+ const order = (rows) => (rows.find((r) => r.entity === wanted.entity) || {}).forms;
+ if (!eq(order(f.beforeMainFormOrder), wanted.beforeMainFormOrder)) return fail('baseline Main form order does not match the fixture contract');
+ if (!eq(order(f.afterMainFormOrder), wanted.afterMainFormOrder)) return fail('reconciled Main form order does not match the fixture contract');
+ return PASS;
+});
+
+ASSERTIONS.set('verify: Quick View bindings survive form reconciliation', ({ facts, eval: ev }) => {
+ const f = facts.formReconcile;
+ if (!f || f.error) return fail(f && f.error ? f.error : 'no deployed Quick View evidence');
+ const expected = ev.expect && ev.expect.formReconcile && ev.expect.formReconcile.quickViews;
+ if (!expected || f.quickViews.length !== expected) return fail(`Quick View declarations: expected ${expected}, got ${f.quickViews.length}`);
+ for (const qv of f.quickViews) {
+ if (!qv.formId) return fail(`Quick View ${qv.host}/${qv.form}: target form could not be resolved`);
+ if (!qv.deployed.length) return fail(`Quick View ${qv.host}/${qv.form} is missing`);
+ const hits = qv.deployed.filter((p) => p.lookup === qv.lookup);
+ if (hits.length !== 1) return fail(`Quick View ${qv.host}/${qv.form}: expected one lookup ${qv.lookup}, got ${hits.length}`);
+ if (hits[0].classId !== '5c5600e0-1d6e-4205-a272-be80da87fd42') return fail(`Quick View ${qv.host}/${qv.form}: wrong control class`);
+ if (hits[0].formId !== qv.formId || hits[0].targetEntity !== qv.targetEntity) {
+ return fail(`Quick View ${qv.host}/${qv.form}: expected form ${qv.formId} on ${qv.targetEntity}, got ${hits[0].formId} on ${hits[0].targetEntity}`);
+ }
+ }
+ return PASS;
+});
+
// colspan/rowspan are the reason a two-column section is worth authoring at all — a full-width title
// over a two-up grid. Both are dropped silently by a serializer that does not carry them, so a form
// can look correct in the field list and still render as a plain stack.
diff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.js
index bd7876957..af0d052de 100644
--- a/evals/model-apps/app-builder/lib/facts.js
+++ b/evals/model-apps/app-builder/lib/facts.js
@@ -1,34 +1,39 @@
'use strict';
const path = require('node:path');
+const fs = require('node:fs');
// Reach the plugin's pure primitives (4 levels up from evals/model-apps/app-builder/lib/ → repo root,
// same depth genpage/lib uses to reach references/verified-icons.txt). These are offline-only modules
-// with no I/O, no SDK handle, and no network access, so they are safe to call from the eval harness.
+// with no SDK handle or network access. Download/content helpers read fixture files only.
function pluginLib(name) { return require(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', 'lib', name)); }
// Same, for a top-level script rather than a lib module. download-model-app.js exports its pure
// helpers and performs no I/O at require time, so it is safe to load from the offline harness.
function pluginLib2(name) { return require(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', name)); }
-const { migrateAppSpec, validateAppSpec, lookupColumnsFor, SDK_ROLE_MARKER } = pluginLib('app-spec.js');
+const { migrateAppSpec, validateAppSpec, lookupColumnsFor, normalizePageSource, SDK_ROLE_MARKER, FORM_TYPE_CODE } = pluginLib('app-spec.js');
const { lintAppSpec } = pluginLib('spec-lint.js');
const { planFor, PHASES, appDef, viewDef, chartDef, compileFormIntent, formFieldLogicals, defaultViewColumns, enrichesDefaultViews, subgridLabel, personaRoleSpecFor, businessRuleDef, bpfDef } = pluginLib('sdk-build.js');
-const { subgridSectionIntent } = pluginLib('artifact-intent.js');
+const { subgridSectionIntent, isNonFieldControl } = pluginLib('artifact-intent.js');
+const { decodeXmlEntities } = pluginLib('sitemap-pages.js');
const { schemaFacts } = pluginLib('schema-facts.js');
const { verifySpec } = pluginLib('verify-spec.js');
const { isMainForm, plannedMainFormSequence } = pluginLib('form-order.js');
// Round-trip (edit/download) + teardown oracles: both plugin primitives are PURE — planTeardown does
-// no I/O, and hydrateSpec takes an injected `read`, so we can grade the download→rebuild round-trip
-// and the reverse-of-build teardown plan fully offline (no live env). See EVAL_GUIDE.md.
+// no I/O, and hydrateSpec takes an injected `read`, so we can grade the compared hydration subset
+// and the reverse-of-build teardown plan offline. This does not execute a rebuild. See EVAL_GUIDE.md.
const { planTeardown } = pluginLib('sdk-teardown.js');
const { hydrateSpec } = pluginLib('hydrate-spec.js');
// entityFromMetadata is the PURE metadata->spec projection the downloader uses for a table's
// `columns[]`. Grading it here (rather than only in the plugin's unit tests) puts the download
// side of the round-trip under the same fixture corpus as the build side.
-const { entityFromMetadata } = pluginLib2('download-model-app.js');
+const { entityFromMetadata, parseDownloadedPages, assignPageKeys } = pluginLib2('download-model-app.js');
+const { unescapePacName } = pluginLib('genpage-cli.js');
+const { classifyChanges } = pluginLib('classify-changes.js');
+const { annotateContentHashes, pageSourceFileErrors } = pluginLib('content-hash.js');
+const { makeEnvelope, markEligible, parseEnvelope, serializeEnvelope, isFastPathEligible } = pluginLib('apply-snapshot.js');
-// Plan 3's pure PAGEREF_ resolver may not be landed yet — load it optionally so the page oracle
-// degrades to a SKIP instead of crashing the harness. It IS present on this branch, but the
-// try/catch keeps the harness portable across checkouts where Plan 3 isn't available (design §13.2).
+// Retain the legacy optional resolver path for older plugin checkouts. The current verifier also
+// requires this module, so its absence is already a required-plugin load error on current versions.
let pagerefResolver = null;
try { pagerefResolver = pluginLib('pageref-resolver.js'); } catch { pagerefResolver = null; }
@@ -76,8 +81,25 @@ function flattenPrivileges(personaLike) {
// author: design-profile validation + lint. The harness runs in autopilot/design mode — pages are
// intents, so 'plan' is the right profile (design §7.1 — deploy profile would reject intent pages).
-function authorFacts(spec) {
- return { validate: validateAppSpec(spec, { profile: 'plan' }), lint: lintAppSpec(spec) };
+function authorFacts(spec, approvedPageNames) {
+ const validate = validateAppSpec(spec, { profile: 'plan' });
+ const lint = lintAppSpec(spec);
+ // Artifact identity is authored input, independent of the linter's grouping. Otherwise a linter
+ // that regressed to global name scope would supply both the wrong warning and its own expectation.
+ const artifactNames = ['form', 'view', 'chart'].flatMap((kind) => (spec[`${kind}s`] || []).filter((a) => a && a.name).map((a) => ({
+ kind, entity: lc(a.entity), name: a.name, formType: kind === 'form' ? (a.formType || 'Main') : null,
+ })));
+ const groups = new Map();
+ for (const record of artifactNames) {
+ const key = [record.kind, record.entity, lc(record.formType), lc(record.name)].join('|');
+ const prior = groups.get(key);
+ groups.set(key, { ...record, count: prior ? prior.count + 1 : 1 });
+ }
+ return {
+ validate, lint, artifactNames, approvedPageNames,
+ artifactNameCollisions: [...groups.values()].filter((g) => g.count > 1),
+ pageNames: (spec.pages || []).map((p) => ({ key: p.key || p.name, name: p.name })),
+ };
}
// plan: the deterministic phase-grouped plan (planFor is pure for a fixed spec/opts — design §13.2).
@@ -95,14 +117,17 @@ function wireFacts(spec) {
views: (spec.views || []).map((v) => { const d = viewDef(spec, v); return { entity: d.entityLogicalName, name: d.name, columns: d.columns.map((c) => c.name) }; }),
charts: (spec.charts || []).map((c) => { const d = chartDef(spec, c); return { entity: d.entityLogicalName, name: d.name, measure: d.series[0].aggregate, groupBy: d.categories[0].attribute }; }),
forms: (spec.forms || []).map((f) => {
+ const authoredShape = authoredFormShape(f);
+ const authoredPlacements = authoredFormPlacements(f);
const intent = compileFormIntent(spec, f, {});
return {
entity: intent.entityLogicalName,
name: intent.name,
fields: formFieldLogicals(intent),
explicit: !!intent.__explicitLayout,
- authoredShape: authoredFormShape(f),
+ authoredShape,
compiledShape: compiledFormShape(intent),
+ authoredPlacements,
placements: formPlacements(intent),
};
}),
@@ -178,18 +203,25 @@ function authoredFormShape(f) {
// Normalised HERE rather than through the plugin's own helper, so the oracle states the structure
// independently of the code it grades.
const columnsOf = (t) => (Array.isArray(t.columns) ? t.columns : [{ width: null, sections: t.sections || [] }]);
- return f.tabs.map((t) => ({
+ return f.tabs.map((t, ti) => ({
+ name: t.name || `tab_${ti}`,
label: labelOf(t),
expanded: t.expanded !== false,
+ visible: t.visible !== false,
columnCount: Array.isArray(t.columns) ? t.columns.length : 1,
- // Only widths the author actually WROTE. Omitted widths are split evenly by the compiler, and
- // asserting the eval's own copy of that split would grade the compiler against itself.
+ // Keep authored overrides distinct from the independently stated default-split contract below.
declaredWidths: Array.isArray(t.columns) ? t.columns.map((c) => (c && c.width) || null) : [null],
+ // State the percentage-split contract from authored input, not compileFormIntent's output.
+ // In particular, two omitted widths must still mean 50/50, never 100/100 or "not checked".
+ expectedWidths: columnsOf(t).map((c, ci, cols) => (c && c.width) || `${Math.floor(100 / cols.length) + (ci === 0 ? 100 % cols.length : 0)}%`),
// Grouped BY FORM-COLUMN, not flattened. A flat list cannot see a section that moved from column
// 0 to column 1 with its order and fields intact — which is precisely the topology this fixture
// exists to prove, so flattening let the oracle pass a form it should have failed.
- sectionsByColumn: columnsOf(t).map((c) => ((c && c.sections) || []).map((s) => ({
+ sectionsByColumn: columnsOf(t).map((c, ci) => ((c && c.sections) || []).map((s, si) => ({
+ name: s.name || `section_${ti}${ci > 0 ? `_${ci}` : ''}_${si}`,
label: labelOf(s),
+ visible: s.visible !== false,
+ showLabel: s.showLabel !== false,
columns: s.columns === undefined ? 1 : s.columns,
fields: (s.fields || []).map((x) => lc(typeof x === 'string' ? x : x && x.name)),
}))),
@@ -198,20 +230,48 @@ function authoredFormShape(f) {
function compiledFormShape(intent) {
return (intent.tabs || []).map((t) => ({
+ name: t.name,
label: labelOf(t),
expanded: t.expanded !== false,
+ visible: t.visible !== false,
columnCount: (t.columns || []).length,
declaredWidths: (t.columns || []).map((c) => (c && c.width) || null),
sectionsByColumn: (t.columns || []).map((c) => ((c && c.sections) || [])
.filter((s) => !cellsOfSection(s).some(isSubgridCell))
.map((s) => ({
+ name: s.name,
label: labelOf(s),
+ visible: s.visible !== false,
+ showLabel: s.showLabel !== false,
columns: s.columns === undefined ? 1 : s.columns,
fields: cellsOfSection(s).map((cell) => lc(cell.control && cell.control.fieldName)),
}))),
}));
}
+function authoredFormPlacements(form) {
+ const out = [];
+ const defaults = Object.fromEntries(Object.entries(form.fieldOptions || {}).map(([key, value]) => [lc(key), value]));
+ for (const [ti, tab] of (form.tabs || []).entries()) {
+ const cols = Array.isArray(tab.columns) ? tab.columns : [{ sections: tab.sections || [] }];
+ for (const [ci, col] of cols.entries()) for (const [si, section] of (col.sections || []).entries()) {
+ for (const entry of section.fields || []) {
+ const field = lc(typeof entry === 'string' ? entry : entry.name);
+ const inline = typeof entry === 'string' ? {} : entry;
+ const base = defaults[field] || {};
+ out.push({
+ tab: tab.name || `tab_${ti}`,
+ section: section.name || `section_${ti}${ci > 0 ? `_${ci}` : ''}_${si}`,
+ field,
+ hidden: inline.hidden === true || base.hidden === true,
+ readOnly: inline.readOnly === true || base.readOnly === true,
+ });
+ }
+ }
+ }
+ return out;
+}
+
// Every placed control, flattened. Feeds the two invariants that hold on EVERY layout: a field is
// placed exactly ONCE (the reconcile MOVES a misplaced control between sections — it must never
// duplicate one), and the placed set is exactly the set the form intends to carry.
@@ -221,13 +281,15 @@ function formPlacements(intent) {
for (const c of t.columns || []) {
for (const s of (c && c.sections) || []) {
for (const cell of cellsOfSection(s)) {
- if (isSubgridCell(cell)) continue;
+ if (isSubgridCell(cell) || isNonFieldControl(cell.control)) continue;
out.push({
tab: t.name,
section: s.name,
field: lc(cell.control && cell.control.fieldName),
colspan: cell.colspan === undefined ? 1 : cell.colspan,
rowspan: cell.rowspan === undefined ? 1 : cell.rowspan,
+ hidden: cell.visible === false,
+ readOnly: !!(cell.control && cell.control.isReadOnly === true),
});
}
}
@@ -324,19 +386,15 @@ function downloadFacts(spec) {
// app: sitemap subarea target facts + navigation-graph validity. appDef resolves page/dashboard
// subareas from a result map; synthesize deterministic ids offline (no build) so the shape is stable.
//
-// Page lookup: appDef resolves `result.pages[sa.page]`; lintAppSpec validates `sa.page` against
-// `p.name`. We key result.pages by BOTH `p.key` and `p.name` so appDef can resolve subareas
-// regardless of whether the author used the key or the name as the `page` reference — matching
-// the linting behavior without requiring key === name in the fixture.
+// Page lookup: v2 subareas use stable keys; legacy subareas may use display names. Preserve both
+// aliases in this synthetic result map without forcing the key and display name to be identical.
function appFacts(spec) {
const result = { forms: {}, views: {}, charts: {}, dashboards: {}, pages: {} };
for (const d of spec.dashboards || []) result.dashboards[d.name] = `dash-${d.name}`;
for (const p of spec.pages || []) {
const k = p.key || p.name;
result.pages[k] = `gp-${k}`;
- // Also key by name so appDef can resolve a subarea whose `page` field holds the display name.
- // The linter validates sa.page against p.name (spec-lint.js), and authors naturally use names
- // as subarea references. Without the name key, appDef would throw on those subareas.
+ // Also retain the display-name alias for legacy references.
if (p.name && p.name !== k) result.pages[p.name] = `gp-${k}`;
}
const def = appDef(spec, result);
@@ -371,48 +429,49 @@ function appFacts(spec) {
// `formTopology`, and verify now (correctly) reports an explicit layout as UNVERIFIED — a gap in
// the fixture, not a finding about the spec.
//
-// Cells are packed by WIDTH exactly as the compiler packs them, because the oracle checks that no
-// row carries more columns of content than its section declares. `columns` is emitted as the width
-// RATIO string FormXML actually uses ("11" = two equal columns), not as a count.
-function formXmlForAuthoredLayout(form) {
+// Rendered from the COMPILER's own output (compileFormIntent) rather than re-derived, because every
+// attribute below is one verify compares: tab and section display flags, the form-column widths the
+// compiler fills in (an equal split where the author gave none), its row packing, and each cell's spans
+// and read-only / hidden state. A second derivation here drifted from it — an undeclared width rendered
+// as 100% in every form-column, and no display flag at all. `columns` is emitted as the width RATIO
+// string FormXML actually uses ("11" = two equal columns), not as a count.
+function formXmlForAuthoredLayout(spec, form) {
const esc = (v) => String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
const labels = (text) => `<labels><label description="${esc(text)}" languagecode="1033"/></labels>`;
- const tabsXml = (form.tabs || []).map((t, ti) => {
- const cols = Array.isArray(t.columns) ? t.columns : [{ width: '100%', sections: t.sections || [] }];
- const colsXml = cols.map((col, ci) => {
- const secsXml = ((col && col.sections) || []).map((sec, si) => {
+ const cellXml = (cell) => {
+ const control = cell.control || {};
+ const classId = control.classId && control.classId !== 'undefined' ? String(control.classId).replace(/[{}]/g, '') : '';
+ return `<cell colspan="${cell.colspan || 1}" rowspan="${cell.rowspan || 1}"${cell.visible === false ? ' visible="false"' : ''}>`
+ + `<control${control.fieldName ? ` datafieldname="${esc(control.fieldName)}"` : ''}${classId ? ` classid="{${esc(classId)}}"` : ''}`
+ + `${control.isReadOnly ? ' disabled="true"' : ''} /></cell>`;
+ };
+ const tabsXml = (compileFormIntent(spec, form).tabs || []).map((t) => {
+ const colsXml = (t.columns || []).map((col) => {
+ const secsXml = (col.sections || []).map((sec) => {
const width = Math.max(1, Math.min(4, Number(sec.columns) || 1));
- const entries = (sec.fields || []).map((f) => (typeof f === 'string' ? { name: f } : (f || {})));
- const rows = [];
- let cur = [];
- let used = 0;
- for (const e of entries) {
- const span = Math.min(width, Math.max(1, Number(e.colspan) || 1));
- if (used + span > width && cur.length) { rows.push(cur); cur = []; used = 0; }
- cur.push({ name: String(e.name || '').toLowerCase(), colspan: span, rowspan: Math.max(1, Number(e.rowspan) || 1) });
- used += span;
- }
- if (cur.length) rows.push(cur);
- const rowsXml = rows.map((r) => `<row>${r.map((c) => `<cell colspan="${c.colspan}" rowspan="${c.rowspan}">`
- + `<control datafieldname="${esc(c.name)}" /></cell>`).join('')}</row>`).join('');
- const name = sec.name || `section_${ti}_${ci}_${si}`;
- return `<section name="${esc(name)}" columns="${'1'.repeat(width)}">${labels(sec.label || 'Details')}`
- + `<rows>${rowsXml}</rows></section>`;
+ const rowsXml = (sec.rows || []).map((r) => `<row>${(r.cells || []).map(cellXml).join('')}</row>`).join('');
+ return `<section name="${esc(sec.name)}" columns="${'1'.repeat(width)}" visible="${sec.visible !== false}" showlabel="${sec.showLabel !== false}">`
+ + `${labels(sec.label)}<rows>${rowsXml}</rows></section>`;
}).join('');
- return `<column width="${esc((col && col.width) || '100%')}"><sections>${secsXml}</sections></column>`;
+ return `<column width="${esc(col.width)}"><sections>${secsXml}</sections></column>`;
}).join('');
- const tabName = t.name || `tab_${ti}`;
- return `<tab name="${esc(tabName)}">${labels(t.label || 'General')}<columns>${colsXml}</columns></tab>`;
+ return `<tab name="${esc(t.name)}" expanded="${t.expanded !== false}" visible="${t.visible !== false}">${labels(t.label)}<columns>${colsXml}</columns></tab>`;
}).join('');
return `<form><tabs>${tabsXml}</tabs></form>`;
}
-function makeAllPresentReader(spec) {
+function makeAllPresentReader(spec, formEvidence = null) {
const entities = new Set((spec.entities || []).map((e) => lc(e.schemaName)));
const columnsByEntity = {};
for (const e of spec.entities || []) {
columnsByEntity[lc(e.schemaName)] = (e.columns || []).map((c) => ({ logicalName: lc(c.schemaName) }));
}
+ const implementedPages = (spec.pages || []).filter((p) => {
+ const source = normalizePageSource(p);
+ return source && source.kind === 'tsx' && source.codeFile;
+ });
+ const idOfPage = (p) => p.pageId || `gp-${p.key || p.name}`;
+ const pageByKey = new Map((spec.pages || []).map((p) => [p.key || p.name, p]));
// Build a sitemap XML fragment covering the entity subareas declared in appShell. The page/icon
// checks in verifySpec only fire for implemented pages (source.kind==='tsx') — intent-only specs
@@ -426,7 +485,7 @@ function makeAllPresentReader(spec) {
for (const sa of g.subAreas || []) {
const attrs = [];
if (sa.entity) attrs.push(`Entity="${lc(sa.entity)}"`);
- if (sa.page) attrs.push(`Type="GenPage" GenPageId="gp-${sa.page}"`);
+ if (sa.page) attrs.push(`Type="GenPage" GenPageId="${pageByKey.has(sa.page) ? idOfPage(pageByKey.get(sa.page)) : `gp-${sa.page}`}"`);
// Dashboard subarea: verifySpec resolves the dashboard id via queryRecords (which returns
// formid 'x' below) and then confirms a SubArea points at THAT id via DefaultDashboard — and
// carries the dashboard launcher Url, as every dashboard entry the build writes does.
@@ -482,6 +541,20 @@ function makeAllPresentReader(spec) {
// `businessunit` query returns a root BU so the BU-scoped, fail-closed role check resolves offline.
queryRecords: async (set, opts) => {
const filter = String((opts && opts.filter) || '');
+ if (set === 'systemform' && formEvidence) {
+ // Real resolver filters include both the table and numeric type, e.g.
+ // objecttypecode eq 'cnt_workitem' and name eq 'Work Item' and type eq 2.
+ const name = /\bname eq '((?:[^']|'')*)'/.exec(filter);
+ const entity = /\bobjecttypecode eq '((?:[^']|'')*)'/.exec(filter);
+ const type = /\btype eq (\d+)/.exec(filter);
+ const pin = /\bformid eq ([0-9a-f-]+)/i.exec(filter);
+ return (formEvidence.forms || []).filter((f) =>
+ (!name || f.name === name[1].replace(/''/g, "'"))
+ && (!entity || lc(f.entity) === lc(entity[1].replace(/''/g, "'")))
+ && (!type || FORM_TYPE_CODE[f.formType || 'Main'] === Number(type[1]))
+ && (!pin || lc(f.id) === lc(pin[1])))
+ .map((f) => ({ formid: f.id, objecttypecode: f.entity, type: FORM_TYPE_CODE[f.formType || 'Main'], name: f.name }));
+ }
const mainForm = set === 'systemform' && / type eq 2\b/.test(filter) && /\bname eq '((?:[^']|'')*)'/.exec(filter);
if (mainForm) return [{ formid: `form:${mainForm[1].replace(/''/g, "'")}` }];
return set === 'role'
@@ -493,28 +566,186 @@ function makeAllPresentReader(spec) {
: [{ savedqueryid: 'x', savedqueryvisualizationid: 'x', formid: 'x' }];
},
sitemapXml: async () => xml,
+ sitemapPageIds: async () => implementedPages.map(idOfPage),
+ existenceIds: async () => implementedPages.map(idOfPage),
+ manifest: async () => ({ pages: implementedPages.map((p) => ({ key: p.key || p.name, pageId: idOfPage(p) })) }),
// The layout oracle. An "all present" reader that cannot read layouts would make verify report
// every explicit form as UNVERIFIED — correct behaviour, but a fixture gap rather than a finding
// about the spec. Rendering the AUTHORED layout is the honest synthesis here: the reader's whole
// premise is "the environment already matches the spec". A Main form with an auto layout has no
// authored tabs to render, so it answers with its form order alone.
formTopology: async (entityLogical, formId) => {
+ if (formEvidence) {
+ const deployed = (formEvidence.forms || []).find((f) => lc(f.entity) === lc(entityLogical) && lc(f.id) === lc(formId));
+ return deployed ? deployed.xml : null;
+ }
const named = /^form:([\s\S]*)$/.exec(String(formId || ''));
const form = named
? (spec.forms || []).find((f) => isMainForm(f) && lc(f.entity) === lc(entityLogical) && mainFormName(f) === named[1])
: (spec.forms || []).find((f) => lc(f.entity) === lc(entityLogical) && Array.isArray(f.tabs) && f.tabs.length);
if (!form) return null;
- const layout = Array.isArray(form.tabs) && form.tabs.length ? formXmlForAuthoredLayout(form) : '<form><tabs></tabs></form>';
+ const layout = Array.isArray(form.tabs) && form.tabs.length ? formXmlForAuthoredLayout(spec, form) : '<form><tabs></tabs></form>';
return isMainForm(form) ? withOrder(layout, lc(entityLogical), form) : layout;
},
+ servedMainForms: async (entityLogical) => formEvidence
+ ? ((formEvidence.servedMainForms || {})[lc(entityLogical)] || [])
+ : (plannedMainFormSequence(spec, entityLogical) || []).map((f) => ({ id: `form:${mainFormName(f)}`, name: mainFormName(f) })),
+ };
+}
+
+function requiredVerifyChecks(spec, reader) {
+ const mains = [...new Set((spec.forms || []).filter(isMainForm).map((f) => lc(f.entity)))];
+ const ordered = mains.filter((entity) => plannedMainFormSequence(spec, entity));
+ const pages = (spec.pages || []).filter((p) => {
+ const source = normalizePageSource(p);
+ return source && source.kind === 'tsx' && source.codeFile;
+ });
+ const subareas = ((spec.appShell && spec.appShell.areas) || []).flatMap((a) => (a.groups || []).flatMap((g) => g.subAreas || []));
+ const counts = {
+ entity: (spec.entities || []).length,
+ column: (spec.entities || []).reduce((n, e) => n + (e.columns || []).length, 0),
+ view: (spec.views || []).length,
+ chart: (spec.charts || []).length,
+ form: (spec.forms || []).length,
+ dashboard: (spec.dashboards || []).length,
+ 'form-order': ordered.length,
+ 'form-topology': (spec.forms || []).filter((f) => Array.isArray(f.tabs) && f.tabs.length).length,
+ 'form-order-served': typeof reader.servedMainForms === 'function' ? ordered.length : 0,
+ 'business-rule': (spec.businessRules || []).length,
+ 'business-process-flow': (spec.businessProcessFlows || []).length,
+ role: (spec.personas || []).length,
+ subarea: subareas.filter((s) => s.entity || s.dashboard).length,
+ 'subarea-dashboard-launcher': subareas.filter((s) => s.dashboard).length,
+ page: pages.length,
+ 'page-subarea': pages.length,
+ };
+ return {
+ requiredChecks: Object.fromEntries(Object.entries(counts).filter(([, n]) => n > 0)),
+ optionalUnavailable: ordered.length && typeof reader.servedMainForms !== 'function'
+ ? [{ capability: 'servedMainForms', reason: 'servedMainForms is unavailable (optional served Main form order reader)' }]
+ : [],
+ };
+}
+
+async function verifyFacts(spec, options = {}) {
+ const formEvidence = options.fixture && options.fixture.evidence && options.fixture.evidence.formReconcile;
+ const reader = options.verifyReader || makeAllPresentReader(spec, formEvidence);
+ const coverage = requiredVerifyChecks(spec, reader);
+ try {
+ const result = await (options.verifier || verifySpec)(spec, reader);
+ if (!result || typeof result.ok !== 'boolean' || !Array.isArray(result.checks) || !Array.isArray(result.missing)) {
+ throw new Error('verifySpec returned no valid verification result');
+ }
+ return { ...result, ...coverage };
+ } catch (e) {
+ // Required verification is fail-closed. A missing method, broken import or exception is evidence
+ // the eval could not prove correctness, not permission to make the corpus greener with a SKIP.
+ const error = (e && e.message) || String(e);
+ return { ok: false, error, checks: [], missing: [{ kind: 'verify-error', name: 'verifySpec', present: false, detail: error }], ...coverage };
+ }
+}
+
+const QUICK_VIEW_CLASS_ID = '5c5600e0-1d6e-4205-a272-be80da87fd42';
+function quickViewsFromXml(xml) {
+ const attr = (raw, name) => {
+ const hit = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(raw || '');
+ return hit ? decodeXmlEntities(hit[1] === undefined ? hit[2] : hit[1]) : '';
};
+ const out = [];
+ // Quick View parameters are nested wire XML, not an ordinary field state:
+ // <control classid="{5C5600E0-...}" datafieldname="cnt_projectid"><parameters>
+ // <QuickForms><QuickFormIds><QuickFormId entityname="cnt_project">GUID</QuickFormId>...
+ // Also retain a wrong-class control with these parameters so it cannot disappear into a skip.
+ const source = String(xml || '').replace(/<!--[\s\S]*?-->/g, '');
+ for (const control of source.matchAll(/<control\b([^>]*?)(?:\/>|>([\s\S]*?)<\/control>)/gi)) {
+ const classId = attr(control[1], 'classid').replace(/[{}]/g, '').toLowerCase();
+ const form = /<QuickFormId\b([^>]*)>([^<]*)<\/QuickFormId>/i.exec(control[2] || '');
+ if (classId !== QUICK_VIEW_CLASS_ID && !form) continue;
+ out.push({
+ classId,
+ lookup: lc(attr(control[1], 'datafieldname')),
+ targetEntity: form ? lc(attr(form[1], 'entityname')) : '',
+ formId: form ? lc(form[2].trim().replace(/[{}]/g, '')) : '',
+ });
+ }
+ return out;
}
-async function verifyFacts(spec) {
- try { return await verifySpec(spec, makeAllPresentReader(spec)); }
- // If verifySpec calls a reader method not in our synthetic reader (Plan 3 extensions), the
- // assertion layer degrades the result to a SKIP rather than failing the harness.
- catch (e) { return { skipped: e.message }; }
+function formReconcileFacts(spec, fixture) {
+ const evidence = fixture && fixture.evidence && fixture.evidence.formReconcile;
+ if (!evidence) return null;
+ if (!fixture.baselineSpec) return { error: 'form reconciliation evidence has no baseline App Spec' };
+ const before = migrateAppSpec(fixture.baselineSpec);
+ const edits = (spec.forms || []).filter((f) => Array.isArray(f.tabs)).map((f) => {
+ const prior = (before.forms || []).find((p) => lc(p.entity) === lc(f.entity) && p.name === f.name && (p.formType || 'Main') === (f.formType || 'Main'));
+ return { entity: lc(f.entity), name: f.name, before: authoredFormShape(prior), after: authoredFormShape(f) };
+ });
+ const quickViews = [];
+ for (const f of spec.forms || []) for (const qv of f.quickViews || []) {
+ const host = (evidence.forms || []).find((p) => lc(p.entity) === lc(f.entity) && p.name === f.name && (p.formType || 'Main') === (f.formType || 'Main'));
+ const target = (evidence.forms || []).find((p) => lc(p.entity) === lc(qv.targetEntity) && p.name === qv.form && p.formType === 'QuickView');
+ quickViews.push({
+ host: f.name, lookup: lc(qv.lookup), targetEntity: lc(qv.targetEntity), form: qv.form,
+ formId: target ? lc(target.id) : null,
+ deployed: quickViewsFromXml(host && host.xml),
+ });
+ }
+ return {
+ baselineValidation: validateAppSpec(before, { profile: 'plan' }),
+ edits,
+ beforeMainFormOrder: (before.entities || []).map((e) => ({ entity: lc(e.schemaName), forms: e.mainFormOrder || [] })),
+ afterMainFormOrder: (spec.entities || []).map((e) => ({ entity: lc(e.schemaName), forms: e.mainFormOrder || [] })),
+ quickViews,
+ };
+}
+
+async function changedOnlyFacts(spec, fixture) {
+ const evidence = fixture && fixture.evidence && fixture.evidence.changedOnly;
+ if (!evidence) return null;
+ try {
+ if (!fixture.baselineSpec || !fixture.entityEditSpec) throw new Error('changed-only evidence needs baseline and entity-edited App Specs');
+ const baselineDir = path.join(fixture.dir, 'baseline');
+ const baseline = migrateAppSpec(fixture.baselineSpec);
+ const entityEdit = migrateAppSpec(fixture.entityEditSpec);
+ const annotate = (input, dir) => {
+ const validation = validateAppSpec(input, { profile: 'deploy' });
+ if (!validation.ok) throw new Error(`changed-only input validation: ${validation.errors.join('; ')}`);
+ const sourceErrors = pageSourceFileErrors(input, dir);
+ if (sourceErrors.length) throw new Error(`changed-only sources: ${sourceErrors.join('; ')}`);
+ return annotateContentHashes(input, (relative) => fs.readFileSync(path.join(dir, relative)));
+ };
+ const prior = annotate(baseline, baselineDir);
+ const current = annotate(spec, fixture.dir);
+ const columnEdited = annotate(entityEdit, baselineDir);
+ const verified = await verifyFacts(baseline);
+ if (!verified.ok || Object.entries(verified.requiredChecks).some(([kind, n]) => verified.checks.filter((c) => c.kind === kind).length < n)) {
+ throw new Error(`changed-only baseline could not be verified: ${JSON.stringify(verified.missing)}`);
+ }
+ // Exercise the real envelope lifecycle, including its serialization boundary. No workspace
+ // lease, disk snapshot or live identity query is needed to test this pure eligibility gate.
+ const envelope = makeEnvelope(evidence.identity, { generation: evidence.generation, priorSpec: prior });
+ const promoted = markEligible(envelope);
+ if (!promoted.ok) throw new Error(`changed-only snapshot promotion failed: ${promoted.reason}`);
+ const persisted = parseEnvelope(serializeEnvelope(envelope));
+ if (!persisted) throw new Error('changed-only snapshot could not be parsed after serialization');
+ const snapshot = isFastPathEligible(persisted, evidence.identity);
+ return {
+ baselineVerified: verified.ok,
+ snapshot,
+ contentHashes: (current.pages || []).map((p) => ({
+ key: p.key || p.name,
+ before: (persisted.priorSpec.pages || []).find((b) => (b.key || b.name) === (p.key || p.name)).__contentSha,
+ after: p.__contentSha,
+ })),
+ cases: [
+ { name: 'page-only', ...classifyChanges(current, persisted.priorSpec) },
+ { name: 'column-edit', ...classifyChanges(columnEdited, persisted.priorSpec) },
+ { name: 'identical', ...classifyChanges(annotate(baseline, baselineDir), persisted.priorSpec) },
+ ],
+ };
+ } catch (e) {
+ return { error: (e && e.message) || String(e) };
+ }
}
// page: PAGEREF_ resolution facts (Plan 3). Returns null when pageref-resolver isn't loaded →
@@ -621,7 +852,8 @@ function processFacts(spec) {
// pages with a GenPageId, entities, dashboards keyed by id), then hydrated back. Synthetic ids are
// deterministic (`gp-<key>` / `dash-<name>`) so GenPage/DashBoard subareas resolve back to their
// page-key / dashboard-name exactly as a live download would.
-function buildDeployedReader(spec) {
+function buildDeployedReader(spec, downloadedPages = null) {
+ const idOf = (p) => p.pageId || `gp-${p.key || p.name}`;
const areas = ((spec.appShell && spec.appShell.areas) || []).map((a) => ({
title: a.label,
...(a.icon ? { icon: a.icon } : {}),
@@ -631,7 +863,10 @@ function buildDeployedReader(spec) {
subAreas: (g.subAreas || []).map((sa) => {
const base = { title: sa.title, ...(sa.icon ? { icon: sa.icon } : {}), ...(sa.vectorIcon ? { vectorIcon: sa.vectorIcon } : {}) };
if (sa.entity) return { ...base, type: 'Entity', entity: sa.entity };
- if (sa.page) return { ...base, type: 'GenPage', genPageId: `gp-${sa.page}` };
+ if (sa.page) {
+ const page = (spec.pages || []).find((p) => (p.key || p.name) === sa.page);
+ return { ...base, type: 'GenPage', genPageId: page ? idOf(page) : `gp-${sa.page}` };
+ }
if (sa.dashboard) return { ...base, type: 'DashBoard', dashboardId: `dash-${sa.dashboard}` };
if (sa.url) return { ...base, type: 'URL', url: sa.url };
return base;
@@ -641,8 +876,9 @@ function buildDeployedReader(spec) {
return {
app: async () => ({ name: spec.app.name, description: spec.app.description || '', siteMap: { areas } }),
// Emit the v2 (keyed) page shape so hydrate resolves GenPage subareas by key and preserves them.
- pages: async () => (spec.pages || []).map((p) => ({
- pageId: `gp-${p.key || p.name}`, key: p.key || p.name, name: p.name,
+ pages: async () => downloadedPages || (spec.pages || []).map((p) => ({
+ pageId: idOf(p), key: p.key || p.name, name: p.name,
+ ...(p.model !== undefined ? { model: p.model } : {}),
...(p.purpose !== undefined ? { purpose: p.purpose } : {}),
...(p.dataSources ? { dataSources: p.dataSources } : {}),
...(p.navigatesTo ? { navigatesTo: p.navigatesTo } : {}),
@@ -663,13 +899,32 @@ function buildDeployedReader(spec) {
}
// round-trip: project the spec into a deployed app, hydrate it back, and expose the recovered
-// solution / tables / page-keys / sitemap so assertions can prove the download→rebuild is lossless
-// (create == edit). Never throws — a hydrate error is captured as `error` and surfaced by the assertion.
-async function roundTripFacts(spec) {
- let hydrated;
- try { hydrated = await hydrateSpec(buildDeployedReader(spec)); }
- catch (e) { return { error: e.message }; }
+// solution / tables / page metadata / sitemap for the compared hydration subset. A hydrate error is
+// captured as `error` and surfaced by assertions; no build or live download is executed here.
+async function roundTripFacts(spec, options = {}) {
+ let hydrated, downloadedPages = null;
+ const unreadableConfigs = [], unkeptModels = [];
+ const fixture = options.fixture;
+ const evidence = fixture && fixture.evidence && fixture.evidence.pageRoundTrip;
+ try {
+ if (evidence) {
+ const rawNames = new Map((evidence.envPages || []).map((p) => [lc(p.pageId), p.name]));
+ const titles = new Map();
+ for (const a of (spec.appShell && spec.appShell.areas) || []) for (const g of a.groups || []) for (const sa of g.subAreas || []) {
+ if (sa.page) titles.set(sa.page, sa.title);
+ }
+ // Match download's seam: env-wide names outrank sitemap titles; PAC's \" is decoded before
+ // parseDownloadedPages reads the real config files, then assignPageKeys supplies stable keys.
+ const nameById = new Map((spec.pages || []).map((p) => [lc(p.pageId),
+ unescapePacName(rawNames.get(lc(p.pageId)) || titles.get(p.key || p.name) || p.pageId)]));
+ downloadedPages = parseDownloadedPages(path.join(fixture.dir, 'pages'), fixture.dir, nameById, unreadableConfigs, unkeptModels);
+ assignPageKeys(downloadedPages, { pages: spec.pages || [] }, new Map((spec.pages || []).map((p) => [p.key || p.name, p.pageId])));
+ }
+ hydrated = await (options.hydrator || hydrateSpec)(buildDeployedReader(spec, downloadedPages));
+ }
+ catch (e) { return { error: (e && e.message) || String(e) }; }
return {
+ source: evidence ? 'pac-download-fixture' : 'synthetic-reader',
solution: hydrated.solution && hydrated.solution.uniqueName,
tables: (hydrated.entities || []).map((e) => lc(e.schemaName)).sort(),
pageKeys: (hydrated.pages || []).map((p) => p.key || p.name).sort(),
@@ -680,6 +935,13 @@ async function roundTripFacts(spec) {
// value from a silently rewritten one.
origDirectEntry: directEntryByKey(spec.pages),
hydratedDirectEntry: directEntryByKey(hydrated.pages),
+ pageMetadata: (hydrated.pages || []).map((p) => ({
+ key: p.key || p.name, pageId: p.pageId || null, name: p.name,
+ model: p.model === undefined ? null : p.model,
+ dataSources: p.dataSources || [],
+ })).sort((a, b) => String(a.key).localeCompare(String(b.key))),
+ unreadableConfigs,
+ unkeptModels,
};
}
@@ -739,21 +1001,26 @@ function securityFacts(spec) {
});
}
-async function stageFacts(rawSpec) {
+async function stageFacts(rawSpec, options = {}) {
+ // Capture approved text before any producer sees the input. Comparing with rawSpec after a
+ // mutating lint/migration would let a sanitizer rewrite both the result and its expectation.
+ const approvedPageNames = (Array.isArray(rawSpec && rawSpec.pages) ? rawSpec.pages : []).map((p) => p && p.name);
const spec = migrateAppSpec(rawSpec);
return {
- author: authorFacts(spec),
+ author: authorFacts(spec, approvedPageNames),
plan: planFacts(spec),
data: schemaFacts(spec),
ui: wireFacts(spec),
app: appFacts(spec),
security: securityFacts(spec),
- verify: await verifyFacts(spec),
+ verify: await verifyFacts(spec, options),
+ formReconcile: formReconcileFacts(spec, options.fixture),
+ changedOnly: await changedOnlyFacts(spec, options.fixture),
page: pageFacts(spec),
process: processFacts(spec),
teardown: teardownFacts(spec),
download: downloadFacts(spec),
- roundTrip: await roundTripFacts(spec),
+ roundTrip: await roundTripFacts(spec, options),
PHASES,
};
}
diff --git a/evals/model-apps/app-builder/lib/fixture-loader.js b/evals/model-apps/app-builder/lib/fixture-loader.js
index 20c10feaf..777c7acc3 100644
--- a/evals/model-apps/app-builder/lib/fixture-loader.js
+++ b/evals/model-apps/app-builder/lib/fixture-loader.js
@@ -1,6 +1,33 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
+const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+
+function readFixtureJson(file, fixtureName, kind) {
+ const raw = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
+ let value;
+ try { value = JSON.parse(raw); }
+ catch (e) { throw new Error(`Fixture ${fixtureName}: ${file} is not valid JSON — ${e.message}`); }
+ if (!isObject(value)) {
+ throw new Error(`Fixture ${fixtureName}: ${file} must contain a JSON object (${kind}), got ${Array.isArray(value) ? 'an array' : value === null ? 'null' : typeof value}`);
+ }
+ return value;
+}
+
+function fixtureFile(dir, relative, fixtureName) {
+ if (typeof relative !== 'string' || !relative) throw new Error(`Fixture ${fixtureName}: evidence file must be a non-empty relative path`);
+ const root = fs.realpathSync(dir);
+ // Both containment checks must use the canonical root; a junction alias is not an escape.
+ const file = path.resolve(root, relative);
+ const confined = (candidate) => {
+ const rel = path.relative(root, candidate);
+ return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
+ };
+ if (!confined(file) || !confined(fs.realpathSync(file))) {
+ throw new Error(`Fixture ${fixtureName}: evidence file '${relative}' resolves outside the fixture`);
+ }
+ return file;
+}
// Load each fixture subdir (named "<eval-id>-<slug>"); its app-spec.json is the graded input.
// Mirrors evals/model-apps/genpage/lib/fixture-loader.js, but the app-builder input is the App
@@ -23,19 +50,26 @@ function loadFixtures(fixturesDir) {
if (!fs.existsSync(specPath)) continue;
// Strip a UTF-8 BOM: editors on Windows add one by default and `JSON.parse` rejects the
// leading \uFEFF, which failed the whole run for a file that is otherwise valid JSON.
- const raw = fs.readFileSync(specPath, 'utf8').replace(/^\uFEFF/, '');
- let spec;
- try {
- spec = JSON.parse(raw);
- } catch (e) {
- throw new Error(`Fixture ${entry.name}: ${specPath} is not valid JSON — ${e.message}`);
- }
- // `null`, `[]`, `"str"` and numbers all parse fine and were accepted as specs, so the real
- // problem surfaced much later as an opaque stage-facts error. An App Spec is a JSON object.
- if (spec === null || typeof spec !== 'object' || Array.isArray(spec)) {
- throw new Error(`Fixture ${entry.name}: ${specPath} must contain a JSON object (an App Spec), got ${Array.isArray(spec) ? 'an array' : spec === null ? 'null' : typeof spec}`);
+ const spec = readFixtureJson(specPath, entry.name, 'an App Spec');
+ const evidencePath = path.join(dir, 'evidence.json');
+ const evidence = fs.existsSync(evidencePath) ? readFixtureJson(evidencePath, entry.name, 'eval evidence') : {};
+ if (evidence.formReconcile !== undefined) {
+ const reconcile = evidence.formReconcile;
+ if (!isObject(reconcile) || !Array.isArray(reconcile.forms)) {
+ throw new Error(`Fixture ${entry.name}: formReconcile must be an object with a forms array`);
+ }
+ for (const [i, form] of reconcile.forms.entries()) {
+ if (!isObject(form) || ['id', 'entity', 'name'].some((key) => typeof form[key] !== 'string' || !form[key].trim())) {
+ throw new Error(`Fixture ${entry.name}: formReconcile.forms[${i}] must be an object with id, entity and name`);
+ }
+ form.xml = fs.readFileSync(fixtureFile(dir, form.xmlFile, entry.name), 'utf8');
+ }
}
- fixtures.push({ id: parseInt(m[1], 10), dirName: entry.name, dir, spec });
+ const baselinePath = path.join(dir, 'baseline-app-spec.json');
+ const baselineSpec = fs.existsSync(baselinePath) ? readFixtureJson(baselinePath, entry.name, 'an App Spec baseline') : null;
+ const entityEditPath = path.join(dir, 'entity-edit-app-spec.json');
+ const entityEditSpec = fs.existsSync(entityEditPath) ? readFixtureJson(entityEditPath, entry.name, 'an entity-edited App Spec') : null;
+ fixtures.push({ id: parseInt(m[1], 10), dirName: entry.name, dir, spec, evidence, baselineSpec, entityEditSpec });
}
return fixtures;
}
diff --git a/evals/model-apps/app-builder/run-app-builder.js b/evals/model-apps/app-builder/run-app-builder.js
index 6a65bf70d..d1d25c776 100644
--- a/evals/model-apps/app-builder/run-app-builder.js
+++ b/evals/model-apps/app-builder/run-app-builder.js
@@ -29,6 +29,35 @@ function loadEvals() {
return JSON.parse(fs.readFileSync(path.join(__dirname, 'evals.json'), 'utf8'));
}
+// Grades one fixture: `notes` are the TAP comment lines (lint warnings, omitted page models) and
+// `results` the assertions in report order, `kind` saying which list each came from. main() reports
+// exactly these, and evals/model-apps/tests/eval-coverage-contract.test.js reads the same results.
+async function gradeFixture(fix, ev, evalsData) {
+ if (!ev) {
+ return { notes: [], results: [{ kind: 'gate', text: `fixture references eval id ${fix.id}`, result: { status: 'fail', reason: `no eval id ${fix.id} in evals.json` } }] };
+ }
+ let facts;
+ try { facts = await stageFacts(fix.spec, { fixture: fix }); }
+ catch (e) {
+ return { notes: [], results: [{ kind: 'gate', text: 'stage facts computed without error', result: { status: 'fail', reason: e.message } }] };
+ }
+ const notes = [
+ ...(facts.author.lint.warnings || []).map((warning) => ` # lint warning: ${JSON.stringify(warning)}`),
+ ...(facts.roundTrip.unkeptModels || []).map((model) => ` # page model omitted (a rebuild stores it empty): ${JSON.stringify(model)}`),
+ ];
+ const texts = [
+ ...evalsData.common_stage_assertions.map((text) => ({ kind: 'common', text })),
+ ...(ev.expectations || []).map((text) => ({ kind: 'expectation', text })),
+ ];
+ const results = texts.map(({ kind, text }) => {
+ const check = ASSERTIONS.get(text);
+ return { kind, text, result: check
+ ? check({ facts, spec: fix.spec, eval: ev })
+ : { status: 'skip', reason: 'no check registered for this assertion text' } };
+ });
+ return { notes, results };
+}
+
async function main() {
const args = parseArgs(process.argv.slice(2));
const fixturesDir = args.fixtures ? path.resolve(args.fixtures) : path.join(__dirname, 'fixtures');
@@ -51,26 +80,9 @@ async function main() {
for (const fix of selected) {
reporter.startFixture(fix.dirName);
- const ev = evalById.get(fix.id);
- if (!ev) {
- reporter.assertion(`fixture references eval id ${fix.id}`, { status: 'fail', reason: `no eval id ${fix.id} in evals.json` });
- reporter.endFixture();
- continue;
- }
- let facts;
- try { facts = await stageFacts(fix.spec); }
- catch (e) {
- reporter.assertion('stage facts computed without error', { status: 'fail', reason: e.message });
- reporter.endFixture();
- continue;
- }
- const texts = [...evalsData.common_stage_assertions, ...(ev.expectations || [])];
- for (const text of texts) {
- const check = ASSERTIONS.get(text);
- reporter.assertion(text, check
- ? check({ facts, spec: fix.spec, eval: ev })
- : { status: 'skip', reason: 'no check registered for this assertion text' });
- }
+ const { notes, results } = await gradeFixture(fix, evalById.get(fix.id), evalsData);
+ for (const line of notes) reporter.write(line);
+ for (const { text, result } of results) reporter.assertion(text, result);
reporter.endFixture();
}
@@ -79,4 +91,4 @@ async function main() {
}
if (require.main === module) main();
-module.exports = { main, parseArgs };
+module.exports = { main, parseArgs, gradeFixture };
diff --git a/evals/model-apps/app-builder/tests/facts.test.js b/evals/model-apps/app-builder/tests/facts.test.js
index bd83a3582..9498d0575 100644
--- a/evals/model-apps/app-builder/tests/facts.test.js
+++ b/evals/model-apps/app-builder/tests/facts.test.js
@@ -1,13 +1,30 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
-const { stageFacts } = require('../lib/facts.js');
+const path = require('node:path');
+const fs = require('node:fs');
+const os = require('node:os');
+const { spawnSync } = require('node:child_process');
+const { stageFacts, makeAllPresentReader } = require('../lib/facts.js');
const { ASSERTIONS } = require('../lib/assertions.js');
+const { loadFixtures } = require('../lib/fixture-loader.js');
+const evalsManifest = require('../evals.json');
+
+function fixtureFor(id) {
+ const fixture = loadFixtures(path.join(__dirname, '..', 'fixtures')).find((f) => f.id === id);
+ assert.ok(fixture, `fixture ${id} exists`);
+ return fixture;
+}
+
+function score(text, facts, fixture) {
+ const check = ASSERTIONS.get(text);
+ assert.strictEqual(typeof check, 'function', `registered assertion: ${text}`);
+ return check({ facts, spec: fixture.spec, eval: evalsManifest.evals.find((e) => e.id === fixture.id) });
+}
// A minimal but valid schemaVersion:2 spec covering all stage primitives: one entity with a
// Choice column, a view, a chart, a form, an intent page (no .tsx), and a sitemap subarea for each.
-// The page key and name are the same string to avoid the linter's name-vs-key ambiguity in subarea
-// references (spec-lint.js validates sa.page against p.name, not p.key).
+// The page key and display name intentionally differ: v2 sitemap references use the stable key.
const spec = {
schemaVersion: 2,
solution: { uniqueName: 'S', publisherPrefix: 'new' },
@@ -20,9 +37,7 @@ const spec = {
views: [{ entity: 'new_order', name: 'Active Orders', columns: ['new_name', 'new_status'], activeOnly: true }],
charts: [{ entity: 'new_order', name: 'Orders by Status', groupBy: 'new_status', measure: 'count', chartType: 'Pie' }],
forms: [{ entity: 'new_order', type: 'main', name: 'Order', layout: 'auto' }],
- // The page's name matches the key (both "overview"); validateAppSpec(v2) checks sa.page against
- // page keys, while lintAppSpec checks against page names — making key === name satisfies both.
- pages: [{ key: 'overview', name: 'overview', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'overview' }] }],
+ pages: [{ key: 'overview', name: 'Overview', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'overview' }] }],
appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [
{ entity: 'new_order', title: 'Orders' },
{ page: 'overview', title: 'Overview' },
@@ -54,8 +69,90 @@ test('stageFacts.app resolves every sitemap subarea and reports no dangling nav'
test('stageFacts.plan groups items by known engine phase; verify runs offline', async () => {
const f = await stageFacts(spec);
assert.ok(f.plan.phases.every((p) => f.PHASES.includes(p)), `unknown phase in plan: ${f.plan.phases.filter((p) => !f.PHASES.includes(p))}`);
- // verifySpec either succeeds (ok:true) or degrades gracefully (skipped string) — never throws.
- assert.ok(f.verify.ok === true || typeof f.verify.skipped === 'string', `unexpected verify result: ${JSON.stringify(f.verify)}`);
+ assert.strictEqual(f.verify.ok, true, `unexpected verify result: ${JSON.stringify(f.verify)}`);
+ assert.deepStrictEqual(f.verify.missing, []);
+});
+
+test('verification exceptions fail the eval rather than skip', async () => {
+ const layoutSpec = require('../fixtures/6-form-layout/app-spec.json');
+ const check = ASSERTIONS.get('verify: reconcile against an all-present reader returns ok with no missing');
+ const positive = await stageFacts(layoutSpec);
+ assert.strictEqual(check({ facts: positive }).status, 'pass');
+
+ const throwingVerifier = await stageFacts(layoutSpec, {
+ verifier: async () => { throw new Error('verifier regression'); },
+ });
+ assert.strictEqual(throwingVerifier.verify.ok, false);
+ assert.strictEqual(throwingVerifier.verify.skipped, undefined);
+ const failure = check({ facts: throwingVerifier });
+ assert.strictEqual(failure.status, 'fail');
+ assert.match(failure.reason, /verifier regression/);
+
+ const reader = makeAllPresentReader(layoutSpec);
+ reader.formTopology = async () => { throw new Error('topology read regression'); };
+ const throwingReader = await stageFacts(layoutSpec, { verifyReader: reader });
+ assert.strictEqual(throwingReader.verify.ok, false);
+ assert.strictEqual(check({ facts: throwingReader }).status, 'fail');
+ assert.ok(throwingReader.verify.missing.some((m) => /topology read regression/.test(m.detail)));
+
+ // Isolate the injected plugin export in a child process: a scorer failure must also reach the
+ // runner's exit code, without altering the production module or another test's require cache.
+ const runner = path.join(__dirname, '..', 'run-app-builder.js');
+ const verifierPath = path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', 'lib', 'verify-spec.js');
+ const child = spawnSync(process.execPath, ['-e', `
+ require(${JSON.stringify(verifierPath)}).verifySpec = async () => { throw new Error('verifier regression'); };
+ process.argv = [process.execPath, ${JSON.stringify(runner)}, '--eval', '6'];
+ require(${JSON.stringify(runner)}).main();
+ `], { encoding: 'utf8' });
+ assert.strictEqual(child.status, 1, child.stdout + child.stderr);
+ assert.match(child.stdout, /not ok \d+ - verify: reconcile against an all-present reader/);
+ assert.match(child.stdout, /verifier regression/);
+
+ const malformed = await stageFacts(layoutSpec, { verifier: async () => ({ skipped: 'unspecified optional extension' }) });
+ assert.strictEqual(check({ facts: malformed }).status, 'fail', 'a skip-shaped result is not required verification');
+ const noTopology = makeAllPresentReader(layoutSpec);
+ delete noTopology.formTopology;
+ const absentReader = await stageFacts(layoutSpec, { verifyReader: noTopology });
+ assert.strictEqual(check({ facts: absentReader }).status, 'fail', 'topology is required, unlike the served-order capability');
+ assert.match(check({ facts: absentReader }).reason, /UNVERIFIED/);
+});
+
+test('verification requires each applicable check kind, not just an ok flag', async () => {
+ const f = await stageFacts(require('../fixtures/6-form-layout/app-spec.json'));
+ const check = ASSERTIONS.get('verify: every required check kind actually ran');
+ assert.strictEqual(typeof check, 'function', 'the required-check assertion is registered');
+ assert.strictEqual(check({ facts: f }).status, 'pass');
+ for (const kind of ['entity', 'column', 'view', 'chart', 'form', 'form-order', 'form-topology', 'form-order-served']) {
+ assert.ok(f.verify.requiredChecks[kind] > 0, `${kind} is required by fixture 6`);
+ const drifted = structuredClone(f);
+ drifted.verify.checks = drifted.verify.checks.filter((c) => c.kind !== kind);
+ const result = check({ facts: drifted });
+ assert.strictEqual(result.status, 'fail', `${kind} cannot silently stop running`);
+ assert.ok(result.reason.includes(kind), result.reason);
+ }
+ const empty = structuredClone(f);
+ empty.verify.checks = [];
+ assert.strictEqual(check({ facts: empty }).status, 'fail', 'ok:true with no checks is not verification');
+});
+
+test('an unavailable optional served-form reader is a named skip, never a verifier-error skip', async () => {
+ const layoutSpec = require('../fixtures/6-form-layout/app-spec.json');
+ const check = ASSERTIONS.get('verify: served Main form order is checked or explicitly unavailable');
+ assert.strictEqual(typeof check, 'function', 'the optional capability assertion is registered');
+ const positive = await stageFacts(layoutSpec);
+ assert.strictEqual(check({ facts: positive }).status, 'pass');
+
+ const reader = makeAllPresentReader(layoutSpec);
+ delete reader.servedMainForms;
+ const unavailable = await stageFacts(layoutSpec, { verifyReader: reader });
+ assert.strictEqual(unavailable.verify.ok, true);
+ const result = check({ facts: unavailable });
+ assert.strictEqual(result.status, 'skip');
+ assert.match(result.reason, /servedMainForms.*optional/i);
+
+ reader.servedMainForms = async () => { throw new Error('served order regression'); };
+ const broken = await stageFacts(layoutSpec, { verifyReader: reader });
+ assert.strictEqual(check({ facts: broken }).status, 'fail');
});
test('stageFacts.teardown plans a reverse-of-build delete ending at the solution, web resources after tables', async () => {
@@ -70,7 +167,7 @@ test('stageFacts.teardown plans a reverse-of-build delete ending at the solution
assert.ok(firstWr > lastTable, `web-resource step (${firstWr}) must follow the last table (${lastTable})`);
});
-test('stageFacts.roundTrip hydrates the spec back losslessly (solution, tables, pages, sitemap)', async () => {
+test('stageFacts.roundTrip preserves the compared synthetic metadata (solution, tables, pages, sitemap)', async () => {
const f = await stageFacts(spec);
assert.strictEqual(f.roundTrip.error, undefined, f.roundTrip.error);
assert.strictEqual(f.roundTrip.solution, 'S', 'the solution round-trips');
@@ -270,4 +367,365 @@ test('the form-topology assertion sees a section moved between form-columns', ()
// per-column count matches and only the contents moved.
const swapped = run([tab([[sec('R', ['b'])], [sec('L', ['a'])]])]);
assert.strictEqual(swapped.status, 'fail', 'sections swapped between form-columns must fail');
+});
+
+test('form facts detect state order width and quick-view drift', async () => {
+ const fixture = fixtureFor(7);
+ const facts = await stageFacts(fixture.spec, { fixture });
+ assert.ok(facts.formReconcile, 'independent deployed form evidence is scored');
+ const topology = 'ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)';
+ const state = 'ui: explicit container names display flags and field state match authored intent';
+ const baseline = 'verify: form reconciliation exercises an inserted tab and reordered existing containers';
+ const quickViews = 'verify: Quick View bindings survive form reconciliation';
+ const verify = 'verify: reconcile against an all-present reader returns ok with no missing';
+ for (const text of [topology, state, baseline, quickViews, verify]) {
+ assert.strictEqual(score(text, facts, fixture).status, 'pass', text);
+ }
+ const badBaseline = structuredClone(facts);
+ badBaseline.formReconcile.edits.find((e) => e.name === 'Work Item').before = [];
+ const baselineFailure = score(baseline, badBaseline, fixture);
+ assert.strictEqual(baselineFailure.status, 'fail', 'a fresh-only fixture cannot masquerade as an edit baseline');
+ assert.match(baselineFailure.reason, /baseline tab order/);
+ const main = facts.ui.forms.find((f) => f.name === 'Work Item');
+ assert.deepStrictEqual(main.authoredShape[1].expectedWidths, ['50%', '50%']);
+ assert.strictEqual(main.authoredShape[2].name, 'tab_admin');
+ assert.strictEqual(main.authoredShape[2].visible, false);
+ assert.strictEqual(main.authoredShape[1].sectionsByColumn[0][0].visible, false);
+ assert.strictEqual(main.authoredShape[1].sectionsByColumn[0][1].showLabel, false);
+ assert.ok(main.authoredPlacements.some((p) => p.field === 'cnt_projectid' && p.hidden && p.readOnly));
+ assert.ok(facts.verify.checks.some((c) => c.kind === 'form-order-served' && c.present));
+
+ const xml = fixture.evidence.formReconcile.forms[0].xml;
+ const swap = (source, tag, first, second) => {
+ const block = (name) => new RegExp(`<${tag} name="${name}"[\\s\\S]*?<\\/${tag}>`).exec(source)[0];
+ const a = block(first), b = block(second);
+ return source.replace(a, '__FIRST_CONTAINER__').replace(b, a).replace('__FIRST_CONTAINER__', b);
+ };
+ const changes = [
+ ['hidden tab', (s) => s.replace('name="tab_admin" visible="false"', 'name="tab_admin" visible="true"'), /tab_admin.*visible/],
+ ['collapsed tab', (s) => s.replace('name="tab_admin" visible="false" expanded="false"', 'name="tab_admin" visible="false" expanded="true"'), /tab_admin.*expanded/],
+ ['hidden section', (s) => s.replace('name="section_notes" columns="1" visible="false"', 'name="section_notes" columns="1" visible="true"'), /section_notes.*visible/],
+ ['section label display', (s) => s.replace('name="section_execution" columns="11" visible="true" showlabel="false"', 'name="section_execution" columns="11" visible="true" showlabel="true"'), /section_execution.*showlabel/],
+ ['hidden field', (s) => s.replace('id="lookup_cell" visible="false"', 'id="lookup_cell" visible="true"'), /cnt_projectid.*visible/],
+ ['read-only field', (s) => s.replace('id="project_lookup" datafieldname="cnt_projectid" disabled="true"', 'id="project_lookup" datafieldname="cnt_projectid" disabled="false"'), /cnt_projectid.*disabled/],
+ ['equal-split width', (s) => s.replace('width="50%"', 'width="100%"'), /form-column 1.*100%.*50%/],
+ ['grid width', (s) => s.replace('name="section_execution" columns="11"', 'name="section_execution" columns="1"'), /section_execution.*column/],
+ ['tab order', (s) => swap(s, 'tab', 'tab_intake', 'tab_admin'), /tabs.*order/],
+ ['section order', (s) => swap(s, 'section', 'section_notes', 'section_execution'), /sections.*order/],
+ ['inserted tab missing', (s) => s.replace(/<tab name="tab_intake"[\s\S]*?<\/tab>/, ''), /tab_intake.*absent/],
+ ['field span', (s) => s.replace('colspan="2"', 'colspan="1"'), /cnt_title.*colspan/],
+ ['field rowspan', (s) => s.replace('rowspan="2"', 'rowspan="1"'), /cnt_notes.*rowspan/],
+ ['stored form order', (s) => s.replace('Order="0"', 'Order="2"'), /form-order.*not after/],
+ ];
+ for (const [name, change, reason] of changes) {
+ const changed = structuredClone(fixture);
+ const deployed = change(xml);
+ assert.notStrictEqual(deployed, xml, `${name} changes one deployed fact`);
+ changed.evidence.formReconcile.forms[0].xml = deployed;
+ const drift = await stageFacts(changed.spec, { fixture: changed });
+ const result = score(verify, drift, changed);
+ assert.strictEqual(result.status, 'fail', name);
+ assert.match(result.reason, reason, `${name}: ${result.reason}`);
+ }
+
+ const served = structuredClone(fixture);
+ served.evidence.formReconcile.servedMainForms.cnt_workitem.reverse();
+ const wrongOrder = await stageFacts(served.spec, { fixture: served });
+ assert.strictEqual(score(verify, wrongOrder, served).status, 'fail');
+ assert.match(score(verify, wrongOrder, served).reason, /form-order-served.*Work Item Review/);
+
+ for (const [name, change, reason] of [
+ ['missing Quick View', (s) => s.replace(/<cell id="quickview_cell"[\s\S]*?<\/cell>/, ''), /Quick View.*missing/],
+ ['wrong Quick View form', (s) => s.replace('00000000-0000-0000-0000-000000000703</QuickFormId>', '00000000-0000-0000-0000-000000000704</QuickFormId>'), /Quick View.*form/],
+ ['wrong Quick View lookup', (s) => s.replace('id="project_quickview" classid="{5C5600E0-1D6E-4205-A272-BE80DA87FD42}" datafieldname="cnt_projectid"', 'id="project_quickview" classid="{5C5600E0-1D6E-4205-A272-BE80DA87FD42}" datafieldname="cnt_wrongid"'), /Quick View.*lookup/],
+ ['wrong Quick View target table', (s) => s.replace('QuickFormId entityname="cnt_project"', 'QuickFormId entityname="cnt_workitem"'), /Quick View.*form/],
+ ['wrong Quick View class', (s) => s.replace('classid="{5C5600E0-1D6E-4205-A272-BE80DA87FD42}"', 'classid="{4273EDBD-AC1D-40D3-9FB2-095C621B552D}"'), /Quick View.*control class/],
+ ]) {
+ const changed = structuredClone(fixture);
+ changed.evidence.formReconcile.forms[0].xml = change(xml);
+ assert.notStrictEqual(changed.evidence.formReconcile.forms[0].xml, xml, name);
+ const result = score(quickViews, await stageFacts(changed.spec, { fixture: changed }), changed);
+ assert.strictEqual(result.status, 'fail', name);
+ assert.match(result.reason, reason);
+ }
+
+ // The Quick View is encountered before the ordinary lookup and has the same binding. Its display
+ // state must neither mask a wrong lookup state nor make a correct lookup fail.
+ const independentCard = structuredClone(fixture);
+ independentCard.evidence.formReconcile.forms[0].xml = xml
+ .replace('id="quickview_cell" visible="false"', 'id="quickview_cell" visible="true"')
+ .replace('datafieldname="cnt_projectid" disabled="true">\n', 'datafieldname="cnt_projectid" disabled="false">\n');
+ const unchangedLookup = await stageFacts(independentCard.spec, { fixture: independentCard });
+ assert.strictEqual(score(verify, unchangedLookup, independentCard).status, 'pass');
+
+ for (const [name, mutate] of [
+ ['tab name', (f) => { f.compiledShape[2].name = 'tab_wrong'; }],
+ ['section name', (f) => { f.compiledShape[1].sectionsByColumn[0][0].name = 'section_wrong'; }],
+ ['tab visibility', (f) => { f.compiledShape[2].visible = true; }],
+ ['section visibility', (f) => { f.compiledShape[1].sectionsByColumn[0][0].visible = true; }],
+ ['section showLabel', (f) => { f.compiledShape[1].sectionsByColumn[0][1].showLabel = true; }],
+ ['compiled field state', (f) => { f.placements.find((p) => p.field === 'cnt_reviewer').readOnly = false; }],
+ ['compiled hidden field', (f) => { f.placements.find((p) => p.field === 'cnt_notes').hidden = false; }],
+ ]) {
+ const drift = structuredClone(facts);
+ mutate(drift.ui.forms.find((f) => f.name === 'Work Item'));
+ const result = score(state, drift, fixture);
+ assert.strictEqual(result.status, 'fail', name);
+ assert.match(result.reason, /Work Item/);
+ }
+ const wrongWidth = structuredClone(facts);
+ wrongWidth.ui.forms.find((f) => f.name === 'Work Item').compiledShape[1].declaredWidths[0] = '100%';
+ assert.strictEqual(score(topology, wrongWidth, fixture).status, 'fail', 'omitted authored widths still require the independent equal split');
+});
+
+test('page round-trip facts preserve own names and models through the real download helpers and hydrator', async () => {
+ const fixture = fixtureFor(8);
+ const facts = await stageFacts(fixture.spec, { fixture });
+ assert.strictEqual(facts.roundTrip.source, 'pac-download-fixture', 'read committed PAC files, not a compiler-generated page');
+ const text = 'round-trip: generative pages preserve their names and models';
+ assert.strictEqual(score(text, facts, fixture).status, 'pass');
+ const page = (f, key) => f.roundTrip.pageMetadata.find((p) => p.key === key);
+ assert.strictEqual(page(facts, 'revenue').name, 'Revenue "FY"');
+ assert.strictEqual(page(facts, 'revenue').model, 'gpt-4.1');
+ assert.deepStrictEqual(page(facts, 'revenue').dataSources, ['cnt_order']);
+ assert.strictEqual(page(facts, 'help').model, null);
+ assert.strictEqual(page(facts, 'archive').model, null);
+ assert.deepStrictEqual(facts.roundTrip.origSubareaTargets, facts.roundTrip.hydratedSubareaTargets);
+
+ for (const [name, key, field, value] of [
+ ['lost name', 'revenue', 'name', undefined],
+ ['navigation title used as name', 'revenue', 'name', 'Revenue Navigation'],
+ ['escaping accumulates', 'revenue', 'name', 'Revenue \\"FY\\"'],
+ ['model emptied', 'revenue', 'model', ''],
+ ['model dropped', 'revenue', 'model', null],
+ ['absent model invented', 'help', 'model', 'gpt-4.1'],
+ ['invalid model retained', 'archive', 'model', 'model with spaces'],
+ ]) {
+ const changed = structuredClone(facts);
+ page(changed, key)[field] = value;
+ const result = score(text, changed, fixture);
+ assert.strictEqual(result.status, 'fail', name);
+ assert.match(result.reason, new RegExp(`${key}.*${field}`));
+ }
+
+ const { hydrateSpec } = require('../../../../plugins/model-apps/scripts/lib/hydrate-spec.js');
+ for (const field of ['name', 'model']) {
+ const changed = await stageFacts(fixture.spec, { fixture, hydrator: async (reader) => {
+ const hydrated = await hydrateSpec(reader);
+ delete hydrated.pages.find((p) => p.key === 'revenue')[field];
+ return hydrated;
+ } });
+ assert.strictEqual(score(text, changed, fixture).status, 'fail', `a broken hydrate dropping ${field} cannot score green`);
+ }
+});
+
+test('invalid downloaded page models are dropped with discriminating loss diagnostics', async () => {
+ const fixture = fixtureFor(8);
+ const facts = await stageFacts(fixture.spec, { fixture });
+ const text = 'round-trip: invalid downloaded models are omitted with explicit diagnostics';
+ assert.strictEqual(score(text, facts, fixture).status, 'pass');
+ assert.deepStrictEqual(facts.roundTrip.unkeptModels, [
+ { pageId: '00000000-0000-0000-0000-000000000803', model: 'model with spaces' },
+ ]);
+ const missingWarning = structuredClone(facts);
+ missingWarning.roundTrip.unkeptModels = [];
+ assert.strictEqual(score(text, missingWarning, fixture).status, 'fail', 'silent model loss is not a successful round trip');
+ const retained = structuredClone(facts);
+ retained.roundTrip.pageMetadata.find((p) => p.key === 'archive').model = 'model with spaces';
+ assert.strictEqual(score(text, retained, fixture).status, 'fail', 'a diagnostic does not excuse retaining invalid metadata');
+ const unreadable = structuredClone(facts);
+ unreadable.roundTrip.unreadableConfigs = [{ pageId: '00000000-0000-0000-0000-000000000801', reason: 'invalid JSON' }];
+ assert.strictEqual(score(text, unreadable, fixture).status, 'fail', 'unknown bindings must not look like an absent model');
+});
+
+test('changed-only facts use real hashes snapshots and classifications and reject wrong verdicts', async () => {
+ const fixture = fixtureFor(9);
+ const facts = await stageFacts(fixture.spec, { fixture });
+ assert.ok(facts.changedOnly, 'the real changed-only decision core is exercised');
+ const text = 'changed-only: page bytes use a page-only fast path data-model edits use full and identical inputs are noop';
+ assert.strictEqual(score(text, facts, fixture).status, 'pass');
+ assert.strictEqual(facts.changedOnly.snapshot.eligible, true);
+ assert.strictEqual(facts.changedOnly.baselineVerified, true);
+ assert.ok(facts.verify.checks.some((c) => c.kind === 'page' && c.present), 'implemented pages must also be verified');
+ assert.ok(facts.verify.requiredChecks.page > 0);
+ const cases = facts.changedOnly.cases;
+ assert.deepStrictEqual(cases.map((c) => [c.name, c.verdict]), [
+ ['page-only', 'fast'], ['column-edit', 'full'], ['identical', 'noop'],
+ ]);
+ const hashes = facts.changedOnly.contentHashes;
+ for (const row of hashes) {
+ assert.match(row.before, /^[0-9a-f]{64}$/);
+ assert.match(row.after, /^[0-9a-f]{64}$/);
+ assert.strictEqual(row.before !== row.after, row.key === 'overview', 'only overview bytes differ');
+ }
+ assert.deepStrictEqual(cases[0].fastChanges.map((c) => [c.shape, c.phase, c.identity]), [['page', 'pages', 'overview']]);
+ assert.match(cases[1].fullReasons[0], /data-model: changed/);
+
+ for (const [index, wrong] of [[0, 'noop'], [0, 'full'], [1, 'fast'], [1, 'noop'], [2, 'fast'], [2, 'full']]) {
+ const changed = structuredClone(facts);
+ changed.changedOnly.cases[index].verdict = wrong;
+ const result = score(text, changed, fixture);
+ assert.strictEqual(result.status, 'fail', `${cases[index].name} cannot report ${wrong}`);
+ assert.match(result.reason, /verdict/);
+ }
+ for (const [name, mutate, reason] of [
+ ['wrong page identity', (c) => { c.cases[0].fastChanges[0].identity = 'detail'; }, /page-only.*fast changes/],
+ ['extra page upload', (c) => { c.cases[0].fastChanges.push({ shape: 'page', phase: 'pages', identity: 'detail' }); }, /page-only.*fast changes/],
+ ['wrong phase', (c) => { c.cases[0].changedPhases = ['forms']; }, /page-only.*phases/],
+ ['wrong full reason', (c) => { c.cases[1].fullReasons = ['pages changed']; }, /column-edit.*reason/],
+ ['missing case', (c) => { c.cases.pop(); }, /case/],
+ ['ineligible snapshot', (c) => { c.snapshot.eligible = false; }, /snapshot/],
+ ['unverified baseline', (c) => { c.baselineVerified = false; }, /baseline/],
+ ['unexpected debt', (c) => { c.cases[1].debt = [{ artifactType: 'entity', identity: 'cnt_order', reason: 'unexpected debt' }]; }, /debt/],
+ ]) {
+ const changed = structuredClone(facts);
+ mutate(changed.changedOnly);
+ const result = score(text, changed, fixture);
+ assert.strictEqual(result.status, 'fail', name);
+ assert.match(result.reason, reason);
+ }
+});
+
+test('artifact names are per-table and page quote warnings remain visible', async () => {
+ const fixture = fixtureFor(10);
+ const facts = await stageFacts(fixture.spec, { fixture });
+ const names = 'author: artifact-name warnings use per-table and form-type scope';
+ const quotes = 'author: page quote warnings remain visible without rewriting approved names';
+ assert.strictEqual(facts.author.validate.ok, true, JSON.stringify(facts.author.validate.errors));
+ assert.deepStrictEqual(facts.author.lint.errors, []);
+ assert.strictEqual(score(names, facts, fixture).status, 'pass');
+ assert.strictEqual(score(quotes, facts, fixture).status, 'pass');
+ assert.deepStrictEqual(facts.author.artifactNameCollisions, [], 'shared names on different tables are not collisions');
+ assert.deepStrictEqual(facts.author.pageNames.map((p) => p.name), fixture.spec.pages.map((p) => p.name));
+ const quoteWarnings = facts.author.lint.warnings.filter((w) => w.includes('ASCII double quote'));
+ assert.strictEqual(quoteWarnings.length, 1);
+ assert.match(quoteWarnings[0], /Revenue "FY"/);
+ assert.ok(!quoteWarnings.some((w) => w.includes("Clerk's Queue") || w.includes('Revenue \u201cFY\u201d')));
+ assert.ok(facts.author.lint.warnings.some((w) => !w.includes('ASCII double quote')), 'other legitimate warnings remain non-fatal');
+
+ for (const [collection, kind] of [['forms', 'form'], ['views', 'view'], ['charts', 'chart']]) {
+ const changed = structuredClone(fixture);
+ changed.spec[collection].push(structuredClone(changed.spec[collection][0]));
+ const duplicate = await stageFacts(changed.spec, { fixture: changed });
+ assert.ok(duplicate.author.lint.warnings.some((w) => w.startsWith(`Duplicate ${kind} name on cnt_order:`)), `${kind}: same-table duplicate is flagged by the real linter`);
+ const result = score(names, duplicate, changed);
+ assert.strictEqual(result.status, 'fail', `${kind}: a same-table duplicate cannot pass the fixture contract`);
+ assert.match(result.reason, /same-table duplicate.*cnt_order/);
+ }
+
+ const otherType = structuredClone(fixture);
+ otherType.spec.forms.push({ ...otherType.spec.forms[0], formType: 'QuickView' });
+ const typeScoped = await stageFacts(otherType.spec, { fixture: otherType });
+ assert.strictEqual(score(names, typeScoped, otherType).status, 'pass', 'Main and QuickView names have separate identities');
+ assert.ok(typeScoped.author.lint.warnings.some((w) => /QuickView.*isn't placed/.test(w)), 'an unrelated advisory does not become a blanket failure');
+
+ const globalCollision = structuredClone(facts);
+ globalCollision.author.lint.warnings.push('Duplicate form name on cnt_ticket: Information');
+ assert.strictEqual(score(names, globalCollision, fixture).status, 'fail', 'a globally scoped duplicate warning is a false positive');
+ const missingQuote = structuredClone(facts);
+ missingQuote.author.lint.warnings = missingQuote.author.lint.warnings.filter((w) => !w.includes('ASCII double quote'));
+ assert.strictEqual(score(quotes, missingQuote, fixture).status, 'fail', 'quote warnings must not silently disappear');
+ for (const key of ['apostrophe', 'typographic']) {
+ const changed = structuredClone(facts);
+ const name = fixture.spec.pages.find((p) => p.key === key).name;
+ changed.author.lint.warnings.push(`Page '${name}': pac stores each ASCII double quote`);
+ assert.strictEqual(score(quotes, changed, fixture).status, 'fail', `${key} is not an ASCII-quote warning`);
+ }
+ const rewritten = structuredClone(facts);
+ rewritten.author.pageNames.find((p) => p.key === 'straight-quote').name = 'Revenue FY';
+ assert.strictEqual(score(quotes, rewritten, fixture).status, 'fail', 'the approved name must not be silently sanitized');
+
+ const runner = path.join(__dirname, '..', 'run-app-builder.js');
+ const shown = spawnSync(process.execPath, [runner, '--eval', '10'], { encoding: 'utf8' });
+ assert.strictEqual(shown.status, 0, shown.stdout + shown.stderr);
+ assert.match(shown.stdout, /# lint warning:.*ASCII double quote/, 'the warning is visible in green TAP output');
+ const lintPath = path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', 'lib', 'spec-lint.js');
+ const lost = spawnSync(process.execPath, ['-e', `
+ const lint = require(${JSON.stringify(lintPath)});
+ const realLint = lint.lintAppSpec;
+ lint.lintAppSpec = (spec) => {
+ const result = realLint(spec);
+ return { ...result, warnings: result.warnings.filter((w) => !w.includes('ASCII double quote')) };
+ };
+ process.argv = [process.execPath, ${JSON.stringify(runner)}, '--eval', '10'];
+ require(${JSON.stringify(runner)}).main();
+ `], { encoding: 'utf8' });
+ assert.strictEqual(lost.status, 1, lost.stdout + lost.stderr);
+ assert.match(lost.stdout, /not ok \d+ - author: page quote warnings/);
+
+ const sanitized = spawnSync(process.execPath, ['-e', `
+ const lint = require(${JSON.stringify(lintPath)});
+ const realLint = lint.lintAppSpec;
+ lint.lintAppSpec = (spec) => {
+ for (const page of spec.pages || []) page.name = page.name.replace(/"/g, '');
+ return realLint(spec);
+ };
+ process.argv = [process.execPath, ${JSON.stringify(runner)}, '--eval', '10'];
+ require(${JSON.stringify(runner)}).main();
+ `], { encoding: 'utf8' });
+ assert.strictEqual(sanitized.status, 1, 'an input-mutating linter cannot rewrite its own approved-name expectation:\n' + sanitized.stdout + sanitized.stderr);
+ assert.match(sanitized.stdout, /approved page names were rewritten/);
+});
+
+test('evidence loading rejects malformed form records and out-of-fixture XML paths by fixture name', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ab-evidence-'));
+ const dir = path.join(root, '6-form-evidence');
+ try {
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify(require('../fixtures/6-form-layout/app-spec.json')));
+ fs.writeFileSync(path.join(dir, 'inside.xml'), '<form/>');
+ fs.writeFileSync(path.join(root, 'outside.xml'), '<form/>');
+ const form = { id: '00000000-0000-0000-0000-000000000601', entity: 'new_workitem', name: 'Work Item', xmlFile: 'inside.xml' };
+ const write = (body) => fs.writeFileSync(path.join(dir, 'evidence.json'), JSON.stringify(body));
+ write({ formReconcile: { forms: [form] } });
+ assert.strictEqual(loadFixtures(root)[0].evidence.formReconcile.forms[0].xml, '<form/>');
+ for (const body of [
+ { formReconcile: 'not an object' },
+ { formReconcile: { forms: 'not an array' } },
+ { formReconcile: { forms: [null] } },
+ ]) {
+ write(body);
+ assert.throws(() => loadFixtures(root), /Fixture 6-form-evidence:.*formReconcile/);
+ }
+ write({ formReconcile: { forms: [{ ...form, xmlFile: path.join('..', 'outside.xml') }] } });
+ assert.throws(() => loadFixtures(root), /Fixture 6-form-evidence:.*outside the fixture/);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('evidence XML remains confined when the fixtures root is accessed through a junction or symlink', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ab-evidence-link-'));
+ const corpus = path.join(root, 'corpus');
+ const dir = path.join(corpus, '6-linked-evidence');
+ const alias = path.join(root, 'alias');
+ try {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify(require('../fixtures/6-form-layout/app-spec.json')));
+ fs.writeFileSync(path.join(dir, 'inside.xml'), '<form/>');
+ const form = { id: '00000000-0000-0000-0000-000000000601', entity: 'new_workitem', name: 'Work Item', xmlFile: 'inside.xml' };
+ fs.writeFileSync(path.join(dir, 'evidence.json'), JSON.stringify({ formReconcile: { forms: [form] } }));
+ fs.symlinkSync(corpus, alias, 'junction');
+ assert.strictEqual(loadFixtures(alias)[0].evidence.formReconcile.forms[0].xml, '<form/>');
+ fs.writeFileSync(path.join(corpus, 'outside.xml'), '<form/>');
+ fs.writeFileSync(path.join(dir, 'evidence.json'), JSON.stringify({ formReconcile: { forms: [{ ...form, xmlFile: path.join('..', 'outside.xml') }] } }));
+ assert.throws(() => loadFixtures(alias), /Fixture 6-linked-evidence:.*outside the fixture/);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('the app-builder fixture roster and required assertion texts match the registry', () => {
+ const fixtures = loadFixtures(path.join(__dirname, '..', 'fixtures'));
+ const check = (inputs, manifest) => {
+ assert.deepStrictEqual(inputs.map((f) => f.id).sort((a, b) => a - b), manifest.evals.map((e) => e.id).sort((a, b) => a - b), 'fixture ids match the manifest');
+ for (const ev of manifest.evals) for (const text of [...manifest.common_stage_assertions, ...(ev.expectations || [])]) {
+ assert.ok(ASSERTIONS.has(text), `unregistered assertion for eval ${ev.id}: ${text}`);
+ }
+ };
+ check(fixtures, evalsManifest);
+ assert.throws(() => check(fixtures.slice(1), evalsManifest), /fixture ids/);
+ const typo = structuredClone(evalsManifest);
+ typo.evals.find((e) => e.id === 7).expectations.push('verify: an unregistered required assertion');
+ assert.throws(() => check(fixtures, typo), /unregistered assertion/);
});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.md
index 78d48353b..e48278bb4 100644
--- a/evals/model-apps/genpage/EVAL_GUIDE.md
+++ b/evals/model-apps/genpage/EVAL_GUIDE.md
@@ -12,7 +12,7 @@ Comprehensive guide to the `/genpage` evaluation suite. **What evals exist, how
6. [Fixture types (synthetic vs real captures)](#fixture-types)
7. [Running the suite](#running-the-suite)
8. [Cadence — when to run](#cadence)
-9. [Quick start — running one eval end-to-end](#quick-start)
+9. [Quick start — manual capture and offline replay](#quick-start)
10. [Reading runner output (TAP)](#reading-runner-output)
11. [Manual grep patterns (Layer 2 fallback)](#manual-grep-patterns)
12. [Pass / fail summary](#pass-fail-summary)
@@ -20,7 +20,7 @@ Comprehensive guide to the `/genpage` evaluation suite. **What evals exist, how
14. [Capturing real fixtures from `/genpage`](#capturing-real-fixtures)
15. [Adding a new eval](#adding-a-new-eval)
16. [Adding a new assertion](#adding-a-new-assertion)
-17. [Known-red fixtures and why they're allowed](#known-red-fixtures)
+17. [Expected refusals and corpus gating](#expected-refusals-and-corpus-gating)
---
@@ -42,7 +42,7 @@ Comprehensive guide to the `/genpage` evaluation suite. **What evals exist, how
## What we evaluate
-`/genpage` is a multi-phase skill: orchestrator → planner → optional entity-builder → page-builder(s) → deploy → optional verify. Each phase has rules (auth must precede entity creation, plans must follow a schema, generated code must follow rules.md, etc.). The eval suite checks that the agent honors those rules end-to-end.
+`/genpage` is a multi-phase skill: orchestrator → planner → optional entity-builder → page-builder(s) → deploy → optional verify. Each phase has rules (auth must precede entity creation, plans must follow a schema, generated code must follow rules.md, etc.). These runners **replay stored artifacts** against selected contracts; they do not launch agents, answer questions, run logged commands, or deploy anything. A green replay is not end-to-end evidence of current agent or platform behavior.
Three kinds of failure we want to catch:
@@ -60,18 +60,20 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
### Layer 1 — Workflow assertions
-**Input:** `workflow-log.md`, `genpage-plan.md`, optionally `genpage-edit-plan.md` and `entity-creation-log.md`.
+**Input:** `workflow-log.md`, `genpage-plan.md`, optionally `genpage-edit-plan.md` and `genpage-entity-creation-log.md` (legacy `entity-creation-log.md` remains supported). Current synthetic fixtures also supply `fixture.json`, ordered `tool-results.json` and the declared JSON/text/source snapshots.
**What it checks:**
-- Prereq commands ran (`node --version`, `pac help` with version ≥ 2.7.0)
+- Prereq commands are recorded (`node --version`, `pac help` with version **> 2.10.0**)
- `pac auth list` ran and the active env was reported
- `AskUserQuestion` was used (or new-page intent was inferable from a `## Pages` section in the plan)
- Plan was presented via `EnterPlanMode` and approved
-- Plan conforms to `references/plan-schema.md` (all required `##` headings)
+- Plan conforms to `references/plan-schema.md` (required headings, safe targets and matching Pages-table/per-page File values)
- `## Environment` contains `Solution:` and `Publisher Prefix:` lines
- Solution-selection question runs when (and only when) metadata work is needed
-- `check-auth.js` runs before `entity-builder` when entities need creating
-- `pac model genpage upload` invocations include `--prompt` with correct scoping
+- Auth results belong to their commands; the latest successful applicable gate precedes mutations, final failures halt, and timeout retry/advice is bounded
+- Failed connection discovery is not an empty success and cannot authorize setup
+- Current upload commands use `genpage-upload.js` with file transport; the preservation fixture compares exact approved/forwarded text and before/after name, model and binding sets
+- Custom API discovery/gates/bindings/runtime/update stages agree; optional packaging names every deployed page and preserves failures/read-back evidence
- Prefix discipline holds across plan, entity-creation log, and resolved names
**Runner:** `evals/model-apps/genpage/run-layer-1.js`
@@ -79,25 +81,27 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
### Layer 2 — Code-quality assertions
-**Input:** every `.tsx` file in the fixture (excluding `RuntimeTypes.ts`).
+**Input:** every top-level `.tsx` file in the fixture (excluding `RuntimeTypes.ts`), plus declared before/after source and lifecycle evidence where applicable.
**What it checks** (against `common_code_assertions` in `evals.json`):
- Single file with `export default GeneratedComponent`
- `pageInput` is destructured from props (even on mock pages)
- Either `./RuntimeTypes` import (Dataverse) or realistic inline mock data
-- `makeStyles` + `tokens` (no inline styles for static values)
+- `makeStyles` presence (the existing heuristic does not prove tokens or prohibit every inline style)
- **No** `100vh` / `100vw` / `createTheme` / `mergeThemes` / `useTheme` / `<FluentProvider>`
- **No** `window.location` / `react-router` / raw `pagetype=` URLs
- `Xrm.Navigation.navigateTo` (or `xrm?.Navigation?.navigateTo` via a typed `(window as any).Xrm` alias) for in-app nav
- Unsized Fluent icons only (e.g., `AddRegular`, not `Add24Regular`)
- Every icon name in `@fluentui/react-icons` imports appears in `references/verified-icons.txt`
-- `try`/`catch` around `await dataApi.*` (Dataverse pages)
+- A `try`/`catch` marker for Dataverse awaits (not proof that every await is enclosed)
- No `TODO`/`FIXME`/`...` placeholders
- Lookup fields use `@OData.Community.Display.V1.FormattedValue` annotations
- `<DataGrid>` usage imports `createTableColumn` + configures `columnSizingOptions` or `resizableColumns`
-- Multi-page builds use quoted `"PAGEREF_<filename>"` placeholders for cross-page nav
+- Every effective navigation target is checked with the production resolver; current before/after snapshots must differ by exact substitutions only, and only affected pages reupload
+- The production `pageStructureProblems` gate rejects truncated modules, including unfinished statements after valid exports
+- The Custom API lifecycle grades actual saved TSX, method/parameter/bound-record parity, sanitized result handling and preservation versus explicit clear
-Plus per-eval `expectations` whose text starts with `Phase 5` (page-builder-specific).
+Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The registered Phase-5b column checker now executes; its existing `column-name verification requires RuntimeTypes.ts fixture` SKIP is explicit, not silently excluded by routing. Column/schema verification itself remains unimplemented. Other unregistered/AST-dependent expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.
**Runner:** `evals/model-apps/genpage/run-layer-2.js`
**Library:** `lib/assertions-layer-2.js`
@@ -126,11 +130,58 @@ Plus per-eval `expectations` whose text starts with `Phase 5` (page-builder-spec
All eval definitions live in `evals.json` alongside this file. The file contains:
-- `common_workflow_assertions`: 15 workflow checks every run must pass (prereqs, auth, solution selection gating, check-auth pre-flight, plan creation, workflow log, `--prompt` scoping, prefix discipline at plan-format / resolved-names / solution-alignment).
-- `common_code_assertions`: 18 code-quality checks the generated `.tsx` must pass (Fluent UI V9 only, no forbidden patterns, etc.).
-- `evals`: 16 test cases — each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.
+- `common_workflow_assertions`: **19** registered workflow checks, each passed or explicitly skipped when inapplicable.
+- `common_code_assertions`: **21** registered code checks.
+- `evals`: **25** prompt definitions, each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.
+
+The `data` field specifies scenario assumptions for a manual capture or constructed fixture. The offline harness does not provide responses to `AskUserQuestion` or verify every recorded answer. The corpus contains **20 fixture directories / 26 top-level TSX files**, representing 18 prompt IDs. IDs **3, 6, 8, 9, 12, 14, 16** have no fixture and are not executed.
+
+### Enumerating registered and unmatched checks
+
+The assertion modules export four iterable Maps: Layer 1's `WORKFLOW_ASSERTIONS` and
+`PHASE_EXPECTATIONS`, and Layer 2's `ASSERTIONS` and `PHASE5_EXPECTATIONS`. Iterate their
+entries to inventory every registered text and callback. Use the matching common Map
+for `common_workflow_assertions` / `common_code_assertions`.
+
+For **per-eval expectations**, both runner modules export `getExpectationCheck(text)`,
+returning the actual routed callback or `undefined`. They also export their predicates:
+Layer 1 `isPhaseExpectation(text)` and Layer 2 `isPhase5Expectation(text)`. The scoring
+loops use these same functions. A cross-runner contract test can list unmatched entries
+without reimplementing the routing expressions (paths below are relative to this directory):
+
+```javascript
+const data = require('./evals.json');
+const workflow = require('./run-layer-1.js');
+const code = require('./run-layer-2.js');
+const unmatched = data.evals.flatMap(({ id, expectations }) =>
+ expectations
+ .filter((text) => !workflow.getExpectationCheck(text) && !code.getExpectationCheck(text))
+ .map((text) => ({ id, text }))
+);
+```
+
+A matched callback can still intentionally return SKIP; matching is not proof of an
+implemented oracle. The Phase-5b routing test also injects a failing result at the real
+registry entry and requires runner exit 1, proving the callback executes.
+
+### The coverage contract
+
+`evals/model-apps/tests/eval-coverage-contract.test.js` (run by CI with the other eval unit
+tests) grades through each runner's exported `gradeFixture`, so it sees exactly what the runners
+report, and fails when:
+
+- a prompt has no fixture and no recorded reason, or a fixture has no prompt;
+- an expectation is routed by neither runner (it would be dropped without even a SKIP), or a
+ common assertion has no check;
+- an expectation has no check and is not recorded as `deferred` (an offline check could grade
+ it) or `manual` (a person judges the generated page);
+- a registered check returns SKIP on every fixture it runs on and is not recorded with its reason;
+- the counts and missing prompt IDs this guide and `fixtures/README.md` state disagree with the
+ registries, or the loader's entity-log name differs from the one the skill writes.
-The `data` field specifies the user answers and environment state the eval assumes. During manual eval runs, the human grader role-plays this data. During automated runs, the eval harness provides these responses to `AskUserQuestion`.
+Today's gaps are recorded in `evals/model-apps/tests/eval-coverage-baseline.json`. Every list in
+it is a ratchet: when you capture a missing prompt, add a check or make a placeholder grade, the
+contract fails until you remove the entry, so the baseline only shrinks.
---
@@ -140,8 +191,8 @@ Each eval in `evals.json` has a `tier` field for selective execution.
| Tier | Count | When to run | Eval IDs |
|------|------|-------------|----------|
-| `smoke` | 4 | **Every PR** that touches the skill, agents, rules, or evals | 1, 2, 3, 16 |
-| `full` | 9 | Nightly or pre-release; covers core workflows | 4, 5, 6, 7, 8, 9, 11, 13, 15 |
+| `smoke` | 5 | **Every PR** that touches the skill, agents, rules, or evals | 1, 2, 3, 16, 17 |
+| `full` | 17 | Nightly or pre-release; covers core workflows | 4, 5, 6, 7, 8, 9, 11, 13, 15, 18–25 |
| `stress` | 3 | With full suite; edge cases (auth blockers, plan revisions, filename collisions) | 10, 12, 14 |
**Recommended cadence:**
@@ -165,7 +216,7 @@ A fixture is a folder under `fixtures/<eval-id>-<slug>/` containing the artifact
### Synthetic fixtures
-Hand-built v2.x-compliant artifacts. Built from samples + hand-crafted workflow-log + plan. They serve as **green-path regression tests** — if a runner change accidentally rejects a known-good fixture, we know the change is wrong.
+Hand-built artifacts for specific contracts, not captured agent runs. The seven current additions declare `provenance: "synthetic"`, `contractVersion: 2` and the public skill/reference sections they exercise. They serve as deterministic positive/rejection/recovery controls. Historical synthetics retain their compatibility contract rather than being advertised as current compliant output.
Pros: deterministic, fast to build, no Dataverse dependency, fully under our control.
Cons: can't catch agent drift (the synthetic fixture is what we *want* the agent to produce, not what it *does*).
@@ -184,18 +235,48 @@ The suite ships both kinds:
| Eval | Synthetic fixture | Real capture |
|-----:|-------------------|---------------|
| 1 | `1-account-card-gallery` | — |
-| 2 | `2-mock-dashboard` | `2-mock-dashboard-real` (pre-v2.2-spec — see [known-red](#known-red-fixtures)) |
+| 2 | `2-mock-dashboard` | `2-mock-dashboard-real` (historical compatibility replay) |
| 4 | `4-case-wizard` | — |
-| 5 | — | `5-kanban-task-board` (pre-v2.2-spec — see [known-red](#known-red-fixtures)) |
+| 5 | — | `5-kanban-task-board` (historical compatibility replay) |
| 7 | `7-job-candidates-new-entities` | — |
-| 11 | `11-recruitment-multi-page` | `11-recruitment-pages-real` (v2.2-spec, ✓ green) |
+| 11 | `11-recruitment-multi-page` (historical) | `11-recruitment-pages-real` (historical, green) |
| 13 | `13-contact-localization` | — |
-| 15 | — | `15-support-tickets-real` (v2.2-spec, ✓ green) |
+| 15 | — | `15-support-tickets-real` (historical, green) |
+| 17 | `17-weather-mock-data` (historical) | — |
+| 18 | `18-sharepoint-connectors` (historical) | — |
+| 19 | `19-add-weather-connector` (historical edit) | — |
+| 10 | `10-auth-timeout-halt` (current refusal) | — |
+| 20 | `20-upload-preservation` (current create/edit/refusal) | — |
+| 21 | `21-discovery-failure` (current refusal) | — |
+| 22 | `22-navigation-contract` (current before/after) | — |
+| 23 | `23-worker-completeness` (current rejection/recovery) | — |
+| 24 | `24-custom-api-lifecycle` (current create/preserve/clear) | — |
+| 25 | `25-solution-package` (current packaging/refusal) | — |
The mix gives:
- A **green baseline** to catch runner regressions (synthetics)
- **Drift detection** against real agent output (real captures)
-- **Proof of life** that the current spec produces green captures (the two v2.2-spec captures)
+- **Compatibility evidence**, not proof that the current skill produces current-compliant captures
+
+---
+
+### Versioned evidence and discrimination
+
+`fixtures/contracts.json` explicitly labels the 13 existing directories as historical contract 1, without rewriting captured content. Raw PAC transport, legacy navigation spelling and missing transport/read-back artifacts are **not** certified as current compliant. Contract 2 uses a per-directory `fixture.json` and `tool-results.json`: one ordered record per command with its own result, plus `artifacts` listing the exact files to load. Artifact paths must stay inside the fixture and be plain files.
+
+The seven new fixtures exercise these current contracts:
+
+| Fixture | Evidence/check | Negative control in scorer tests |
+|---------|----------------|----------------------------------|
+| `10-auth-timeout-halt` | One timeout retry, original advice, no provisioning/upload | Failed auth followed by unrelated `ok:true`; malformed result or wrong environment |
+| `20-upload-preservation` | Wrapper/name/prompt/message files; separate own-name/config snapshots | Inline/rewritten approved text; dropped name/model/bindings; hidden shim/read warnings |
+| `21-discovery-failure` | Unreadable discovery returns `needs_input`, no setup | Failed discovery followed by connection/reference creation or upload |
+| `22-navigation-contract` | Actual before/after TSX and deployed ID map | Unknown/optional-call non-GUID target, runtime override, collateral edit or extra reupload |
+| `23-worker-completeness` | Failed production gate, fresh regeneration, then upload | Valid export plus unfinished statement, stale/missing write or upload before acceptance |
+| `24-custom-api-lifecycle` | Discovery, re-probe, bare actions, runtime and config stages | Disabled/unreadable gate, invented kind/name/parameter, wrong method/bound record, unsafe response or lost bindings |
+| `25-solution-package` | Explicit page IDs, dynamic types, app-first writes and read-back | Omitted page/wrong solution/type/order; invalid ID writes; partial failure reported as success |
+
+Expected refusals are green **only when the recorded refusal contract is satisfied**. Fixtures 10 and 21 legitimately contain no generated TSX; Layer 2 grades their failed gate and absence of generation/mutations rather than manufacturing a page. Fixture 23's rejected snapshot is nested evidence; the top-level page is the accepted regeneration. Expected-failure mutations live in unit tests, never unexplained red corpus directories.
---
@@ -216,14 +297,14 @@ Exit codes:
### Filter by tier
```bash
-node run-layer-1.js --tier smoke # 4 smoke evals
-node run-layer-1.js --tier full # 9 full evals
-node run-layer-1.js --tier stress # 3 stress evals
+node run-layer-1.js --tier smoke # 4 stored fixtures, 5 prompt definitions
+node run-layer-1.js --tier full # 15 stored fixtures, 17 prompt definitions
+node run-layer-1.js --tier stress # 1 stored fixture (id 10), 3 prompt definitions
```
-A tier runs the fixtures that exist for its evals. The committed fixtures cover only some evals (none
-of the stress ones), so a tier with no captured fixture reports `no fixtures matched the filter` and
-exits 2; point `--fixtures <dir>` at your own captures to run it.
+A tier runs only existing fixtures, not every prompt definition. An empty selection reports
+`no fixtures matched the filter` and exits 2. The stress tier now replays the synthetic auth-timeout
+refusal; plan-revision and filename-collision prompts still have no fixture.
### Filter by eval id (debugging)
@@ -257,13 +338,13 @@ For raw counts:
node run-layer-1.js 2>&1 | tail -6
```
-Prints:
+Example summary (counts come from the selected stored corpus):
```
-# tests 261
-# pass 124
-# fail 10
-# skip 127
-# fixtures 10 (pass 8, fail 2)
+# tests 530
+# pass 267
+# fail 0
+# skip 263
+# fixtures 20 (pass 20, fail 0)
```
---
@@ -297,31 +378,31 @@ Example using eval id 1 (account gallery) — manual fixture capture if you don'
## Reading runner output
-The runners emit TAP v13. Each fixture is a subtest; each assertion is one `ok` / `not ok` line.
+The runners emit TAP v13. Each fixture is a subtest; each assertion is one `ok` / `not ok` line. The following is illustrative failure output, not the current corpus result.
```
TAP version 13
-1..10
+1..2
# Subtest: 1-account-card-gallery
ok 1 - Generated .tsx is a single file with `export default GeneratedComponent`
ok 2 - Generated .tsx destructures props including `pageInput`
ok 3 - Generated .tsx imports types from `./RuntimeTypes` ...
...
- 1..18
+ 1..21
ok 1 - 1-account-card-gallery
# Subtest: 11-recruitment-pages-real
...
- not ok 17 - For Dataverse list/detail pages, the inline IIFE + window cache pattern is used
+ not ok 18 - For Dataverse list/detail pages, the inline IIFE + window cache pattern is used
---
reason: "candidate-list.tsx: missing window cache or uses useCallback for fetch"
...
-ok 2 - 11-recruitment-pages-real
+not ok 2 - 11-recruitment-pages-real
...
-# tests 187
-# pass 98
-# fail 6
-# skip 92
-# fixtures 7 (pass 6, fail 1)
+# tests 42
+# pass 39
+# fail 1
+# skip 2
+# fixtures 2 (pass 1, fail 1)
```
Read this output as:
@@ -369,11 +450,11 @@ For ad-hoc verification or assertions the Layer 2 runner currently skips, grep t
An eval run passes when:
-- **Layer 1:** 100% of workflow assertions pass
-- **Layer 2:** 100% of code assertions pass on every `.tsx`
+- **Layer 1:** no executed workflow assertion fails
+- **Layer 2:** no executed code/lifecycle assertion fails (or the declared source-free refusal is verified)
- **Layer 3:** average UX score ≥ 8.5, no page below 7
-An eval run fails if any layer's criteria isn't met. Skipped assertions never count as failures — they're either inapplicable to the fixture or pending AST-based implementation.
+An offline replay fails if any executed assertion fails. Skips are visible but do not fail the run: they can be inapplicable, manual/AST-dependent or unregistered. Green therefore does not imply complete prompt coverage, a TypeScript build, React execution, live upload/download, or a browser/UX result.
---
@@ -399,7 +480,7 @@ Use `scripts/capture-fixture.js`. The helper copies the right files (excluding l
### Steps
-1. **Run `/genpage` in a regular interactive Claude Code session.** Use the eval's exact prompt from `evals.json`. Answer each `AskUserQuestion` per the eval's `data.question_answers` (the runner emits these as the canonical answers).
+1. **Run `/genpage` manually with the plugin loaded.** Use the eval's prompt and role-play its `data.question_answers`; offline runners do not emit or supply those answers.
2. **After completion, run the capture script:**
@@ -410,15 +491,15 @@ Use `scripts/capture-fixture.js`. The helper copies the right files (excluding l
--slug <kebab-slug>
```
-3. **Inspect the JSON summary** the script prints. If `layer1.failures` and `layer2.failures` are both empty, the fixture is good to commit. If there are failures, decide:
+3. **Inspect the JSON summary** the script prints. Each layer reports its counts, the runner's `exitCode` and a `failures` list. If `layer1.failures` and `layer2.failures` are both empty, the fixture is good to commit. A runner that exits with an error but reports no failing assertion, or reports no assertions at all, is listed as a failure too: nothing was verified, even though the process itself exits 0. If there are failures, decide:
- **Real agent drift** → file an issue or tighten the spec (don't doctor the fixture)
- **Runner false positive** → relax the assertion regex to accept the functionally-equivalent alternative pattern
- - **Stale fixture from before a spec change** → mark as known-red with a fixture-local README (see `15-support-tickets-real/README.md` for the template)
+ - **Historical contract** → label/version the evidence and capture a new directory under a fresh slug, rather than rewriting an old transcript
### What the script copies (allowlist)
- `*.tsx` (each page produced)
-- `*.md` (workflow-log, genpage-plan, entity-creation-log, edit-plan)
+- `*.md` (workflow-log, genpage-plan, genpage-entity-creation-log, genpage-edit-plan)
- `RuntimeTypes.ts`
### What it skips (denylist)
@@ -436,6 +517,8 @@ Use `scripts/capture-fixture.js`. The helper copies the right files (excluding l
---
+Prefer a fresh slug for historical captures; do not use `--force` to make old evidence resemble today's workflow. The capture helper's allowlist does not collect the new JSON/text transport and lifecycle evidence. Constructed contract-2 fixtures explicitly package those snapshots and associated results themselves.
+
## Adding a new eval
When the skill grows a new capability (new sample pattern, new agent flow, etc.), add an eval to cover it.
@@ -508,7 +591,7 @@ When a new rule is added to `rules.md` or a new phase requirement lands in `SKIL
4. **Add unit tests** in `tests/assertions-layer-{1,2}.test.js` covering pass / fail / skip cases.
-5. **Update at least one fixture** to exercise the assertion. If existing fixtures naturally cover it, you're done; otherwise edit a synthetic fixture's `.tsx` or workflow-log to include the pattern.
+5. **Add a versioned synthetic fixture** for a new contract, or rely on existing evidence when it genuinely covers it. Do not alter captured directories. Include a positive control and a negative mutation proving the scorer rejects the precise regression.
6. **Run the full test + runner sweep:**
@@ -520,26 +603,14 @@ When a new rule is added to `rules.md` or a new phase requirement lands in `SKIL
---
-## Known-red fixtures
-
-A fixture can be **intentionally red** if:
-
-- It documents real agent drift (the runner is catching a legitimate violation)
-- It was captured before a spec change and predates the current rules
-- It serves as historical reference
-
-In all cases, the fixture must have a **`README.md` inside the fixture directory** documenting:
-- What's failing and why
-- Whether the failures are runner false-positives (would be fixed) or real-but-pre-spec drift (would be replaced)
-- When the fixture should be replaced
-
-Currently red:
-
-| Fixture | Why | Action |
-|---------|-----|--------|
-| `2-mock-dashboard-real/` | Pre-v2.2-spec workflow-log compactness + `void props;` instead of `pageInput` destructure | Re-capture under v2.2 spec to replace |
-| `5-kanban-task-board/` | Pre-v2.2-spec workflow-log compactness (Layer 2 is fully green; only Layer 1 affected) | Re-capture under v2.2 spec to replace |
+## Expected refusals and corpus gating
-Both will go green when their `/genpage` sessions are re-run after the v2.2 planner-spec tightening propagates. See each fixture's README for the specific failing assertions and remediation path.
+Currently red: **none**. Every fixture — synthetic and real capture alike — is green under both
+runners, and CI runs both runners on every PR that touches `evals/model-apps/**`
+(`.github/workflows/model-apps-script-tests.yml`, job `test-model-apps-evals`).
-**Aggregate state for CI gating:** A passing build is one where every **synthetic** fixture is green. Real captures may be red while documented; their failures count as known-signal, not regressions. (You can adjust this policy if you want CI to gate on real captures too — see the runner's `--eval` filter for narrowing.)
+**Aggregate state for CI gating:** every stored fixture must pass. Expected rejection is an explicit
+outcome with associated failed-gate/no-mutation evidence, not an excuse for a red fixture. Put bad
+inputs and ignored-failure mutations in scorer unit tests. Historical captures use their labelled
+compatibility contract; newer requirements need new evidence rather than rewritten history or a
+broader skip. CI green covers these replays and units, not unrepresented prompts or live behavior.
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index 594f44be9..d9281c640 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -15,8 +15,12 @@
"Phase 2a: When entities need creating, scripts/check-auth.js runs and returns ok:true before entity-builder is invoked (provision-entities.js, or legacy create-table.js/add-column.js/create-relationship.js/create-record.js); on ok:false the orchestrator surfaces the message to the user and halts",
"Phase 6 / 6.5 / 7.5 / Edit Phase 6 (--prompt scoping): The FIRST pac model genpage upload for each new page passes --prompt with the FULL page description (from plan's ## User Requirements). EVERY SUBSEQUENT upload of an existing page (--page-id, no --add-to-sitemap) passes --prompt scoped to ONLY the delta of changes in that upload — never the full original description",
"Prefix discipline — plan format: Every name in `## Entity Creation Required` (table headings, column Suffix values, choice column suffixes, relationship Lookup Suffix values) is a bare suffix matching `^[a-z][a-z0-9]+$`. No value contains an underscore or a prefix. The prefix lives only in `## Environment` → `Publisher Prefix:`.",
- "Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan's `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).",
- "Prefix discipline — solution alignment: If the env has a dominant non-system custom prefix (>=50% of custom tables AND >=3 such tables), the planner surfaces this in the solution question and ordered the option whose publisher prefix matches the dominant prefix FIRST as the recommended choice. If the user picks a different-prefix solution, the planner logged a one-line warning before proceeding."
+ "Prefix discipline — resolved names: For every operation in `genpage-entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan's `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).",
+ "Prefix discipline — solution alignment: If the env has a dominant non-system custom prefix (>=50% of custom tables AND >=3 such tables), the planner surfaces this in the solution question and ordered the option whose publisher prefix matches the dominant prefix FIRST as the recommended choice. If the user picks a different-prefix solution, the planner logged a one-line warning before proceeding.",
+ "Phase 2a: Every applicable auth result is associated with its command; only the latest successful gate authorizes mutations, and final failures halt with bounded retry and advice",
+ "Phase 1: Failed connector discovery returns needs_input and never creates a connection or reference",
+ "Phase 4.6: A populated Custom API plan never discovers, generates or uploads after a disabled or unreadable feature gate",
+ "Phase 6.7: Packaging uses every deployed page id, the approved solution and discovered component types; invalid identities refuse before writes and results agree with read-back"
],
"common_code_assertions": [
"Generated .tsx is a single file with `export default GeneratedComponent`",
@@ -38,7 +42,8 @@
"For Dataverse pages with fetching, separate setState calls inside async callbacks are batched into a single setData(...) call (Rule 14)",
"For Dataverse list/detail pages, the inline IIFE + window cache + cache-guard pattern from references/data-caching.md is used (Rule 15); no useCallback for data-fetching functions",
"For multi-page builds, cross-page navigation uses quoted `\"PAGEREF_<filename>\"` placeholders that the orchestrator's Phase 6.5 resolves to real GUIDs",
- "For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)"
+ "For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)",
+ "Generated .tsx passes the production completeness gate (complete module, JSX, brackets, strings, comments and no prose fences)"
],
"evals": [
{
@@ -215,7 +220,7 @@
"Phase 2b (Entity Builder): Lookup relationship (cr_candidate → cr_jobrequisition) is provisioned via input JSON; provision-entities.js handles propagation internally",
"Phase 2b (Entity Builder): User is asked about sample data via AskUserQuestion",
"Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js input JSON; parent references use $parent/match convention for dependency resolution",
- "Phase 2b (Entity Builder): Actual logical names are reported back (may be normalized by Dataverse); a transaction log at <working-dir>/entity-creation-log.md captures each successful operation",
+ "Phase 2b (Entity Builder): Actual logical names are reported back (may be normalized by Dataverse); a transaction log at <working-dir>/genpage-entity-creation-log.md captures each successful operation",
"Phase 4: pac model genpage generate-types is run with the created entity names",
"Phase 5 (Page Builder): Generated code uses ONLY verified column names from RuntimeTypes.ts",
"Phase 6: Upload includes --data-sources with both created entity names"
@@ -277,7 +282,7 @@
"new_or_edit": "Create new page(s)",
"data_source": "Dataverse entity: cr_widget (new, does not exist)"
},
- "environment_state": "az CLI is not logged in, OR logged in as a user without access to the target Dataverse env"
+ "environment_state": "az CLI is signed out, lacks Dataverse access, or times out; timeout retry is bounded to once and a final failure halts"
},
"expectations": [
"Phase 1 (Planner): cr_widget is identified as NOT existing (exact logical-name match, not fuzzy)",
@@ -286,7 +291,8 @@
"Phase 2a: If the script returns blocker:'az_not_logged_in', orchestrator surfaces the message ('Run `az login`...') to the user and halts (entity-builder is NOT invoked)",
"Phase 2a: If blocker:'whoami_403', orchestrator surfaces the message including the specific `az login --username <pacUser>` command and halts",
"Phase 2a: If ok:true but identitiesMatch:false, orchestrator proceeds but surfaces a one-line warning",
- "Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true"
+ "Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true",
+ "Phase 2a: Auth timeout retries once then halts before provisioning or upload"
]
},
{
@@ -410,7 +416,7 @@
"Phase 2b (Entity Builder): Priority picklist has 4 options starting at 100000000 (Low=100000000, Medium=100000001, High=100000002, Critical=100000003)",
"Phase 2b (Entity Builder): Status picklist has 4 options starting at 100000000",
"Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration",
- "Phase 2b (Entity Builder): Transaction log (entity-creation-log.md) records each create with its returned metadataId",
+ "Phase 2b (Entity Builder): Transaction log (genpage-entity-creation-log.md) records each create with its returned metadataId",
"Phase 4: pac model genpage generate-types picks up the enum registrations",
"Phase 5 (Page Builder): Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)",
"Phase 5 (Page Builder): Generated .tsx uses dataApi.getChoices() or reads FormattedValue annotations for choice display names"
@@ -505,6 +511,61 @@
"Edit Phase 5 (preservation): content the connector cannot supply is preserved per the edit plan's Preservation Constraints rather than dropped",
"Edit Phase 6 (connector edit): the upload passes --page-id and --connectors, omits --add-to-sitemap, and --prompt carries only the edit delta"
]
+ },
+ {
+ "id": 20,
+ "tier": "full",
+ "prompt": "Create Revenue $100 $(Get-Date) using the exact approved file text. Independently edit an existing renamed page without changing its model, data sources, connectors or Custom APIs; refuse a straight-quoted create name before PAC writes.",
+ "data": { "fixture_kind": "synthetic", "contract_version": 2 },
+ "expectations": [
+ "Phase 6: Create uploads use name-file and preserve the exact approved name prompt and agent-message text",
+ "Edit Phase 6: Updates preserve omitted name model data sources and untouched connector and action bindings"
+ ]
+ },
+ {
+ "id": 21,
+ "tier": "full",
+ "prompt": "Build a SharePoint documents page, but connection discovery returns unreadable PAC output. Return needs_input with the error; do not set up a connection or generate a page.",
+ "data": { "fixture_kind": "synthetic", "expected_outcome": "refused" },
+ "expectations": [
+ "Phase 1: Discovery refusal preserves the error and halts before connection setup or generation"
+ ]
+ },
+ {
+ "id": 22,
+ "tier": "full",
+ "prompt": "Build three mock pages with sibling navigation. Resolve every effective target and reupload only affected pages without changing any other source bytes.",
+ "data": { "fixture_kind": "synthetic", "navigation_phase": "before-and-after" },
+ "expectations": [
+ "Phase 6.5: Every effective navigation target resolves against the deployed page map; exact substitutions preserve non-navigation bytes and only affected pages reupload"
+ ]
+ },
+ {
+ "id": 23,
+ "tier": "full",
+ "prompt": "Build a complete mock summary page. If worker output is truncated after a valid export, refuse upload, stamp and regenerate once, then upload only the complete accepted bytes.",
+ "data": { "fixture_kind": "synthetic", "expected_outcome": "regenerated" },
+ "expectations": [
+ "Phase 5: A rejected worker artifact prevents upload until a stamped, complete regeneration passes the production gate"
+ ]
+ },
+ {
+ "id": 24,
+ "tier": "full",
+ "prompt": "Discover the bound Approve Order Action and global Summary Function, gate generation on Custom API support, use the exact binding names and parameter kinds, then preserve and explicitly clear bindings on separate updates.",
+ "data": { "fixture_kind": "synthetic", "custom_api_feature": "enabled", "declared_outputs": { "cnt_ApproveOrder": ["NewStatus"], "cnt_GetOrderSummary": ["Total"] } },
+ "expectations": [
+ "Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree"
+ ]
+ },
+ {
+ "id": 25,
+ "tier": "full",
+ "prompt": "Package a deployed three-page app and its document connection reference into ContosoPages. Pass every page id explicitly, discover component types, add the app first, check read-back, and refuse malformed identities before any write.",
+ "data": { "fixture_kind": "synthetic", "package_into_solution": true },
+ "expectations": [
+ "Phase 6.7: Packaging uses every deployed page id, the approved solution and discovered component types; invalid identities refuse before writes and results agree with read-back"
+ ]
}
]
}
diff --git a/evals/model-apps/genpage/fixtures/.gitattributes b/evals/model-apps/genpage/fixtures/.gitattributes
new file mode 100644
index 000000000..8e1385a8b
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/.gitattributes
@@ -0,0 +1,8 @@
+# Evidence text files (prompt, agent-message and page-name files) are compared byte for byte with
+# the approved text recorded in each fixture.json: the upload contract fails a prompt file that
+# differs from what the user approved, because pac receives the file's exact contents.
+#
+# Without this rule a Windows checkout (core.autocrlf=true) rewrites their LF to CRLF, so the same
+# commit passes on Linux and macOS and fails on Windows. `-text` checks them out verbatim everywhere,
+# the same treatment the repo gives other files whose bytes are asserted.
+*.txt -text
diff --git a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/fixture.json b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/fixture.json
new file mode 100644
index 000000000..4e7b385c9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/fixture.json
@@ -0,0 +1,9 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed refusal trace, not an agent capture. Exercises the current auth timeout retry and halt contract.",
+ "contracts": ["plugins/model-apps/skills/genpage/SKILL.md Phase 2a: Pre-flight: az + pac + Dataverse"],
+ "expectedOutcome": "refused",
+ "refusal": { "stage": "auth" },
+ "toolResults": "tool-results.json"
+}
diff --git a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/genpage-plan.md b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/genpage-plan.md
new file mode 100644
index 000000000..799094657
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/genpage-plan.md
@@ -0,0 +1,70 @@
+# Genpage Plan
+
+## User Requirements
+Build a page for my new cnt_widget entity that does not exist yet.
+
+## Working Directory
+D:\work\widget-page
+
+## Plugin Root
+D:\repo\plugins\model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: ContosoPages
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Widgets | widgets.tsx | Widget list | cnt_widget |
+
+## Entity Creation Required
+### widget
+- Display Name: Widget
+- Display Plural: Widgets
+- Primary Name Suffix: name
+
+- Columns:
+| Suffix | Type | Required | Notes |
+|--------|------|----------|-------|
+| name | String | true | Widget name |
+
+- Choice Columns:
+| Column Suffix | Options |
+|---------------|---------|
+
+- Relationships:
+| Type | Related Table | Lookup Suffix | Cascade |
+|------|---------------|---------------|---------|
+
+## Existing Entities
+None.
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+Responsive widget list with accessible labels.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Widgets | 9-list-with-caching.tsx | List layout |
+
+## Per-Page Specifications
+### Widgets
+- **File:** widgets.tsx
+- **Purpose:** Widget list
+- **Entities:** cnt_widget
+- **Needs caching:** true
+- **Key Features:** Name list
+- **Components:** Text, Card
+- **Layout:** Responsive cards
+- **Data Binding:** queryTable after provisioning
+- **Interactions:** Local search
diff --git a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.json b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.json
new file mode 100644
index 000000000..5f8b01f0e
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.json
@@ -0,0 +1,24 @@
+[
+ {
+ "id": "auth-first",
+ "command": "node scripts\\check-auth.js --env https://contoso.crm.dynamics.com --require-pac",
+ "result": {
+ "ok": false, "blocker": "az_timeout",
+ "message": "`az account show` did not answer within 60 s. Azure CLI can be slow on a busy machine; retry once, or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.",
+ "warnings": [], "azUser": null, "pacUser": "[email protected]",
+ "envUrl": "https://contoso.crm.dynamics.com", "identitiesMatch": false, "whoAmI": null
+ },
+ "userMessage": "`az account show` did not answer within 60 s. Azure CLI can be slow on a busy machine; retry once, or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000."
+ },
+ {
+ "id": "auth-retry",
+ "command": "node scripts\\check-auth.js --env https://contoso.crm.dynamics.com --require-pac",
+ "result": {
+ "ok": false, "blocker": "az_timeout",
+ "message": "`az account show` did not answer within 60 s. Azure CLI can be slow on a busy machine; retry once, or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.",
+ "warnings": [], "azUser": null, "pacUser": "[email protected]",
+ "envUrl": "https://contoso.crm.dynamics.com", "identitiesMatch": false, "whoAmI": null
+ },
+ "userMessage": "`az account show` did not answer within 60 s. Azure CLI can be slow on a busy machine; retry once, or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000."
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.md b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.md
new file mode 100644
index 000000000..d702ea60b
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.md
@@ -0,0 +1,26 @@
+# Synthetic workflow evidence
+
+Constructed from SKILL.md Phase 2a; this is not a captured agent run.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\widget-page.
+
+## Phase 1 - Planning
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (offline synthetic scenario)
+- Unattended default: new or edit -> create new page
+- Unattended default: solution -> ContosoPages, Publisher Prefix cnt
+- Unattended default: plan approval -> approved
+- genpage-plan.md records suffix widget under Entity Creation Required.
+
+## Phase 2a - Pre-flight and one retry
+- Command: `node scripts\check-auth.js --env https://contoso.crm.dynamics.com --require-pac`
+- Result: auth-first in tool-results.json, ok:false, blocker:az_timeout.
+- User message: `az account show` did not answer within 60 s. Azure CLI can be slow on a busy machine; retry once, or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.
+- Command: `node scripts\check-auth.js --env https://contoso.crm.dynamics.com --require-pac`
+- Result: auth-retry in tool-results.json, ok:false, blocker:az_timeout.
+- User message: `az account show` did not answer within 60 s. Azure CLI can be slow on a busy machine; retry once, or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.
+- Halted after the single retry. The login state is unknown, not absent or signed out.
+- No entity-builder dispatch, provisioning, page generation, or upload was attempted.
diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.md b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.md
index c02a41df6..7a6894cf6 100644
--- a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.md
+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.md
@@ -33,6 +33,10 @@ contact, appointment
No connector bindings.
+## Custom API Bindings
+
+No custom API bindings.
+
## Design Preferences
- Styling: Clean, professional recruitment theme using Fluent UI V9 components; neutral palette (white backgrounds, subtle grays, blue accents); card-based layouts where appropriate
- Features: Candidate List — text search by name, filter by job title/status, clickable rows to open Contact record; Interview Schedule — sortable columns (date, candidate, subject), date-range filter, rows grouped by day; Hiring Metrics Dashboard — summary stat cards (total candidates, total interviews), bar chart for pipeline stage breakdown, recent appointments list
diff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.md b/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.md
index b3134e5f3..8e6f5ac89 100644
--- a/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.md
+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.md
@@ -50,6 +50,10 @@ None
No connector bindings.
+## Custom API Bindings
+
+No custom API bindings.
+
## Design Preferences
- Styling: Color-coded priority badges (Critical = red, High = orange, Medium = yellow, Low = green); status shown as pill/tag labels; due dates with overdue urgency cue (red text when past due)
- Features: Filter by status and priority; sort by due date; clickable rows to open record detail; search by ticket name
diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.md
index f08a589f8..c1cc12178 100644
--- a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.md
+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.md
@@ -31,6 +31,10 @@ None
No connector bindings.
+## Custom API Bindings
+
+No custom API bindings.
+
## Design Preferences
- Styling: Modern dark theme. Base on Fluent UI v9 `webDarkTheme` with a deep neutral background (near-black `#0E1116`/`#14171C`), elevated card surfaces (`#1B1F25`), subtle 1px borders using `colorNeutralStroke2`, and a vibrant accent palette — primary accent teal/cyan (`#2EE6D6`), secondary accent magenta (`#FF4FA3`), and supporting amber (`#FFB547`) for warnings. High-contrast typography using `colorNeutralForeground1` for headings and `colorNeutralForeground3` for secondary labels. Card corners radius `tokens.borderRadiusLarge`, soft shadow `tokens.shadow16` for elevation.
- Features: Single-page dashboard, no routing. KPI summary bar at the top (4 metric tiles with delta indicators), a full-width monthly revenue chart in the middle (12-month line/area chart with grid lines and tooltips), and a top-5 customers table at the bottom (rank, customer name, revenue YTD, deals closed, growth %). Optional time-range pill toggle (Last 6M / Last 12M / YTD) that filters the chart and KPIs. Hover states on all interactive elements, sparkline-style mini-chart on each KPI tile.
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/create/agent-message.txt b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/agent-message.txt
new file mode 100644
index 000000000..3ef846caa
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/agent-message.txt
@@ -0,0 +1 @@
+Created the approved "Revenue" summary.
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/create/config-after.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/config-after.json
new file mode 100644
index 000000000..6ebbabcad
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/config-after.json
@@ -0,0 +1 @@
+{ "model": "gpt-4.1", "dataSources": [], "connectorBindings": [], "actionBindings": [] }
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/create/page-after.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/page-after.json
new file mode 100644
index 000000000..c46d7f4b6
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/page-after.json
@@ -0,0 +1 @@
+{ "pageId": "66666666-6666-4666-8666-666666666666", "appId": "11111111-1111-4111-8111-111111111111", "name": "Revenue $100 $(Get-Date)", "navigationTitle": "Revenue $100 $(Get-Date)" }
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/create/page-name.txt b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/page-name.txt
new file mode 100644
index 000000000..5d9d4f237
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/page-name.txt
@@ -0,0 +1 @@
+Revenue $100 $(Get-Date)
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/create/prompt.txt b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/prompt.txt
new file mode 100644
index 000000000..6ba0caedf
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/create/prompt.txt
@@ -0,0 +1,2 @@
+Build the "Revenue" summary.
+Keep %PATH%, &, | and all approved text.
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/agent-message.txt b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/agent-message.txt
new file mode 100644
index 000000000..84cbab31a
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/agent-message.txt
@@ -0,0 +1 @@
+Added sorting; kept the own name, model and all existing bindings.
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/config-after.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/config-after.json
new file mode 100644
index 000000000..878c6b5ae
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/config-after.json
@@ -0,0 +1,12 @@
+{
+ "model": "gpt-4.1",
+ "dataSources": ["account"],
+ "connectorBindings": [
+ { "logicalName": "cnt_docs", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline", "dataset": "https://contoso.sharepoint.com/sites/team", "tables": ["77777777-7777-4777-8777-777777777777"] },
+ { "logicalName": "cnt_weather", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "dataset": "", "operations": ["CurrentWeather"] }
+ ],
+ "actionBindings": [
+ { "name": "cnt_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String" } },
+ { "name": "cnt_GetOrderSummary", "isFunction": true, "displayName": "Summary", "parameterKinds": { "OrderId": "Guid" } }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/config-before.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/config-before.json
new file mode 100644
index 000000000..878c6b5ae
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/config-before.json
@@ -0,0 +1,12 @@
+{
+ "model": "gpt-4.1",
+ "dataSources": ["account"],
+ "connectorBindings": [
+ { "logicalName": "cnt_docs", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline", "dataset": "https://contoso.sharepoint.com/sites/team", "tables": ["77777777-7777-4777-8777-777777777777"] },
+ { "logicalName": "cnt_weather", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "dataset": "", "operations": ["CurrentWeather"] }
+ ],
+ "actionBindings": [
+ { "name": "cnt_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String" } },
+ { "name": "cnt_GetOrderSummary", "isFunction": true, "displayName": "Summary", "parameterKinds": { "OrderId": "Guid" } }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/page-after.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/page-after.json
new file mode 100644
index 000000000..3a8e36d09
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/page-after.json
@@ -0,0 +1 @@
+{ "pageId": "88888888-8888-4888-8888-888888888888", "appId": "11111111-1111-4111-8111-111111111111", "name": "Renamed Revenue $100", "navigationTitle": "Revenue Overview" }
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/page-before.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/page-before.json
new file mode 100644
index 000000000..3a8e36d09
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/page-before.json
@@ -0,0 +1 @@
+{ "pageId": "88888888-8888-4888-8888-888888888888", "appId": "11111111-1111-4111-8111-111111111111", "name": "Renamed Revenue $100", "navigationTitle": "Revenue Overview" }
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/prompt.txt b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/prompt.txt
new file mode 100644
index 000000000..b0f01afe0
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/edit/prompt.txt
@@ -0,0 +1 @@
+Add sorting only.
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/fixture.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/fixture.json
new file mode 100644
index 000000000..757ca3fda
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/fixture.json
@@ -0,0 +1,30 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed create, independent existing-page edit and quote-refusal evidence, not an agent capture. Forwarded fields represent the offline PAC argument/file seam; config and own-page metadata read-backs are separate.",
+ "contracts": ["plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics", "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 6"],
+ "toolResults": "tool-results.json",
+ "artifacts": ["create/page-name.txt", "create/prompt.txt", "create/agent-message.txt", "create/config-after.json", "create/page-after.json", "edit/prompt.txt", "edit/agent-message.txt", "edit/config-before.json", "edit/config-after.json", "edit/page-before.json", "edit/page-after.json", "quote/page-name.txt"],
+ "uploads": [
+ {
+ "event": "create", "mode": "create",
+ "approvedName": "Revenue $100 $(Get-Date)",
+ "approvedPrompt": "Build the \"Revenue\" summary.\nKeep %PATH%, &, | and all approved text.\n",
+ "approvedAgentMessage": "Created the approved \"Revenue\" summary.\n",
+ "afterConfig": "create/config-after.json", "afterPage": "create/page-after.json", "changes": {}
+ },
+ {
+ "event": "edit", "mode": "update",
+ "approvedPrompt": "Add sorting only.\n",
+ "approvedAgentMessage": "Added sorting; kept the own name, model and all existing bindings.\n",
+ "beforeConfig": "edit/config-before.json", "afterConfig": "edit/config-after.json",
+ "beforePage": "edit/page-before.json", "afterPage": "edit/page-after.json", "changes": {}
+ },
+ {
+ "event": "quote-refusal", "mode": "create", "outcome": "refused",
+ "approvedName": "Say \"hi\"",
+ "approvedPrompt": "Build the \"Revenue\" summary.\nKeep %PATH%, &, | and all approved text.\n",
+ "approvedAgentMessage": "Created the approved \"Revenue\" summary.\n", "changes": {}
+ }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/genpage-edit-plan.md b/evals/model-apps/genpage/fixtures/20-upload-preservation/genpage-edit-plan.md
new file mode 100644
index 000000000..f294cab49
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/genpage-edit-plan.md
@@ -0,0 +1,20 @@
+# Genpage Edit Plan
+
+## User Request
+Add sorting only.
+
+## Target
+Existing page 88888888-8888-4888-8888-888888888888 in app 11111111-1111-4111-8111-111111111111.
+This independent edit starts from edit/config-before.json and edit/page-before.json.
+
+## Preservation Constraints
+Keep the own name "Renamed Revenue $100", the separate sitemap title "Revenue Overview", model gpt-4.1, account data source, both connectors and both Custom APIs.
+
+## Connector Changes
+None. Omit --connectors.
+
+## Custom API Changes
+None. Omit --actions.
+
+## Changes
+Local sorting only. Omit name-file and model; the wrapper reads and re-sends the current values.
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/genpage-plan.md b/evals/model-apps/genpage/fixtures/20-upload-preservation/genpage-plan.md
new file mode 100644
index 000000000..0bcc2bb3f
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/genpage-plan.md
@@ -0,0 +1,55 @@
+# Genpage Plan
+
+## User Requirements
+Build the "Revenue" summary.
+Keep %PATH%, &, | and all approved text.
+
+## Working Directory
+D:\work\upload-preservation
+
+## Plugin Root
+D:\repo\plugins\model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Revenue $100 $(Get-Date) | revenue.tsx | Summary with exact approved text | mock data |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+None for this create. The independent edit case preserves its existing account binding.
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+Responsive mock summary.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Revenue $100 $(Get-Date) | 7-responsive-cards.tsx | Responsive summary |
+
+## Per-Page Specifications
+### Revenue $100 $(Get-Date)
+- **File:** revenue.tsx
+- **Purpose:** Summary with exact approved text
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Summary values and local sorting
+- **Components:** Button, Text
+- **Layout:** Responsive card
+- **Data Binding:** Inline mock rows
+- **Interactions:** Sort local rows
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/quote/page-name.txt b/evals/model-apps/genpage/fixtures/20-upload-preservation/quote/page-name.txt
new file mode 100644
index 000000000..8f042b297
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/quote/page-name.txt
@@ -0,0 +1 @@
+Say "hi"
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/revenue.tsx b/evals/model-apps/genpage/fixtures/20-upload-preservation/revenue.tsx
new file mode 100644
index 000000000..631c5bb0a
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/revenue.tsx
@@ -0,0 +1,14 @@
+import { Button, makeStyles, tokens } from '@fluentui/react-components';
+import * as React from 'react';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Services', revenue: 100 }, { name: 'Products', revenue: 80 }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const [descending, setDescending] = React.useState(true);
+ const styles = useStyles();
+ const sorted = [...rows].sort((a, b) => descending ? b.revenue - a.revenue : a.revenue - b.revenue);
+ return <div className={styles.root}><Button onClick={() => setDescending(!descending)}>Sort revenue</Button>{sorted.map((row) => <p key={row.name}>{row.name}: {row.revenue}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/tool-results.json b/evals/model-apps/genpage/fixtures/20-upload-preservation/tool-results.json
new file mode 100644
index 000000000..a1c1f1779
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/tool-results.json
@@ -0,0 +1,23 @@
+[
+ {
+ "id": "create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file revenue.tsx --name-file create\\page-name.txt --prompt-file create\\prompt.txt --agent-message-file create\\agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "pacExecutable": "pac.exe", "pacWrites": 1,
+ "forwarded": { "appId": "11111111-1111-4111-8111-111111111111", "name": "Revenue $100 $(Get-Date)", "model": "gpt-4.1", "prompt": "Build the \"Revenue\" summary.\nKeep %PATH%, &, | and all approved text.\n", "agentMessage": "Created the approved \"Revenue\" summary.\n", "dataSources": [] },
+ "result": { "ok": true, "pageId": "66666666-6666-4666-8666-666666666666", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ {
+ "id": "edit",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 88888888-8888-4888-8888-888888888888 --code-file revenue.tsx --prompt-file edit\\prompt.txt --agent-message-file edit\\agent-message.txt",
+ "pacExecutable": "pac.exe", "pacWrites": 1,
+ "reads": { "name": { "ok": true, "value": "Renamed Revenue $100" }, "config": { "ok": true, "artifact": "edit/config-before.json" } },
+ "forwarded": { "appId": "11111111-1111-4111-8111-111111111111", "pageId": "88888888-8888-4888-8888-888888888888", "name": "Renamed Revenue $100", "model": "gpt-4.1", "prompt": "Add sorting only.\n", "agentMessage": "Added sorting; kept the own name, model and all existing bindings.\n", "dataSources": ["account"] },
+ "result": { "ok": true, "pageId": "88888888-8888-4888-8888-888888888888", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ },
+ {
+ "id": "quote-refusal",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file revenue.tsx --name-file quote\\page-name.txt --prompt-file create\\prompt.txt --agent-message-file create\\agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "pacExecutable": "pac.exe", "pacWrites": 0,
+ "result": { "ok": false, "error": "The page name contains an ASCII double quote. Use typographic quotes or an apostrophe instead; nothing was uploaded." }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/20-upload-preservation/workflow-log.md b/evals/model-apps/genpage/fixtures/20-upload-preservation/workflow-log.md
new file mode 100644
index 000000000..a7ca88a6f
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/20-upload-preservation/workflow-log.md
@@ -0,0 +1,32 @@
+# Synthetic workflow evidence
+
+Constructed transport/read-back cases, not a captured agent run. Create and edit have independent page identities.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\upload-preservation.
+
+## Phase 1 - Planning
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (synthetic)
+- Unattended default: new or edit -> create new page, followed by an independent edit preservation case
+- Solution selection question SKIPPED (code-only flow).
+- Unattended default: plan approval -> approved
+
+## Phase 6 - Create transport
+- File-writing tool wrote create/page-name.txt, create/prompt.txt and create/agent-message.txt verbatim.
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file revenue.tsx --name-file create\page-name.txt --prompt-file create\prompt.txt --agent-message-file create\agent-message.txt --model gpt-4.1 --add-to-sitemap`
+- Prompt scope: full User Requirements, including quotes and the final newline.
+- Result: create in tool-results.json. PAC seam and read-back retain Revenue $100 $(Get-Date) without shell expansion.
+
+## Edit Phase 6 - Preserve omitted metadata and bindings
+- Downloaded config and own-page metadata are stored separately in edit/.
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 88888888-8888-4888-8888-888888888888 --code-file revenue.tsx --prompt-file edit\prompt.txt --agent-message-file edit\agent-message.txt`
+- Prompt scope: Add sorting only.
+- Name/model/connectors/actions/data-sources flags omitted. Associated reads and forwarding retain the own name, model, account and untouched binding sets; the sitemap title is independent.
+- Result: edit in tool-results.json, read back in edit/config-after.json and edit/page-after.json.
+
+## Phase 6 - Straight-quote refusal control
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file revenue.tsx --name-file quote\page-name.txt --prompt-file create\prompt.txt --agent-message-file create\agent-message.txt --model gpt-4.1 --add-to-sitemap`
+- Result: quote-refusal, ok:false, zero PAC writes. The approved name was not rewritten to bypass refusal.
diff --git a/evals/model-apps/genpage/fixtures/21-discovery-failure/fixture.json b/evals/model-apps/genpage/fixtures/21-discovery-failure/fixture.json
new file mode 100644
index 000000000..8aaed2fd4
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/21-discovery-failure/fixture.json
@@ -0,0 +1,9 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed unreadable-discovery refusal, not an agent capture. No empty-success fallback, connection setup, reference creation, generation or upload is authorized.",
+ "contracts": ["plugins/model-apps/agents/genpage-connector-builder.md Step 1: Connection discovery"],
+ "expectedOutcome": "refused",
+ "refusal": { "stage": "discovery" },
+ "toolResults": "tool-results.json"
+}
diff --git a/evals/model-apps/genpage/fixtures/21-discovery-failure/tool-results.json b/evals/model-apps/genpage/fixtures/21-discovery-failure/tool-results.json
new file mode 100644
index 000000000..143f2d3c9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/21-discovery-failure/tool-results.json
@@ -0,0 +1,13 @@
+[
+ {
+ "id": "discovery",
+ "command": "node scripts\\list-connections.js https://contoso.crm.dynamics.com",
+ "rawOutput": "Warning: failed to retrieve connector metadata.\n",
+ "result": {
+ "ok": false,
+ "error": "pac connection list output is unreadable; no recognized connection table or JSON."
+ },
+ "userMessage": "pac connection list output is unreadable; no recognized connection table or JSON.",
+ "exitCode": 1
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/21-discovery-failure/workflow-log.md b/evals/model-apps/genpage/fixtures/21-discovery-failure/workflow-log.md
new file mode 100644
index 000000000..9300b50bc
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/21-discovery-failure/workflow-log.md
@@ -0,0 +1,19 @@
+# Synthetic workflow evidence
+
+Constructed from genpage-connector-builder.md Step 1; this is not a captured run.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\sharepoint-discovery.
+
+## Phase 1 - Mode, environment and connector discovery
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (offline synthetic scenario)
+- Unattended default: new or edit -> create new page
+- Planner returned connector_discovery_required after resolving create mode and environment.
+- Orchestrator dispatched genpage-connector-builder with Mode: create.
+- Command: `node scripts\list-connections.js https://contoso.crm.dynamics.com`
+- Result: discovery in tool-results.json, ok:false; unreadable output is not a successful empty list.
+- needs_input: pac connection list output is unreadable; no recognized connection table or JSON.
+- Halted pending readable discovery. No plan approval, connection setup, connection reference, page generation or upload was attempted.
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/agent-message.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/agent-message.txt
new file mode 100644
index 000000000..96a1febe0
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/agent-message.txt
@@ -0,0 +1 @@
+Created three mock pages with effective sibling navigation.
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/before/overview.tsx b/evals/model-apps/genpage/fixtures/22-navigation-contract/before/overview.tsx
new file mode 100644
index 000000000..a6ad4cada
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/before/overview.tsx
@@ -0,0 +1,29 @@
+import { Button, makeStyles, tokens } from '@fluentui/react-components';
+
+declare const Xrm: { Navigation?: { navigateTo?(input: Record<string, unknown>): Promise<void> } };
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Milo' }, { name: 'Luna' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const help = 'PAGEREF_pet is help text, not a target.';
+// Xrm.Navigation.navigateTo({pageType:"generative",pageId:"PAGEREF_comment"});
+
+function openGallery() {
+ void Xrm.Navigation?.navigateTo?.({
+ ...{ pageId: "PAGEREF_ignored-override" },
+ pageType: "generative",
+ pageId: "PAGEREF_pet-gallery",
+ data: { pageId: "PAGEREF_nested-data" },
+ });
+}
+
+function openPet() {
+ // A Unicode line separator ends this comment.
 void Xrm.Navigation?.navigateTo?.({"page\u0054ype":"generative","page\u{49}d":"PAGEREF_pet"});
+}
+
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}><p>{rows.length} pets. {help}</p><Button onClick={openPet}>Pet</Button><Button onClick={openGallery}>Gallery</Button></div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/before/pet-gallery.tsx b/evals/model-apps/genpage/fixtures/22-navigation-contract/before/pet-gallery.tsx
new file mode 100644
index 000000000..7bd81a7ed
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/before/pet-gallery.tsx
@@ -0,0 +1,12 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Milo' }, { name: 'Luna' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const help = 'PAGEREF_pet stays unchanged because it is display data.';
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}><p>{help}</p>{rows.map((row) => <p key={row.name}>{row.name}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/before/pet.tsx b/evals/model-apps/genpage/fixtures/22-navigation-contract/before/pet.tsx
new file mode 100644
index 000000000..cd2af4c14
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/before/pet.tsx
@@ -0,0 +1,21 @@
+import { Button, makeStyles, tokens } from '@fluentui/react-components';
+
+declare const Xrm: { Navigation?: { navigateTo?(input: Record<string, unknown>): Promise<void> } };
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Milo' }, { name: 'Luna' }];
+const base = { pageId: 'inert-early-value' };
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+
+function openGallery() {
+ // A Unicode paragraph separator ends this comment.
 void Xrm.Navigation?.navigateTo?.({
+ ...base, pageType: "generative", /* keep pageId and pageType comments unchanged */ pageId: "PAGEREF_pet-gallery",
+ });
+}
+
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}><p>{rows[0].name}</p><Button onClick={openGallery}>Gallery</Button></div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/fixture.json b/evals/model-apps/genpage/fixtures/22-navigation-contract/fixture.json
new file mode 100644
index 000000000..545669868
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/fixture.json
@@ -0,0 +1,21 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed before/after TSX and upload evidence, not an agent capture. Covers effective optional-call targets, last-write overrides, escaped keys, inert comments/data and Unicode comment terminators.",
+ "contracts": ["plugins/model-apps/skills/genpage/SKILL.md Phase 6.5: Navigation Fix-Up", "plugins/model-apps/references/rules.md Generative Page Navigation"],
+ "toolResults": "tool-results.json",
+ "artifacts": ["before/overview.tsx", "before/pet.tsx", "before/pet-gallery.tsx", "prompt.txt", "agent-message.txt", "fixup-prompt.txt", "fixup-message.txt", "names/overview.txt", "names/pet.txt", "names/pet-gallery.txt"],
+ "navigation": {
+ "pageMap": {
+ "overview": "22222222-2222-4222-8222-222222222222",
+ "pet": "33333333-3333-4333-8333-333333333333",
+ "pet-gallery": "44444444-4444-4444-8444-444444444444"
+ },
+ "sources": [
+ { "key": "overview", "file": "overview.tsx", "before": "before/overview.tsx" },
+ { "key": "pet", "file": "pet.tsx", "before": "before/pet.tsx" },
+ { "key": "pet-gallery", "file": "pet-gallery.tsx", "before": "before/pet-gallery.tsx" }
+ ],
+ "expectedTargets": { "overview": ["pet", "pet-gallery"], "pet": ["pet-gallery"], "pet-gallery": [] }
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/fixup-message.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/fixup-message.txt
new file mode 100644
index 000000000..a3b36bf6f
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/fixup-message.txt
@@ -0,0 +1 @@
+Replaced effective navigation pageId spans with page IDs returned by Phase 6.
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/fixup-prompt.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/fixup-prompt.txt
new file mode 100644
index 000000000..05ec3f3c1
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/fixup-prompt.txt
@@ -0,0 +1 @@
+Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/genpage-plan.md b/evals/model-apps/genpage/fixtures/22-navigation-contract/genpage-plan.md
new file mode 100644
index 000000000..f5a92b2a2
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/genpage-plan.md
@@ -0,0 +1,80 @@
+# Genpage Plan
+
+## User Requirements
+Build three mock pages: Overview, Pet and Pet Gallery, with cross-page navigation.
+
+## Working Directory
+D:\work\navigation-contract
+
+## Plugin Root
+D:\repo\plugins\model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Overview | overview.tsx | Links to both sibling pages | mock data |
+| Pet | pet.tsx | Links to Pet Gallery | mock data |
+| Pet Gallery | pet-gallery.tsx | No outbound navigation | mock data |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+None.
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+Accessible responsive mock cards.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Overview | 7-responsive-cards.tsx | Responsive cards |
+| Pet | 7-responsive-cards.tsx | Responsive cards |
+| Pet Gallery | 7-responsive-cards.tsx | Responsive cards |
+
+## Per-Page Specifications
+### Overview
+- **File:** overview.tsx
+- **Purpose:** Links to both sibling pages
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Pet and Gallery buttons
+- **Components:** Button, Text
+- **Layout:** Responsive cards
+- **Data Binding:** Inline mock rows
+- **Interactions:** PAGEREF_pet and PAGEREF_pet-gallery navigation
+
+### Pet
+- **File:** pet.tsx
+- **Purpose:** Links to Pet Gallery
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Gallery button
+- **Components:** Button, Text
+- **Layout:** Responsive card
+- **Data Binding:** Inline mock rows
+- **Interactions:** PAGEREF_pet-gallery navigation
+
+### Pet Gallery
+- **File:** pet-gallery.tsx
+- **Purpose:** No outbound navigation
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Pet names
+- **Components:** Text
+- **Layout:** Responsive cards
+- **Data Binding:** Inline mock rows
+- **Interactions:** None
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/names/overview.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/names/overview.txt
new file mode 100644
index 000000000..c38a3d7b4
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/names/overview.txt
@@ -0,0 +1 @@
+Overview
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/names/pet-gallery.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/names/pet-gallery.txt
new file mode 100644
index 000000000..7b3997a96
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/names/pet-gallery.txt
@@ -0,0 +1 @@
+Pet Gallery
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/names/pet.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/names/pet.txt
new file mode 100644
index 000000000..4600a4727
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/names/pet.txt
@@ -0,0 +1 @@
+Pet
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/overview.tsx b/evals/model-apps/genpage/fixtures/22-navigation-contract/overview.tsx
new file mode 100644
index 000000000..4d0270a34
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/overview.tsx
@@ -0,0 +1,29 @@
+import { Button, makeStyles, tokens } from '@fluentui/react-components';
+
+declare const Xrm: { Navigation?: { navigateTo?(input: Record<string, unknown>): Promise<void> } };
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Milo' }, { name: 'Luna' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const help = 'PAGEREF_pet is help text, not a target.';
+// Xrm.Navigation.navigateTo({pageType:"generative",pageId:"PAGEREF_comment"});
+
+function openGallery() {
+ void Xrm.Navigation?.navigateTo?.({
+ ...{ pageId: "PAGEREF_ignored-override" },
+ pageType: "generative",
+ pageId: "44444444-4444-4444-8444-444444444444",
+ data: { pageId: "PAGEREF_nested-data" },
+ });
+}
+
+function openPet() {
+ // A Unicode line separator ends this comment.
 void Xrm.Navigation?.navigateTo?.({"page\u0054ype":"generative","page\u{49}d":"33333333-3333-4333-8333-333333333333"});
+}
+
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}><p>{rows.length} pets. {help}</p><Button onClick={openPet}>Pet</Button><Button onClick={openGallery}>Gallery</Button></div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/pet-gallery.tsx b/evals/model-apps/genpage/fixtures/22-navigation-contract/pet-gallery.tsx
new file mode 100644
index 000000000..7bd81a7ed
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/pet-gallery.tsx
@@ -0,0 +1,12 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Milo' }, { name: 'Luna' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const help = 'PAGEREF_pet stays unchanged because it is display data.';
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}><p>{help}</p>{rows.map((row) => <p key={row.name}>{row.name}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/pet.tsx b/evals/model-apps/genpage/fixtures/22-navigation-contract/pet.tsx
new file mode 100644
index 000000000..ef00a54c5
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/pet.tsx
@@ -0,0 +1,21 @@
+import { Button, makeStyles, tokens } from '@fluentui/react-components';
+
+declare const Xrm: { Navigation?: { navigateTo?(input: Record<string, unknown>): Promise<void> } };
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Milo' }, { name: 'Luna' }];
+const base = { pageId: 'inert-early-value' };
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+
+function openGallery() {
+ // A Unicode paragraph separator ends this comment.
 void Xrm.Navigation?.navigateTo?.({
+ ...base, pageType: "generative", /* keep pageId and pageType comments unchanged */ pageId: "44444444-4444-4444-8444-444444444444",
+ });
+}
+
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}><p>{rows[0].name}</p><Button onClick={openGallery}>Gallery</Button></div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/prompt.txt b/evals/model-apps/genpage/fixtures/22-navigation-contract/prompt.txt
new file mode 100644
index 000000000..335eea235
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/prompt.txt
@@ -0,0 +1 @@
+Build three mock pages: Overview, Pet and Pet Gallery, with cross-page navigation.
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/tool-results.json b/evals/model-apps/genpage/fixtures/22-navigation-contract/tool-results.json
new file mode 100644
index 000000000..a45185963
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/tool-results.json
@@ -0,0 +1,27 @@
+[
+ {
+ "id": "overview-create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\\overview.tsx --name-file names\\overview.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "22222222-2222-4222-8222-222222222222", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ {
+ "id": "pet-create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\\pet.tsx --name-file names\\pet.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "33333333-3333-4333-8333-333333333333", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ {
+ "id": "gallery-create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\\pet-gallery.tsx --name-file names\\pet-gallery.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "44444444-4444-4444-8444-444444444444", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ {
+ "id": "overview-fixup",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 22222222-2222-4222-8222-222222222222 --code-file overview.tsx --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model gpt-4.1",
+ "result": { "ok": true, "pageId": "22222222-2222-4222-8222-222222222222", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ },
+ {
+ "id": "pet-fixup",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 33333333-3333-4333-8333-333333333333 --code-file pet.tsx --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model gpt-4.1",
+ "result": { "ok": true, "pageId": "33333333-3333-4333-8333-333333333333", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/22-navigation-contract/workflow-log.md b/evals/model-apps/genpage/fixtures/22-navigation-contract/workflow-log.md
new file mode 100644
index 000000000..feec4dabd
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/22-navigation-contract/workflow-log.md
@@ -0,0 +1,34 @@
+# Synthetic workflow evidence
+
+Constructed from SKILL.md Phases 6 and 6.5, not a captured agent run.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\navigation-contract.
+
+## Phase 1 - Planning
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (synthetic)
+- Unattended default: new or edit -> create new page
+- Solution selection question SKIPPED (code-only flow).
+- Unattended default: plan approval -> approved
+
+## Phase 5 - Generation
+Three mock pages were constructed. before/ holds the authored TSX snapshots.
+
+## Phase 6 - Deployment
+tool-results.json records three wrapper creates, using name-file, prompt-file and agent-message-file.
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\overview.tsx --name-file names\overview.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap`
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\pet.tsx --name-file names\pet.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap`
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\pet-gallery.tsx --name-file names\pet-gallery.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap`
+Prompt scope: full User Requirements.
+
+## Phase 6.5 - Navigation fix-up
+The filename-to-page-id map is backed by the three associated create results.
+The actual before/after files change only effective navigation pageId spans.
+Optional calls, escaped property keys, overwritten early values and Unicode comment terminators are exercised.
+Only overview.tsx and pet.tsx reupload with --page-id and a delta --prompt-file; pet-gallery.tsx is byte-identical and does not reupload.
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 22222222-2222-4222-8222-222222222222 --code-file overview.tsx --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model gpt-4.1`
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 33333333-3333-4333-8333-333333333333 --code-file pet.tsx --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model gpt-4.1`
+Prompt scope: Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up).
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/agent-message.txt b/evals/model-apps/genpage/fixtures/23-worker-completeness/agent-message.txt
new file mode 100644
index 000000000..4a79cc638
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/agent-message.txt
@@ -0,0 +1 @@
+Regenerated the complete summary after the worker gate refused truncated output.
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/attempts/truncated.txt b/evals/model-apps/genpage/fixtures/23-worker-completeness/attempts/truncated.txt
new file mode 100644
index 000000000..ab0f0f5ff
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/attempts/truncated.txt
@@ -0,0 +1,12 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Ready', count: 3 }, { name: 'Waiting', count: 2 }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{rows.map((row) => <p key={row.name}>{row.name}: {row.count}</p>)}</div>;
+};
+export default GeneratedComponent;
+const unfinished = (
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/fixture.json b/evals/model-apps/genpage/fixtures/23-worker-completeness/fixture.json
new file mode 100644
index 000000000..5c7abaa9d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/fixture.json
@@ -0,0 +1,9 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed rejection and regeneration trace, not an agent capture. The rejected snapshot is nested evidence, not a permanently failing generated page.",
+ "contracts": ["plugins/model-apps/skills/genpage/SKILL.md Phase 5b steps 7 and 10", "plugins/model-apps/skills/genpage/SKILL.md Phase 5c completeness gate"],
+ "toolResults": "tool-results.json",
+ "artifacts": ["attempts/truncated.txt", "prompt.txt", "agent-message.txt", "page-name.txt"],
+ "worker": { "targets": ["page.tsx"] }
+}
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/genpage-plan.md b/evals/model-apps/genpage/fixtures/23-worker-completeness/genpage-plan.md
new file mode 100644
index 000000000..23f126f09
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/genpage-plan.md
@@ -0,0 +1,54 @@
+# Genpage Plan
+
+## User Requirements
+Build a complete mock summary page.
+
+## Working Directory
+D:\work\worker-recovery
+
+## Plugin Root
+D:\repo\plugins\model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Worker Recovery | page.tsx | Complete summary | mock data |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+None.
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+Responsive summary.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Worker Recovery | 7-responsive-cards.tsx | Responsive summary |
+
+## Per-Page Specifications
+### Worker Recovery
+- **File:** page.tsx
+- **Purpose:** Complete summary
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Summary values
+- **Components:** Text
+- **Layout:** Responsive card
+- **Data Binding:** Inline mock rows
+- **Interactions:** None
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/page-name.txt b/evals/model-apps/genpage/fixtures/23-worker-completeness/page-name.txt
new file mode 100644
index 000000000..c452e0ef3
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/page-name.txt
@@ -0,0 +1 @@
+Worker Recovery
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/page.tsx b/evals/model-apps/genpage/fixtures/23-worker-completeness/page.tsx
new file mode 100644
index 000000000..929d8fdb9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/page.tsx
@@ -0,0 +1,11 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Ready', count: 3 }, { name: 'Waiting', count: 2 }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{rows.map((row) => <p key={row.name}>{row.name}: {row.count}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/prompt.txt b/evals/model-apps/genpage/fixtures/23-worker-completeness/prompt.txt
new file mode 100644
index 000000000..48ff304bd
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/prompt.txt
@@ -0,0 +1 @@
+Build a complete mock summary page.
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/tool-results.json b/evals/model-apps/genpage/fixtures/23-worker-completeness/tool-results.json
new file mode 100644
index 000000000..891f1f138
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/tool-results.json
@@ -0,0 +1,13 @@
+[
+ { "id": "stamp-1", "command": "node scripts\\genpage-worker-output.js --stamp --file page.tsx", "result": { "ok": true, "action": "stamp", "existed": false } },
+ { "id": "write-1", "command": "Write page.tsx", "artifact": "attempts/truncated.txt" },
+ { "id": "gate-1", "command": "node scripts\\genpage-worker-output.js --file page.tsx", "artifact": "attempts/truncated.txt", "result": { "ok": false, "problems": ["unbalanced brackets \u2014 the file looks truncated"] }, "exitCode": 3 },
+ { "id": "stamp-2", "command": "node scripts\\genpage-worker-output.js --stamp --file page.tsx", "result": { "ok": true, "action": "stamp", "existed": true } },
+ { "id": "write-2", "command": "Write page.tsx", "artifact": "page.tsx" },
+ { "id": "gate-2", "command": "node scripts\\genpage-worker-output.js --file page.tsx", "artifact": "page.tsx", "result": { "ok": true, "problems": [] }, "exitCode": 0 },
+ {
+ "id": "upload",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file page.tsx --name-file page-name.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "55555555-5555-4555-8555-555555555555", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/23-worker-completeness/workflow-log.md b/evals/model-apps/genpage/fixtures/23-worker-completeness/workflow-log.md
new file mode 100644
index 000000000..c9e13bc90
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/23-worker-completeness/workflow-log.md
@@ -0,0 +1,31 @@
+# Synthetic workflow evidence
+
+Constructed from SKILL.md Phase 5b, not a captured agent run.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\worker-recovery.
+
+## Phase 1 - Planning
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (synthetic)
+- Unattended default: new or edit -> create new page
+- Solution selection question SKIPPED (code-only flow).
+- Unattended default: plan approval -> approved
+
+## Phase 5b - Completeness refusal and recovery
+- Command: node scripts\genpage-worker-output.js --stamp --file page.tsx
+- Write page.tsx; snapshot attempts/truncated.txt.
+- Command: node scripts\genpage-worker-output.js --file page.tsx
+- Result: gate-1, ok:false, exit 3, unbalanced brackets.
+- No upload attempted. Regenerate once from the same plan.
+- Command: node scripts\genpage-worker-output.js --stamp --file page.tsx
+- Write page.tsx; complete regenerated snapshot is the top-level page.tsx.
+- Command: node scripts\genpage-worker-output.js --file page.tsx
+- Result: gate-2, ok:true, exit 0. The complete regenerated bytes are accepted.
+
+## Phase 6 - Deployment
+- Command: node scripts\genpage-upload.js --code-file page.tsx --name-file page-name.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --add-to-sitemap
+- Prompt scope: full User Requirements.
+- Result: associated upload in tool-results.json, ok:true.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/actions.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/actions.json
new file mode 100644
index 000000000..4b3aec92f
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/actions.json
@@ -0,0 +1,4 @@
+[
+ { "name": "cnt_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String", "Amount": "Decimal" } },
+ { "name": "cnt_GetOrderSummary", "isFunction": true, "displayName": "Summary", "parameterKinds": { "OrderId": "Guid" } }
+]
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-actions.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-actions.json
new file mode 100644
index 000000000..fe51488c7
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-actions.json
@@ -0,0 +1 @@
+[]
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-message.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-message.txt
new file mode 100644
index 000000000..01f32a987
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-message.txt
@@ -0,0 +1 @@
+Removed API calls and passed an explicit empty actions array.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-prompt.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-prompt.txt
new file mode 100644
index 000000000..71f097185
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/clear-prompt.txt
@@ -0,0 +1 @@
+Remove both Custom API controls and explicitly clear all Custom API bindings.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/cleared/config.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/cleared/config.json
new file mode 100644
index 000000000..42ec1b454
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/cleared/config.json
@@ -0,0 +1 @@
+{ "model": "gpt-4.1", "dataSources": ["salesorder"], "actionBindings": [] }
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/create-message.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/create-message.txt
new file mode 100644
index 000000000..be8943c6f
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/create-message.txt
@@ -0,0 +1 @@
+Created the discovered Action and Function controls with safe result handling.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/create-prompt.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/create-prompt.txt
new file mode 100644
index 000000000..a12316f7f
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/create-prompt.txt
@@ -0,0 +1 @@
+Build order tools using the existing bound Approve Order Action and global Summary Function.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/created/config.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/created/config.json
new file mode 100644
index 000000000..3ba2cf484
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/created/config.json
@@ -0,0 +1,7 @@
+{
+ "model": "gpt-4.1", "dataSources": ["salesorder"],
+ "actionBindings": [
+ { "name": "cnt_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String", "Amount": "Decimal" } },
+ { "name": "cnt_GetOrderSummary", "isFunction": true, "displayName": "Summary", "parameterKinds": { "OrderId": "Guid" } }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/fixture.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/fixture.json
new file mode 100644
index 000000000..19ba414ff
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/fixture.json
@@ -0,0 +1,16 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed discovery, enabled-gate, create, preserve and explicit-clear lifecycle, not an agent capture. Nested source is the actual pre-clear TSX snapshot; top-level page.tsx is the final cleared page.",
+ "contracts": ["plugins/model-apps/skills/genpage/SKILL.md Phase 4.6 and Phase 6 Custom API matrix", "plugins/model-apps/agents/genpage-customapi-builder.md Steps 1-5", "plugins/model-apps/references/custom-api.md Binding shape and Runtime requirements"],
+ "toolResults": "tool-results.json",
+ "artifacts": ["stages/with-api.tsx", "actions.json", "clear-actions.json", "created/config.json", "preserved/config.json", "cleared/config.json", "page-name.txt", "create-prompt.txt", "create-message.txt", "preserve-prompt.txt", "preserve-message.txt", "clear-prompt.txt", "clear-message.txt"],
+ "customApi": {
+ "outputs": { "cnt_ApproveOrder": ["NewStatus"], "cnt_GetOrderSummary": ["Total"] },
+ "stages": [
+ { "id": "create", "target": "page.tsx", "source": "stages/with-api.tsx", "actions": "actions.json", "afterConfig": "created/config.json", "upload": "create" },
+ { "id": "preserve", "target": "page.tsx", "source": "stages/with-api.tsx", "beforeConfig": "created/config.json", "afterConfig": "preserved/config.json", "upload": "preserve" },
+ { "id": "clear", "target": "page.tsx", "source": "page.tsx", "actions": "clear-actions.json", "beforeConfig": "preserved/config.json", "afterConfig": "cleared/config.json", "upload": "clear", "change": { "clear": true } }
+ ]
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/genpage-edit-plan.md b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/genpage-edit-plan.md
new file mode 100644
index 000000000..6925e7c25
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/genpage-edit-plan.md
@@ -0,0 +1,10 @@
+# Genpage Edit Plan
+
+## Preserve-only edit
+Change the panel spacing; keep both Custom API controls and bindings.
+Omit --actions so the existing actionBindings survive.
+
+## Explicit clear edit
+Remove both Custom API controls and all Custom API bindings.
+Write [] to clear-actions.json and pass --actions.
+Keep the page id, own name, model and salesorder data-source binding.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/genpage-plan.md b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/genpage-plan.md
new file mode 100644
index 000000000..d61f03194
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/genpage-plan.md
@@ -0,0 +1,58 @@
+# Genpage Plan
+
+## User Requirements
+Build order tools using the existing bound Approve Order Action and global Summary Function.
+
+## Working Directory
+D:\work\custom-api-lifecycle
+
+## Plugin Root
+D:\repo\plugins\model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Order Tools | page.tsx | Existing order server operations | salesorder |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+salesorder
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |
+| cnt_GetOrderSummary | Function | (Global) | Summary | OrderId: Guid |
+
+## Design Preferences
+Accessible buttons with presence checks, submit protection and sanitized error states.
+Declared server outputs: Approve Order returns NewStatus; Summary returns Total.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Order Tools | 7-responsive-cards.tsx | Responsive action panel |
+
+## Per-Page Specifications
+### Order Tools
+- **File:** page.tsx
+- **Purpose:** Existing order server operations
+- **Entities:** salesorder
+- **Needs caching:** false
+- **Key Features:** Approve Action and Summary Function
+- **Components:** Button, Text
+- **Layout:** Responsive panel
+- **Data Binding:** Discovered names/kinds; recordId comes from pageInput; outputs are NewStatus and Total
+- **Interactions:** Guard double-submit; no automatic retry after indeterminate Action; later preserve, then explicitly remove all API controls/bindings
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/page-name.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/page-name.txt
new file mode 100644
index 000000000..8b238ef54
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/page-name.txt
@@ -0,0 +1 @@
+Order Tools
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/page.tsx b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/page.tsx
new file mode 100644
index 000000000..5943d7e6c
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/page.tsx
@@ -0,0 +1,11 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: { recordId?: string } };
+const rows = [{ name: 'Order details retained' }, { name: 'Server controls removed' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{rows.map((row) => <p key={row.name}>{row.name}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserve-message.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserve-message.txt
new file mode 100644
index 000000000..6d9829162
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserve-message.txt
@@ -0,0 +1 @@
+Kept existing API bindings by omitting actions on the update.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserve-prompt.txt b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserve-prompt.txt
new file mode 100644
index 000000000..6ce25a447
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserve-prompt.txt
@@ -0,0 +1 @@
+Adjust panel spacing only; preserve both Custom API controls and bindings.
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserved/config.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserved/config.json
new file mode 100644
index 000000000..3ba2cf484
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/preserved/config.json
@@ -0,0 +1,7 @@
+{
+ "model": "gpt-4.1", "dataSources": ["salesorder"],
+ "actionBindings": [
+ { "name": "cnt_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String", "Amount": "Decimal" } },
+ { "name": "cnt_GetOrderSummary", "isFunction": true, "displayName": "Summary", "parameterKinds": { "OrderId": "Guid" } }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/stages/with-api.tsx b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/stages/with-api.tsx
new file mode 100644
index 000000000..c6f20055d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/stages/with-api.tsx
@@ -0,0 +1,55 @@
+import * as React from 'react';
+import { Button, makeStyles, tokens } from '@fluentui/react-components';
+
+type Request = { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } };
+type Result = { ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string } };
+type ActionApi = { executeAction?(request: Request): Promise<Result>; executeFunction?(request: Request): Promise<Result> };
+type Pending = { current: boolean };
+type Setter = (value: string) => void;
+type Props = { dataApi: ActionApi; pageInput?: { recordId?: string } };
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const rows = [{ name: 'Approve', kind: 'Action' }, { name: 'Summary', kind: 'Function' }];
+
+async function approveOrder(api: ActionApi, recordId: string, amount: number, pending: Pending, setError: Setter, setStatus: Setter, setIsSubmitting: (value: boolean) => void) {
+ if (typeof api.executeAction !== 'function') return;
+ if (pending.current || !recordId) return;
+ pending.current = true;
+ setIsSubmitting(true);
+ try {
+ const res = await api.executeAction({
+ name: 'cnt_ApproveOrder',
+ parameters: { Comment: 'Approved', Amount: amount },
+ boundTo: { entityName: 'salesorder', id: recordId },
+ });
+ if (res.indeterminate) { setError('Refresh before retrying; the server may have committed.'); return; }
+ if (!res.ok) { setError(res.error?.message ?? 'Action failed.'); return; }
+ setStatus(String(res.outputs?.NewStatus ?? ''));
+ } catch { setError('Network failed. Try again manually.'); }
+ finally { pending.current = false; setIsSubmitting(false); }
+}
+
+async function readSummary(api: ActionApi, recordId: string, setError: Setter, setTotal: Setter) {
+ if (typeof api.executeFunction !== 'function') return;
+ if (!recordId) return;
+ const res = await api.executeFunction({ name: 'cnt_GetOrderSummary', parameters: { OrderId: recordId } });
+ if (!res.ok) { setError(res.error?.message ?? 'Summary failed.'); return; }
+ setTotal(String(res.outputs?.Total ?? ''));
+}
+
+const GeneratedComponent = (props: Props) => {
+ const { dataApi, pageInput } = props;
+ const recordId = pageInput?.recordId ?? '';
+ const pending = React.useRef(false);
+ const [isSubmitting, setIsSubmitting] = React.useState(false);
+ const [error, setError] = React.useState('');
+ const [status, setStatus] = React.useState('');
+ const [total, setTotal] = React.useState('');
+ const styles = useStyles();
+ return <div className={styles.root}>
+ <p>{rows.map((row) => row.name).join(' / ')}</p>
+ <Button disabled={isSubmitting || !recordId || typeof dataApi.executeAction !== 'function'} onClick={() => void approveOrder(dataApi, recordId, 100, pending, setError, setStatus, setIsSubmitting)}>Approve</Button>
+ <Button disabled={!recordId || typeof dataApi.executeFunction !== 'function'} onClick={() => void readSummary(dataApi, recordId, setError, setTotal)}>Summary</Button>
+ {error && <p role="alert">{error}</p>}<p>{status} {total}</p>
+ </div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/tool-results.json b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/tool-results.json
new file mode 100644
index 000000000..46d1d759e
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/tool-results.json
@@ -0,0 +1,34 @@
+[
+ { "id": "gate-create", "command": "node scripts\\lib\\feature-flags.js custom-api", "result": "enabled", "exitCode": 0 },
+ {
+ "id": "discovery", "command": "node scripts\\list-custom-apis.js https://contoso.crm.dynamics.com --entities salesorder",
+ "result": {
+ "ok": true,
+ "customApis": [
+ { "name": "cnt_ApproveOrder", "displayName": "Approve Order", "isFunction": false, "bindingType": "Entity", "boundEntityLogicalName": "salesorder", "parameterKinds": { "Comment": "String", "Amount": "Decimal" } },
+ { "name": "cnt_GetOrderSummary", "displayName": "Summary", "isFunction": true, "bindingType": "Global", "parameterKinds": { "OrderId": "Guid" } }
+ ]
+ }
+ },
+ { "id": "gate-generate", "command": "node scripts\\lib\\feature-flags.js custom-api", "result": "enabled", "exitCode": 0 },
+ { "id": "write-create", "command": "Write page.tsx", "artifact": "stages/with-api.tsx" },
+ {
+ "id": "create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file page.tsx --data-sources salesorder --actions actions.json --name-file page-name.txt --prompt-file create-prompt.txt --agent-message-file create-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "99999999-9999-4999-8999-999999999999", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ { "id": "gate-preserve", "command": "node scripts\\lib\\feature-flags.js custom-api", "result": "enabled", "exitCode": 0 },
+ { "id": "write-preserve", "command": "Write page.tsx", "artifact": "stages/with-api.tsx" },
+ {
+ "id": "preserve",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx --prompt-file preserve-prompt.txt --agent-message-file preserve-message.txt",
+ "result": { "ok": true, "pageId": "99999999-9999-4999-8999-999999999999", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ },
+ { "id": "gate-clear", "command": "node scripts\\lib\\feature-flags.js custom-api", "result": "enabled", "exitCode": 0 },
+ { "id": "write-clear", "command": "Write page.tsx", "artifact": "page.tsx" },
+ {
+ "id": "clear",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx --actions clear-actions.json --prompt-file clear-prompt.txt --agent-message-file clear-message.txt",
+ "result": { "ok": true, "pageId": "99999999-9999-4999-8999-999999999999", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/workflow-log.md b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/workflow-log.md
new file mode 100644
index 000000000..8437b0d4c
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/24-custom-api-lifecycle/workflow-log.md
@@ -0,0 +1,51 @@
+# Synthetic workflow evidence
+
+Constructed from custom-api.md and SKILL.md Phases 4.6/6, not an agent capture.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\custom-api-lifecycle.
+
+## Phase 1 - Planning
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (synthetic)
+- Unattended default: new or edit -> create new page
+- Solution selection question SKIPPED (code-only flow).
+- The existing server contract declares Action output NewStatus and Function output Total.
+
+## Phase 1 - Builder gate and discovery
+- Command: node scripts\lib\feature-flags.js custom-api
+- Result: enabled, exit 0.
+- Command: node scripts\list-custom-apis.js https://contoso.crm.dynamics.com --entities salesorder
+- Result: discovery in tool-results.json; exact names, kinds, bound entity and parameterKinds.
+- Unattended default: plan approval -> approved
+
+## Phase 4.6 - Re-probe before generation
+- Command: node scripts\lib\feature-flags.js custom-api
+- Result: enabled, exit 0; this is the fresh probe after discovery and planning.
+- actions.json is the bare array matching the plan and discovered metadata.
+
+## Phase 5 - Runtime generation
+- Write page.tsx; actual snapshot is stages/with-api.tsx.
+- Bound Action uses executeAction and host recordId; global Function uses executeFunction without boundTo.
+- Response.ok precedes outputs; errors use sanitized message, the Action has a latch and no indeterminate auto-retry.
+
+## Phase 6 - Create
+- Command: node scripts\genpage-upload.js --code-file page.tsx --actions actions.json --name-file page-name.txt --prompt-file create-prompt.txt --agent-message-file create-message.txt --add-to-sitemap
+- Prompt scope: full User Requirements.
+- Result: create in tool-results.json; created/config.json has both bindings.
+
+## Edit Phase 6 - Preserve
+- Command: node scripts\lib\feature-flags.js custom-api
+- Result: enabled.
+- Write page.tsx; snapshot stages/with-api.tsx remains unchanged.
+- Command: node scripts\genpage-upload.js --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx --prompt-file preserve-prompt.txt --agent-message-file preserve-message.txt
+- Prompt scope: spacing-only edit; --actions omitted, preserved/config.json retains both entries.
+
+## Edit Phase 6 - Explicit clear
+- Command: node scripts\lib\feature-flags.js custom-api
+- Result: enabled.
+- Write page.tsx; final source contains no API calls.
+- Command: node scripts\genpage-upload.js --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx --actions clear-actions.json --prompt-file clear-prompt.txt --agent-message-file clear-message.txt
+- Prompt scope: remove both controls and clear bindings; clear-actions.json is [], cleared/config.json is empty.
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/agent-message.txt b/evals/model-apps/genpage/fixtures/25-solution-package/agent-message.txt
new file mode 100644
index 000000000..6b2a25247
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/agent-message.txt
@@ -0,0 +1 @@
+Created three mock pages for explicit solution packaging.
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/configs/list.json b/evals/model-apps/genpage/fixtures/25-solution-package/configs/list.json
new file mode 100644
index 000000000..b60972885
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/configs/list.json
@@ -0,0 +1,6 @@
+{
+ "model": "gpt-4.1",
+ "connectorBindings": [
+ { "logicalName": "cnt_docs", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline", "dataset": "https://contoso.sharepoint.com/sites/team", "tables": ["77777777-7777-4777-8777-777777777777"], "tableDisplayNames": ["Documents"] }
+ ]
+}
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/configs/metrics.json b/evals/model-apps/genpage/fixtures/25-solution-package/configs/metrics.json
new file mode 100644
index 000000000..1e1fbc1f5
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/configs/metrics.json
@@ -0,0 +1 @@
+{ "model": "gpt-4.1", "connectorBindings": [] }
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/configs/schedule.json b/evals/model-apps/genpage/fixtures/25-solution-package/configs/schedule.json
new file mode 100644
index 000000000..1e1fbc1f5
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/configs/schedule.json
@@ -0,0 +1 @@
+{ "model": "gpt-4.1", "connectorBindings": [] }
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/connectors.json b/evals/model-apps/genpage/fixtures/25-solution-package/connectors.json
new file mode 100644
index 000000000..cdd11b6a2
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/connectors.json
@@ -0,0 +1,3 @@
+[
+ { "logicalName": "cnt_docs", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline", "dataset": "https://contoso.sharepoint.com/sites/team", "tables": ["77777777-7777-4777-8777-777777777777"], "tableDisplayNames": ["Documents"] }
+]
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/fixture.json b/evals/model-apps/genpage/fixtures/25-solution-package/fixture.json
new file mode 100644
index 000000000..dbdb04279
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/fixture.json
@@ -0,0 +1,23 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed three-page packaging and independent bad-identity refusal, not an agent capture. Requests/read-backs are offline wire evidence for the current Phase 6.7 contract.",
+ "contracts": ["plugins/model-apps/skills/genpage/SKILL.md Phase 6.7: Solution Packaging", "plugins/model-apps/scripts/add-page-to-solution.js identity preflight and component ordering"],
+ "toolResults": "tool-results.json",
+ "artifacts": ["prompt.txt", "agent-message.txt", "names/list.txt", "names/schedule.txt", "names/metrics.txt", "connectors.json", "configs/list.json", "configs/schedule.json", "configs/metrics.json"],
+ "packaging": {
+ "solution": "ContosoPages", "solutionId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "appId": "11111111-1111-4111-8111-111111111111",
+ "pages": [
+ { "file": "list.tsx", "pageId": "22222222-2222-4222-8222-222222222222" },
+ { "file": "schedule.tsx", "pageId": "33333333-3333-4333-8333-333333333333" },
+ { "file": "metrics.tsx", "pageId": "44444444-4444-4444-8444-444444444444" }
+ ],
+ "configs": ["configs/list.json", "configs/schedule.json", "configs/metrics.json"],
+ "connectionReferences": ["cnt_docs"],
+ "attempts": [
+ { "event": "package", "outcome": "success", "readback": "readback" },
+ { "event": "bad-identity", "outcome": "refused" }
+ ]
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/genpage-plan.md b/evals/model-apps/genpage/fixtures/25-solution-package/genpage-plan.md
new file mode 100644
index 000000000..5b4f62b0d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/genpage-plan.md
@@ -0,0 +1,86 @@
+# Genpage Plan
+
+## User Requirements
+Build three mock operations pages and package every deployed page with the app and existing document connection reference.
+
+## Working Directory
+D:\work\solution-package
+
+## Plugin Root
+D:\repo\plugins\model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Documents | list.tsx | Mock document list with an existing binding | mock data |
+| Schedule | schedule.tsx | Mock schedule | mock data |
+| Metrics | metrics.tsx | Mock metrics | mock data |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+None.
+
+## Connector Bindings
+| Logical Name | Connector Id | Dataset | Tables (GUIDs) | Table Display Names | Operations | Fields | Parameters | Response |
+|--------------|--------------|---------|----------------|---------------------|------------|--------|------------|----------|
+| cnt_docs | /providers/Microsoft.PowerApps/apis/shared_sharepointonline | https://contoso.sharepoint.com/sites/team | 77777777-7777-4777-8777-777777777777 | Documents | | Title (string) | | |
+
+## Custom API Bindings
+No custom API bindings.
+
+## Solution Packaging
+- Package into solution: true
+- Solution: ContosoPages
+
+## Design Preferences
+Responsive mock cards. This fixture isolates packaging, not connector execution.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Documents | 7-responsive-cards.tsx | Mock cards |
+| Schedule | 7-responsive-cards.tsx | Mock cards |
+| Metrics | 7-responsive-cards.tsx | Mock cards |
+
+## Per-Page Specifications
+### Documents
+- **File:** list.tsx
+- **Purpose:** Mock document list with an existing binding
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Document titles
+- **Components:** Text
+- **Layout:** Responsive cards
+- **Data Binding:** Inline rows; existing cnt_docs binding carried into config
+- **Interactions:** None
+
+### Schedule
+- **File:** schedule.tsx
+- **Purpose:** Mock schedule
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Schedule labels
+- **Components:** Text
+- **Layout:** Responsive cards
+- **Data Binding:** Inline mock rows
+- **Interactions:** None
+
+### Metrics
+- **File:** metrics.tsx
+- **Purpose:** Mock metrics
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** Summary labels
+- **Components:** Text
+- **Layout:** Responsive cards
+- **Data Binding:** Inline mock rows
+- **Interactions:** None
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/list.tsx b/evals/model-apps/genpage/fixtures/25-solution-package/list.tsx
new file mode 100644
index 000000000..d4d89a4c1
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/list.tsx
@@ -0,0 +1,11 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Project notes' }, { name: 'Release checklist' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{rows.map((row) => <p key={row.name}>{row.name}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/metrics.tsx b/evals/model-apps/genpage/fixtures/25-solution-package/metrics.tsx
new file mode 100644
index 000000000..929d8fdb9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/metrics.tsx
@@ -0,0 +1,11 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Ready', count: 3 }, { name: 'Waiting', count: 2 }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{rows.map((row) => <p key={row.name}>{row.name}: {row.count}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/names/list.txt b/evals/model-apps/genpage/fixtures/25-solution-package/names/list.txt
new file mode 100644
index 000000000..802e07aa9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/names/list.txt
@@ -0,0 +1 @@
+Documents
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/names/metrics.txt b/evals/model-apps/genpage/fixtures/25-solution-package/names/metrics.txt
new file mode 100644
index 000000000..553fb61e5
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/names/metrics.txt
@@ -0,0 +1 @@
+Metrics
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/names/schedule.txt b/evals/model-apps/genpage/fixtures/25-solution-package/names/schedule.txt
new file mode 100644
index 000000000..9d236523a
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/names/schedule.txt
@@ -0,0 +1 @@
+Schedule
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/prompt.txt b/evals/model-apps/genpage/fixtures/25-solution-package/prompt.txt
new file mode 100644
index 000000000..04353cf23
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/prompt.txt
@@ -0,0 +1 @@
+Build three mock operations pages and package every deployed page with the app and existing document connection reference.
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/schedule.tsx b/evals/model-apps/genpage/fixtures/25-solution-package/schedule.tsx
new file mode 100644
index 000000000..d415b6304
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/schedule.tsx
@@ -0,0 +1,11 @@
+import { makeStyles, tokens } from '@fluentui/react-components';
+type Props = { pageInput?: Record<string, unknown> };
+const rows = [{ name: 'Planning' }, { name: 'Review' }];
+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });
+const GeneratedComponent = (props: Props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{rows.map((row) => <p key={row.name}>{row.name}</p>)}</div>;
+};
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/tool-results.json b/evals/model-apps/genpage/fixtures/25-solution-package/tool-results.json
new file mode 100644
index 000000000..78ca92e5c
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/tool-results.json
@@ -0,0 +1,67 @@
+[
+ {
+ "id": "deploy-list",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file list.tsx --connectors connectors.json --name-file names\\list.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "appId": "11111111-1111-4111-8111-111111111111", "pageId": "22222222-2222-4222-8222-222222222222", "updated": false }
+ },
+ {
+ "id": "deploy-schedule",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file schedule.tsx --name-file names\\schedule.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "appId": "11111111-1111-4111-8111-111111111111", "pageId": "33333333-3333-4333-8333-333333333333", "updated": false }
+ },
+ {
+ "id": "deploy-metrics",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file metrics.tsx --name-file names\\metrics.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --model gpt-4.1 --add-to-sitemap",
+ "result": { "ok": true, "appId": "11111111-1111-4111-8111-111111111111", "pageId": "44444444-4444-4444-8444-444444444444", "updated": false }
+ },
+ {
+ "id": "solution",
+ "command": "node scripts\\provision-solution.js https://contoso.crm.dynamics.com ContosoPages Contoso",
+ "result": { "ok": true, "uniqueName": "ContosoPages", "solutionId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", "publisherPrefix": "cnt" }
+ },
+ {
+ "id": "package",
+ "command": "node scripts\\add-page-to-solution.js https://contoso.crm.dynamics.com ContosoPages 11111111-1111-4111-8111-111111111111 --page-ids 22222222-2222-4222-8222-222222222222,33333333-3333-4333-8333-333333333333,44444444-4444-4444-8444-444444444444 --connection-refs cnt_docs",
+ "requests": [
+ { "method": "GET", "path": "EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode", "response": { "status": 200, "data": { "ObjectTypeCode": 10401 } } },
+ { "method": "GET", "path": "EntityDefinitions(LogicalName='connectionreference')?$select=ObjectTypeCode", "response": { "status": 200, "data": { "ObjectTypeCode": 10402 } } },
+ { "method": "GET", "path": "connectionreferences?$filter=connectionreferencelogicalname eq 'cnt_docs'&$select=connectionreferenceid&$top=1", "response": { "status": 200, "data": { "value": [{ "connectionreferenceid": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" }] } } },
+ { "method": "POST", "path": "AddSolutionComponent", "body": { "ComponentId": "11111111-1111-4111-8111-111111111111", "ComponentType": 80, "SolutionUniqueName": "ContosoPages", "AddRequiredComponents": true }, "response": { "status": 204, "data": {} } },
+ { "method": "POST", "path": "AddSolutionComponent", "body": { "ComponentId": "22222222-2222-4222-8222-222222222222", "ComponentType": 10401, "SolutionUniqueName": "ContosoPages", "AddRequiredComponents": true }, "response": { "status": 204, "data": {} } },
+ { "method": "POST", "path": "AddSolutionComponent", "body": { "ComponentId": "33333333-3333-4333-8333-333333333333", "ComponentType": 10401, "SolutionUniqueName": "ContosoPages", "AddRequiredComponents": true }, "response": { "status": 204, "data": {} } },
+ { "method": "POST", "path": "AddSolutionComponent", "body": { "ComponentId": "44444444-4444-4444-8444-444444444444", "ComponentType": 10401, "SolutionUniqueName": "ContosoPages", "AddRequiredComponents": true }, "response": { "status": 204, "data": {} } },
+ { "method": "POST", "path": "AddSolutionComponent", "body": { "ComponentId": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", "ComponentType": 10402, "SolutionUniqueName": "ContosoPages", "AddRequiredComponents": false }, "response": { "status": 204, "data": {} } }
+ ],
+ "result": {
+ "ok": true,
+ "added": [
+ { "type": "appmodule", "id": "11111111-1111-4111-8111-111111111111" },
+ { "type": "uxagentproject", "id": "22222222-2222-4222-8222-222222222222" },
+ { "type": "uxagentproject", "id": "33333333-3333-4333-8333-333333333333" },
+ { "type": "uxagentproject", "id": "44444444-4444-4444-8444-444444444444" },
+ { "type": "connectionreference", "logicalName": "cnt_docs", "id": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" }
+ ]
+ }
+ },
+ {
+ "id": "readback",
+ "command": "node scripts\\dataverse-request.js https://contoso.crm.dynamics.com GET \"solutioncomponents?$filter=_solutionid_value eq aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa&$select=objectid,componenttype\"",
+ "result": {
+ "ok": true, "data": { "value": [
+ { "objectid": "11111111-1111-4111-8111-111111111111", "componenttype": 80 },
+ { "objectid": "22222222-2222-4222-8222-222222222222", "componenttype": 10401 },
+ { "objectid": "33333333-3333-4333-8333-333333333333", "componenttype": 10401 },
+ { "objectid": "44444444-4444-4444-8444-444444444444", "componenttype": 10401 },
+ { "objectid": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", "componenttype": 10402 },
+ { "objectid": "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "componenttype": 62 }
+ ] }
+ }
+ },
+ {
+ "id": "bad-identity",
+ "command": "node scripts\\add-page-to-solution.js https://contoso.crm.dynamics.com ContosoPages bad-app-id --page-ids 22222222-2222-4222-8222-222222222222,33333333-3333-4333-8333-333333333333,44444444-4444-4444-8444-444444444444 --connection-refs cnt_docs",
+ "requests": [],
+ "result": { "ok": false, "error": "Not a GUID: app id 'bad-app-id'. Nothing was added to ContosoPages." },
+ "userMessage": "Not a GUID: app id 'bad-app-id'. Nothing was added to ContosoPages."
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/25-solution-package/workflow-log.md b/evals/model-apps/genpage/fixtures/25-solution-package/workflow-log.md
new file mode 100644
index 000000000..756487203
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/25-solution-package/workflow-log.md
@@ -0,0 +1,35 @@
+# Synthetic workflow evidence
+
+Constructed from SKILL.md Phase 6.7, not an agent capture. The malformed-id control is independent and writes nothing.
+
+## Phase 0 - Working directory
+Working directory created: D:\work\solution-package.
+
+## Phase 1 - Planning
+- node --version -> v20.20.2
+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)
+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]
+- Unattended default: interaction mode -> unattended (synthetic)
+- Unattended default: new or edit -> create new pages
+- Solution selection question SKIPPED for create (code-only flow).
+- Unattended default: plan approval -> approved, including explicit optional packaging into ContosoPages.
+
+## Phase 6 - Deployment
+- Command: node scripts\genpage-upload.js --code-file list.tsx --connectors connectors.json --name-file names\list.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --add-to-sitemap
+- Command: node scripts\genpage-upload.js --code-file schedule.tsx --name-file names\schedule.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --add-to-sitemap
+- Command: node scripts\genpage-upload.js --code-file metrics.tsx --name-file names\metrics.txt --prompt-file prompt.txt --agent-message-file agent-message.txt --add-to-sitemap
+- Prompt scope: full User Requirements.
+- Results: three associated deployed page ids in tool-results.json.
+
+## Phase 6.7 - Packaging
+- Command: node scripts\provision-solution.js https://contoso.crm.dynamics.com ContosoPages Contoso
+- Result: target unique name and solution id in tool-results.json.
+- Command: node scripts\add-page-to-solution.js https://contoso.crm.dynamics.com ContosoPages 11111111-1111-4111-8111-111111111111 --page-ids 22222222-2222-4222-8222-222222222222,33333333-3333-4333-8333-333333333333,44444444-4444-4444-8444-444444444444 --connection-refs cnt_docs
+- Resolve both environment-specific component types and the connection reference before any write.
+- Add app first, every page explicitly, then cnt_docs; read-back confirms all direct components plus the pulled sitemap dependency.
+- Command: node scripts\dataverse-request.js https://contoso.crm.dynamics.com GET "solutioncomponents?$filter=_solutionid_value eq aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa&$select=objectid,componenttype"
+- Result: readback in tool-results.json.
+
+## Phase 6.7 - Invalid identity refusal control
+- Command: node scripts\add-page-to-solution.js https://contoso.crm.dynamics.com ContosoPages bad-app-id --page-ids 22222222-2222-4222-8222-222222222222,33333333-3333-4333-8333-333333333333,44444444-4444-4444-8444-444444444444 --connection-refs cnt_docs
+- Result: ok:false, Not a GUID; the error is surfaced verbatim. Zero requests and zero writes.
diff --git a/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.md b/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.md
index 31451bdcc..1b826d78b 100644
--- a/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.md
+++ b/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.md
@@ -31,6 +31,10 @@ task
No connector bindings.
+## Custom API Bindings
+
+No custom API bindings.
+
## Design Preferences
- Styling: Fluent UI V9 Cards in a 3-column horizontal layout. Priority color-coded badges: green = Low, blue = Normal, orange = High, red = Critical. Clean column headers with icons (ClipboardTaskRegular, PlayRegular, CheckmarkCircleRegular). Neutral background per column with subtle border.
- Features: Drag-and-drop between columns using native HTML5 DnD (no external library — no react-dnd, @dnd-kit, or react-beautiful-dnd). Status updates persist to Dataverse via dataApi.updateRow on drop. Loading, empty, and error states per column. Window cache (window.__genpage_tasks_v1) for list data. Display task subject, priority badge, due date (scheduledend), and owner name (ownerid) on each card.
diff --git a/evals/model-apps/genpage/fixtures/README.md b/evals/model-apps/genpage/fixtures/README.md
index 21ee34821..0566cd9f5 100644
--- a/evals/model-apps/genpage/fixtures/README.md
+++ b/evals/model-apps/genpage/fixtures/README.md
@@ -1,9 +1,9 @@
-# Layer 2 fixtures
+# Genpage replay fixtures
Each subdirectory is a fixture for one eval in `../evals.json`. The Layer 2
runner (`../run-layer-2.js`) grades every `.tsx` in a fixture against the
-`common_code_assertions` and the eval's `Phase 5 (Page Builder):` /
-`Phase 5b:` expectations.
+`common_code_assertions` and the eval's `Phase 5` / `5a` / `5b` / `5c` expectations.
+The offline runners do not execute the skill or any logged command.
## Layout
@@ -27,8 +27,14 @@ digits are parsed as the eval id; the slug is purely cosmetic.
- All `.tsx` files in the fixture root are checked.
- A file literally named `RuntimeTypes.ts` (or `.tsx`) is excluded — it's
schema, not generated output.
-- `workflow-log.md`, `genpage-plan.md`, `entity-creation-log.md` are ignored
- by Layer 2 (Layer 1 will read them).
+- Layer 1 reads the plans/logs. Layer 2 also receives fixture metadata and can
+ inspect declared before/after TSX, worker/API lifecycle and refusal evidence.
+- `genpage-entity-creation-log.md` is the current log name; the loader intentionally
+ falls back to the historical `entity-creation-log.md` **only when the current file
+ is absent**, not when it is empty. An old log must not supply transactions for a fresh run.
+- A current synthetic `fixture.json` declares contract version 2, provenance,
+ source skill/reference sections, ordered `tool-results.json` and artifact paths.
+ Nested snapshots are evidence, not additional generated pages.
## How to capture a real fixture from /genpage
@@ -52,8 +58,7 @@ The script:
failing assertions for triage
Flags:
-- `--force` — overwrite an existing fixture (use when re-capturing after
- agent changes)
+- `--force` — overwrite a trial fixture; use a **new slug** for a historical capture
- `--skip-verify` — capture only, skip the runner sweep (rare)
Manual fallback if the helper doesn't fit your scenario:
@@ -63,65 +68,67 @@ Manual fallback if the helper doesn't fit your scenario:
3. Skip `package.json`, `genpage.d.ts`, `node_modules/`, `*.log`
4. Run `node ../run-layer-1.js --eval <id>` and `../run-layer-2.js --eval <id>`
-## How to regenerate fixtures
+## Updating a contract
-When the page-builder rules change, expected outputs change too. Bulk
-regeneration:
+Do not regenerate historical captures in place. Label their contract in
+`contracts.json`, create a new directory under a fresh slug for new evidence,
+and register its id in `evals.json`. New contract fixtures here are synthetic
+and explicitly say so; they cite current public skill/reference sections.
+The capture helper does not collect the new JSON/text transport snapshots,
+so structured synthetic evidence is packaged explicitly rather than advertised
+as a captured run.
-1. Run all evals against the new agent.
-2. Replace fixture contents wholesale (no incremental diffs — the agent
- may legitimately restructure the file).
-3. Run `node run-layer-2.js` and confirm all fixtures pass.
-4. Commit the regeneration as a single PR titled
- `Regenerate Layer 2 fixtures for <rule version>`.
+Two rules for evidence files:
+
+- **Byte-compared text is `.txt`.** Prompt, agent-message and page-name files
+ are compared byte for byte with `fixture.json`, so `.gitattributes` checks
+ every `*.txt` out verbatim; a Windows checkout would otherwise turn LF into CRLF.
+- **A deliberately broken page is not a `.tsx`.** The plugin's corpus tests
+ require every committed `.tsx` to be a valid page, so store a truncated or
+ rejected worker output under another extension (see
+ `23-worker-completeness/attempts/truncated.txt`).
## Current state
-This directory ships with 10 fixtures — 6 synthetic (hand-built, v2.2-compliant)
-and 4 real captures (3 from sessions under the v2.2 plugin):
+This directory has **20 fixtures, 26 top-level TSX files and 18 represented
+prompt IDs**. All are green under both runners. Directories listed in
+`contracts.json` are historical contract-1 evidence; every other directory is a
+current contract-2 synthetic. Registered prompts with no fixture:
+**3, 6, 8, 9, 12, 14, 16**. `evals/model-apps/tests/eval-coverage-contract.test.js`
+fails when these figures, or the reasons recorded for the missing prompts, fall out
+of step with the fixtures.
| Fixture | Eval | Source | State | Shape covered |
|---------|-----:|--------|-------|---------------|
-| `1-account-card-gallery/` | 1 | Synthetic | green | Dataverse single page, click-to-open Xrm.Navigation, window cache |
-| `2-mock-dashboard/` | 2 | Synthetic (from sample 8) | green | Mock data, D3 charts, no entity work |
-| `2-mock-dashboard-real/` | 2 | Real capture (2026-05-20, pre-v2.2-spec) | red | Mock data — pre-spec-tightening capture; known workflow-log compactness gaps |
-| `4-case-wizard/` | 4 | Synthetic | green | Multi-step wizard, two Dataverse entities, dataApi.createRow with @odata.bind |
-| `5-kanban-task-board/` | 5 | Real capture (2026-05-21, pre-v2.2-spec) | mostly green | Native HTML5 DnD on `task` entity — Layer 2 fully green; Layer 1 pre-spec workflow-log gaps |
-| `7-job-candidates-new-entities/` | 7 | Synthetic | green | New entities + lookup + choice column + sample data + solution selection |
-| `11-recruitment-multi-page/` | 11 | Synthetic | green | Multi-page (3 pages), parallel page-builder dispatch, PAGEREF cross-nav, Phase 6.5 resolution |
-| `11-recruitment-pages-real/` | 11 | Real capture (2026-05-21, v2.2-spec) | red (Custom API section only) | Same shape as synthetic — first real capture validated under tightened spec; predates the enforced `## Custom API Bindings` section (see below) |
-| `13-contact-localization/` | 13 | Synthetic | green | Localization (en-US / ar-SA / fr-FR), RTL, logical CSS properties |
-| `15-support-tickets-real/` | 15 | Real capture (2026-05-26, v2.2-spec) | red (Custom API section only) | New entity + choice columns + sample data + check-auth retry flow; predates the enforced `## Custom API Bindings` section (see below) |
-
-**Synthetic fixtures** are hand-built to be v2.2-compliant — they exercise
-the relevant code paths and serve as green-path regression tests for the
-runners. All Layer 1 + Layer 2 assertions pass or skip.
-
-**Real captures** validate the runners against actual `/genpage` output:
-
-- The two real captures for eval 11 and eval 15 were captured after the
- v2.2 planner-spec tightening landed, and both layers exited 0 against
- them until the `## Custom API Bindings` section was enforced; that one
- Layer 1 check is now their only failure.
-- The two **red real captures** (eval 2, eval 5) were captured before the
- spec tightening propagated to the agent's session. They have known
- workflow-log compactness gaps documented in their fixture READMEs; they
- go green when re-captured under the tightened spec.
-
-The mix gives a green-path regression test (synthetic) + a drift-detection
-example (red real captures) + proof-of-life that the v2.2 spec produces
-passing output (the eval 11 and 15 captures, which pass everything except
-the later-enforced Custom API section).
-
-**Captured plans predate `## Custom API Bindings` enforcement.**
-`references/plan-schema.md` has always required that section, but the
-Layer 1 validator only started enforcing it with [#585], after every
-fixture here was made. The synthetic and authored plans gained the exact
-no-bindings sentinel (`No custom API bindings.`, before
-`## Design Preferences`) — none of those pages calls a Custom API. The four
-**real captures were deliberately not edited**: a capture is evidence of
-what the planner produced, and rewriting it to match today's schema would
-falsify it (the same rule the upload-transport assertions follow). Each now
-also fails that one Layer 1 check; re-capturing clears it.
-
-[#585]: https://github.com/microsoft/power-platform-skills/issues/585
+| `1-account-card-gallery/` | 1 | Historical synthetic | green | Dataverse single page, click-to-open Xrm.Navigation, window cache |
+| `2-mock-dashboard/` | 2 | Historical synthetic (from sample 8) | green | Mock data, D3 charts, no entity work |
+| `2-mock-dashboard-real/` | 2 | Historical capture | green | Mock data; historical workflow/transport |
+| `4-case-wizard/` | 4 | Historical synthetic | green | Multi-step wizard, two Dataverse entities, dataApi.createRow with @odata.bind |
+| `5-kanban-task-board/` | 5 | Historical capture | green | Native HTML5 DnD on `task` |
+| `7-job-candidates-new-entities/` | 7 | Historical synthetic | green | New entities + lookup + choice column + sample data + solution selection |
+| `11-recruitment-multi-page/` | 11 | Historical synthetic | green | Authored legacy navigation; no current before/after fix-up proof |
+| `11-recruitment-pages-real/` | 11 | Historical capture | green | Resolved navigation checked against the capture's deployment map |
+| `13-contact-localization/` | 13 | Historical synthetic | green | Localization (en-US / ar-SA / fr-FR), RTL, logical CSS properties |
+| `15-support-tickets-real/` | 15 | Historical capture | green | New entity/choices and auth retry |
+| `17-weather-mock-data/` | 17 | Historical synthetic | green | Mock weather, no discovery |
+| `18-sharepoint-connectors/` | 18 | Historical synthetic | green | Connector-backed source and discovery |
+| `19-add-weather-connector/` | 19 | Historical synthetic | green | Add-from-none edit compatibility |
+| `10-auth-timeout-halt/` | 10 | Current synthetic | green | Associated timeout results, one retry/advice, halt with no TSX/mutation |
+| `20-upload-preservation/` | 20 | Current synthetic | green | Exact create file transport; independent edit read-backs; quote refusal |
+| `21-discovery-failure/` | 21 | Current synthetic | green | Unreadable discovery is needs_input, never setup/upload; no generated TSX |
+| `22-navigation-contract/` | 22 | Current synthetic | green | Actual before/after source, optional calls/overrides/escaped keys/Unicode terminators, affected-only upload |
+| `23-worker-completeness/` | 23 | Current synthetic | green | Failed production gate blocks upload until fresh complete regeneration |
+| `24-custom-api-lifecycle/` | 24 | Current synthetic | green | Bound Action/global Function discovery, re-probe, runtime, preserve and clear |
+| `25-solution-package/` | 25 | Current synthetic | green | Every deployed page, dynamic component types, app-first writes, read-back and invalid-id refusal |
+
+Historical captures remain compatibility/parser evidence, not proof of today's
+file transport, binding preservation or full skill compliance. Their current
+plans already contain the Custom API no-bindings section. Capture-local READMEs
+can contain capture-era counts/claims; the inventory above is the current roster.
+
+Expected failures belong in discriminating scorer unit tests, or in an explicit
+refusal/recovery trace that satisfies its declared outcome. The corpus is never
+permanently red: both full runners must exit 0. Refusal fixtures prove a failed
+gate and zero generation/mutations; recovery fixtures retain rejected snapshots
+only as nested evidence. Green replay does not mean an agent, TypeScript build,
+React UI, live connector/API, hosted upload or solution import was exercised.
diff --git a/evals/model-apps/genpage/fixtures/contracts.json b/evals/model-apps/genpage/fixtures/contracts.json
new file mode 100644
index 000000000..b7d6a6006
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/contracts.json
@@ -0,0 +1,15 @@
+{
+ "1-account-card-gallery": { "contractVersion": 1, "provenance": "historical" },
+ "2-mock-dashboard": { "contractVersion": 1, "provenance": "historical" },
+ "2-mock-dashboard-real": { "contractVersion": 1, "provenance": "historical" },
+ "4-case-wizard": { "contractVersion": 1, "provenance": "historical" },
+ "5-kanban-task-board": { "contractVersion": 1, "provenance": "historical" },
+ "7-job-candidates-new-entities": { "contractVersion": 1, "provenance": "historical" },
+ "11-recruitment-multi-page": { "contractVersion": 1, "provenance": "historical", "navigationPhase": "legacy-authored" },
+ "11-recruitment-pages-real": { "contractVersion": 1, "provenance": "historical", "navigationPhase": "resolved" },
+ "13-contact-localization": { "contractVersion": 1, "provenance": "historical" },
+ "15-support-tickets-real": { "contractVersion": 1, "provenance": "historical" },
+ "17-weather-mock-data": { "contractVersion": 1, "provenance": "historical" },
+ "18-sharepoint-connectors": { "contractVersion": 1, "provenance": "historical" },
+ "19-add-weather-connector": { "contractVersion": 1, "provenance": "historical" }
+}
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index ff413f700..ef87cf50a 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -15,6 +15,14 @@
const path = require('node:path');
const { pageFileProblems } = require('../../../../plugins/model-apps/scripts/lib/page-file-targets.js');
+const { currentContract, workflowCalls, isAuth, isDiscovery, authGateProblems, discoveryProblems, refusalProblems } = require('./workflow-evidence.js');
+const { gradeEvidence } = require('./evidence-utils.js');
+const { navigationProblems } = require('./navigation-contract.js');
+const { workerProblems } = require('./worker-contract.js');
+const { uploadProblems, uploadPreservationProblems } = require('./upload-contract.js');
+const { planSection, findMarkdownTable, parseMarkdownRows } = require('./plan-evidence.js');
+const { customApiProblems, customApiGateProblems } = require('./custom-api-contract.js');
+const { packagingProblems, isPackaging } = require('./packaging-contract.js');
function fail(reason) { return { status: 'fail', reason }; }
function pass() { return { status: 'pass', reason: '' }; }
@@ -55,6 +63,14 @@ function isEditFlowFixture(fixture) {
return Boolean(fixture && fixture.genpageEditPlan && !fixture.genpagePlan);
}
+function beforePlanningRefusal(fixture) {
+ return fixture.manifest?.expectedOutcome === 'refused' && fixture.manifest.refusal?.stage === 'discovery';
+}
+
+function checkProblems(problems) {
+ return problems.length ? fail(problems[0]) : pass();
+}
+
function logHas(log, pattern) {
return Boolean(log) && new RegExp(pattern, 'mi').test(log);
}
@@ -89,25 +105,6 @@ function isUnattendedLog(log) {
);
}
-function planSection(plan, heading) {
- // Returns text under "## <heading>" up to the next "## " heading or end-of-file.
- // Implemented as line scan to avoid JS regex \Z limitation.
- if (!plan) return null;
- const lines = plan.split('\n');
- const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const startRe = new RegExp(`^##\\s+${escaped}\\s*$`, 'i');
- let i = 0;
- while (i < lines.length && !startRe.test(lines[i])) i++;
- if (i >= lines.length) return null;
- i++; // skip the heading line
- const out = [];
- while (i < lines.length && !/^##\s/.test(lines[i])) {
- out.push(lines[i]);
- i++;
- }
- return out.join('\n').trim();
-}
-
function entitiesNeedCreating(plan) {
const section = planSection(plan, 'Entity Creation Required');
if (!section) return false;
@@ -203,37 +200,6 @@ function parsePlanSections(plan) {
return sections;
}
-function findMarkdownTable(sectionText, requiredColumns) {
- const lines = sectionText.split(/\r?\n/);
- for (let i = 0; i < lines.length; i++) {
- if (!/^\s*\|.*\|\s*$/.test(lines[i])) continue;
- const headers = lines[i]
- .split('|')
- .slice(1, -1)
- .map((header) => header.trim().toLowerCase());
- const hasRequired = requiredColumns.every((column) => headers.includes(column.toLowerCase()));
- if (hasRequired) return { lineIndex: i, headers, lines: lines.slice(i) };
- }
- return null;
-}
-
-function parseMarkdownRows(sectionText, requiredColumns) {
- const table = findMarkdownTable(sectionText, requiredColumns);
- if (!table) return [];
- const rows = [];
- for (const line of table.lines.slice(2)) {
- if (!/^\s*\|.*\|\s*$/.test(line)) break;
- const cells = line.split('|').slice(1, -1).map((cell) => cell.trim());
- if (cells.length === 0 || cells.every((cell) => cell === '')) continue;
- const row = {};
- for (let i = 0; i < table.headers.length; i++) {
- row[table.headers[i]] = cells[i] || '';
- }
- rows.push(row);
- }
- return rows;
-}
-
function workingDirectoryOf(plan) {
const section = planSection(plan, 'Working Directory');
return section ? section.split(/\r?\n/)[0].trim() : '';
@@ -271,12 +237,20 @@ function parsePerPageBlocks(sectionText) {
return blocks;
}
-function hasBulletField(lines, field) {
+function bulletFieldValues(lines, field) {
const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Some fixture plans use the required field as a parent bullet whose details
// are nested on following lines. The schema contract requires the field to be
// present; it does not require single-line prose after the colon.
- return lines.some((line) => new RegExp(`^\\s*[-*]\\s+\\*\\*${escaped}:\\*\\*`, 'i').test(line));
+ const pattern = new RegExp(`^\\s*[-*]\\s+\\*\\*${escaped}:\\*\\*\\s*(.*?)\\s*$`, 'i');
+ return lines.flatMap((line) => {
+ const match = pattern.exec(line);
+ return match ? [match[1]] : [];
+ });
+}
+
+function hasBulletField(lines, field) {
+ return bulletFieldValues(lines, field).length > 0;
}
function validateEnvironment(sectionText, errors) {
@@ -415,6 +389,14 @@ function validateGenpagePlanSchema(plan) {
errors.push(schemaError('missing-per-page-field', `page "${pageName}" missing required per-page field "${field}"`, { section: 'Per-Page Specifications', page: pageName, field }));
}
}
+ // Dispatch reads the Pages table, while the builder reads its per-page File. A disagreement
+ // can overwrite a sibling or leave the declared target unwritten even though both names are safe.
+ const files = bulletFieldValues(block.lines, 'File');
+ if (files.length && (files.length !== 1 || files[0] !== row.file)) {
+ errors.push(schemaError('page-file-mismatch', `page "${pageName}" must have exactly one File matching ## Pages: expected "${row.file}", got ${JSON.stringify(files)}`, {
+ section: 'Per-Page Specifications', page: pageName, expectedFile: row.file, files,
+ }));
+ }
}
for (const pageName of blocks.keys()) {
@@ -530,6 +512,7 @@ WORKFLOW_ASSERTIONS.set(
'Phase 1 (Planner): genpage-plan.md ALWAYS contains \'Solution:\' and \'Publisher Prefix:\' lines in ## Environment; default fallback is \'Solution: Default\' + \'Publisher Prefix: new\' for code-only flows',
({ fixture }) => {
const plan = fixture.genpagePlan;
+ if (beforePlanningRefusal(fixture)) return skip('discovery refused before a create plan was authored');
if (isEditFlowFixture(fixture)) return skip('edit flow — no genpage-plan.md is produced');
if (!plan) return fail('genpage-plan.md not present in fixture');
const env = planSection(plan, 'Environment');
@@ -547,6 +530,7 @@ WORKFLOW_ASSERTIONS.set(
const log = fixture.workflowLog;
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
+ if (beforePlanningRefusal(fixture)) return skip('discovery refused before solution selection');
if (isEditFlowFixture(fixture)) return skip('edit flow — the solution question belongs to the create flow');
if (!plan) return fail('no genpage-plan.md');
const needsMetadata = entitiesNeedCreating(plan) || newAppNeeded(plan);
@@ -587,6 +571,7 @@ WORKFLOW_ASSERTIONS.set(
({ fixture }) => {
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
+ if (beforePlanningRefusal(fixture)) return skip('discovery refused before plan approval');
if (isEditFlowFixture(fixture)) return skip('edit flow — approval is presented from genpage-edit-plan.md');
if (isUnattendedLog(log)) {
if (/EnterPlanMode called|ExitPlanMode called|AskUserQuestion:/i.test(log)) {
@@ -609,6 +594,7 @@ WORKFLOW_ASSERTIONS.set(
WORKFLOW_ASSERTIONS.set(
'Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md',
({ fixture }) => {
+ if (beforePlanningRefusal(fixture)) return skip('discovery refused before a create plan was authored');
if (isEditFlowFixture(fixture)) return skip('edit flow — no genpage-plan.md is produced');
if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
const errors = validateGenpagePlanSchema(fixture.genpagePlan);
@@ -628,22 +614,11 @@ WORKFLOW_ASSERTIONS.set(
const log = fixture.workflowLog;
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
+ if (beforePlanningRefusal(fixture)) return skip('discovery refused before entity planning');
if (isEditFlowFixture(fixture)) return skip('edit flow — entity creation belongs to the create flow');
if (!plan) return fail('no genpage-plan.md');
if (!entitiesNeedCreating(plan)) return skip('no entity creation required');
- if (!/check-auth\.js/.test(log)) return fail('check-auth.js not invoked');
- // Order against the FIRST actual entity-creation script invocation, not
- // against a meta-list mention of the entity-builder agent name. Meta-lists
- // like "## Agents Invoked" can name the agent before the actual commands.
- const idxCheck = log.search(/check-auth\.js/);
- const idxFirstScript = log.search(/\b(provision-entities\.js|create-table\.js|add-column\.js|create-relationship\.js|create-record\.js)\b/);
- if (idxFirstScript !== -1 && idxFirstScript < idxCheck) {
- return fail('entity creation script invoked before check-auth.js');
- }
- if (!/(?:^|\s|"|,|{)ok\s*[:=]\s*"?true"?/i.test(log)) {
- return fail('check-auth.js did not return ok:true (or not logged)');
- }
- return pass();
+ return checkProblems(authGateProblems(fixture, { required: true }));
}
);
@@ -652,6 +627,10 @@ WORKFLOW_ASSERTIONS.set(
({ fixture }) => {
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
+ if (fixture.manifest?.expectedOutcome === 'refused') {
+ return checkProblems(refusalProblems(fixture));
+ }
+ if (currentContract(fixture)) return gradeEvidence(uploadProblems, fixture);
if (!UPLOAD_CMD.test(log)) return fail('no upload invocation recorded');
// `--prompt` also matches `--prompt-file`, which is the intent: what is asserted is that a
// prompt was recorded and scoped, not which flag carried it.
@@ -664,6 +643,7 @@ WORKFLOW_ASSERTIONS.set(
'Prefix discipline — plan format: Every name in `## Entity Creation Required` (table headings, column Suffix values, choice column suffixes, relationship Lookup Suffix values) is a bare suffix matching `^[a-z][a-z0-9]+$`. No value contains an underscore or a prefix. The prefix lives only in `## Environment` → `Publisher Prefix:`.',
({ fixture }) => {
const plan = fixture.genpagePlan;
+ if (beforePlanningRefusal(fixture)) return skip('discovery refused before entity planning');
if (isEditFlowFixture(fixture)) return skip('edit flow — no ## Entity Creation Required section exists');
if (!plan) return fail('no genpage-plan.md');
const section = planSection(plan, 'Entity Creation Required');
@@ -685,12 +665,12 @@ WORKFLOW_ASSERTIONS.set(
);
WORKFLOW_ASSERTIONS.set(
- 'Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).',
+ 'Prefix discipline — resolved names: For every operation in `genpage-entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).',
({ fixture }) => {
const plan = fixture.genpagePlan;
const log = fixture.entityCreationLog;
if (!plan) return skip('no genpage-plan.md');
- if (!log) return skip('no entity-creation-log.md');
+ if (!log) return skip('no genpage-entity-creation-log.md (or its legacy entity-creation-log.md alias)');
const env = planSection(plan, 'Environment');
if (!env) return fail('plan has no ## Environment section');
// Allow optional list markers (`- Publisher Prefix: new` or `* Publisher Prefix: new`).
@@ -726,6 +706,74 @@ WORKFLOW_ASSERTIONS.set(
const PHASE_EXPECTATIONS = new Map();
+const PACKAGING_ASSERTION = 'Phase 6.7: Packaging uses every deployed page id, the approved solution and discovered component types; invalid identities refuse before writes and results agree with read-back';
+PHASE_EXPECTATIONS.set(PACKAGING_ASSERTION, ({ fixture }) => gradeEvidence(packagingProblems, fixture));
+WORKFLOW_ASSERTIONS.set(PACKAGING_ASSERTION, ({ fixture }) => {
+ const section = planSection(fixture.genpagePlan, 'Solution Packaging');
+ if (!fixture.manifest?.packaging && !/Package into solution:\s*true\b/i.test(section || '') && !workflowCalls(fixture).some((call) => isPackaging(call.command))) {
+ return skip('solution packaging was not requested or attempted');
+ }
+ return gradeEvidence(packagingProblems, fixture);
+});
+
+WORKFLOW_ASSERTIONS.set(
+ 'Phase 4.6: A populated Custom API plan never discovers, generates or uploads after a disabled or unreadable feature gate',
+ ({ fixture }) => {
+ const body = planSection(fixture.genpagePlan, 'Custom API Bindings');
+ if (!fixture.manifest?.customApi && (!body || body === 'No custom API bindings.')) return skip('no Custom API lifecycle in this workflow');
+ return gradeEvidence(customApiGateProblems, fixture);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree',
+ ({ fixture }) => gradeEvidence(customApiProblems, fixture)
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6: Create uploads use name-file and preserve the exact approved name prompt and agent-message text',
+ ({ fixture }) => gradeEvidence((f) => uploadPreservationProblems(f, 'create'), fixture)
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 6: Updates preserve omitted name model data sources and untouched connector and action bindings',
+ ({ fixture }) => gradeEvidence((f) => uploadPreservationProblems(f, 'update'), fixture)
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6.5: Every effective navigation target resolves against the deployed page map; exact substitutions preserve non-navigation bytes and only affected pages reupload',
+ ({ fixture }) => gradeEvidence(navigationProblems, fixture)
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5: A rejected worker artifact prevents upload until a stamped, complete regeneration passes the production gate',
+ ({ fixture }) => gradeEvidence(workerProblems, fixture)
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2a: Auth timeout retries once then halts before provisioning or upload',
+ ({ fixture }) => checkProblems(refusalProblems(fixture))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1: Discovery refusal preserves the error and halts before connection setup or generation',
+ ({ fixture }) => checkProblems(refusalProblems(fixture))
+);
+
+WORKFLOW_ASSERTIONS.set(
+ 'Phase 2a: Every applicable auth result is associated with its command; only the latest successful gate authorizes mutations, and final failures halt with bounded retry and advice',
+ ({ fixture }) => workflowCalls(fixture).some((call) => isAuth(call.command))
+ ? checkProblems(authGateProblems(fixture))
+ : skip('no applicable check-auth call')
+);
+
+WORKFLOW_ASSERTIONS.set(
+ 'Phase 1: Failed connector discovery returns needs_input and never creates a connection or reference',
+ ({ fixture }) => workflowCalls(fixture).some((call) => isDiscovery(call.command))
+ ? checkProblems(discoveryProblems(fixture))
+ : skip('no connector discovery in this workflow')
+);
+
PHASE_EXPECTATIONS.set(
'Phase 1 (Planner): pac model list-tables --search \'account\' is run and results are filtered by exact logical-name match',
({ fixture }) => {
@@ -1007,11 +1055,7 @@ PHASE_EXPECTATIONS.set(
PHASE_EXPECTATIONS.set(
'Phase 2a: Orchestrator runs scripts/check-auth.js; ok:true gate before invoking entity-builder',
({ fixture }) => {
- const log = fixture.workflowLog;
- if (!log) return fail('no workflow-log.md');
- if (!/check-auth\.js/.test(log)) return fail('check-auth.js not invoked');
- if (!/ok:\s*true|"ok":\s*true/.test(log)) return fail('check-auth.js did not return ok:true');
- return pass();
+ return checkProblems(authGateProblems(fixture, { required: true }));
}
);
@@ -1019,7 +1063,7 @@ PHASE_EXPECTATIONS.set(
'Phase 2b (Entity Builder): Every create-table.js / add-column.js / create-relationship.js call passes --solution <name> (always — \'Default\' is a valid value, never omitted); provision-entities.js flow specifies solution via input JSON, verified through ## Environment → Solution: declaration',
({ fixture }) => {
const log = fixture.entityCreationLog || fixture.workflowLog;
- if (!log) return fail('no entity-creation-log.md or workflow-log.md');
+ if (!log) return fail('no genpage-entity-creation-log.md (or legacy alias) or workflow-log.md');
// Check legacy flow: old-script calls must have --solution
const legacyMatches = allMatches(/(create-table\.js|add-column\.js|create-relationship\.js)([^\n]*)/g, log);
@@ -1083,9 +1127,8 @@ PHASE_EXPECTATIONS.set(
const idxCheck = log.search(/check-auth\.js/);
const idxBuilder = log.search(/genpage-entity-builder\s+invoked|entity-builder\s+invoked/i);
if (idxBuilder === -1) return skip('entity-builder not invoked');
- if (idxCheck === -1) return fail('entity-builder invoked but check-auth.js never ran');
- if (idxBuilder < idxCheck) return fail('entity-builder invoked before check-auth.js');
- return pass();
+ if (idxCheck === -1 || idxBuilder < idxCheck) return fail('entity-builder invoked before check-auth.js');
+ return checkProblems(authGateProblems(fixture, { required: true }));
}
);
@@ -1102,7 +1145,6 @@ PHASE_EXPECTATIONS.set(
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
if (!plan) return fail('no genpage-plan.md');
-
// (a) list-connections.js must NOT be invoked — a `node ... list-connections.js`
// command must be absent. A narrative mention like "list-connections.js NOT
// run" in a comment is acceptable and does not count as an invocation.
@@ -1136,6 +1178,8 @@ PHASE_EXPECTATIONS.set(
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
if (!plan) return fail('no genpage-plan.md');
+ const discovery = discoveryProblems(fixture, { required: true, needsBinding: true });
+ if (discovery.length) return checkProblems(discovery);
// (a) A `node ... list-connections.js` invocation must appear in the log —
// discovery must run for a connector-backed data source.
@@ -1207,6 +1251,8 @@ PHASE_EXPECTATIONS.set(
if (!/\bnode\b[^\n]*list-connections\.js/.test(log)) {
return fail('list-connections.js not invoked on the edit path');
}
+ const discovery = discoveryProblems(fixture, { required: true, needsBinding: true });
+ if (discovery.length) return checkProblems(discovery);
// (c) Same bare-array shape as the create path — `pac` wraps it into config.json itself.
// Asserted POSITIVELY (the recorded content opens with `[{`) rather than by banning the
diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.js
index eddabdab9..67618b233 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-2.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js
@@ -21,6 +21,11 @@ const fs = require('node:fs');
// two divergent copies of a tokenizer is exactly how a false-green assertion creeps back in. Evals
// never ship, so reaching into the plugin directory here is in-repo only.
const { blankLiterals, findElisionMarker } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+const { pageStructureProblems } = require('../../../../plugins/model-apps/scripts/lib/page-structure.js');
+const { navigationProblems } = require('./navigation-contract.js');
+const { workerProblems } = require('./worker-contract.js');
+const { customApiProblems } = require('./custom-api-contract.js');
+const { gradeEvidence } = require('./evidence-utils.js');
let _verifiedIcons = null;
function getVerifiedIcons() {
@@ -85,6 +90,17 @@ function skip(reason) { return { status: 'skip', reason }; }
const ASSERTIONS = new Map();
+ASSERTIONS.set(
+ 'Generated .tsx passes the production completeness gate (complete module, JSX, brackets, strings, comments and no prose fences)',
+ ({ files }) => {
+ for (const file of files) {
+ const problems = pageStructureProblems(file.content);
+ if (problems.length) return fail(`${file.name}: ${problems[0]}`);
+ }
+ return pass();
+ }
+);
+
ASSERTIONS.set(
'Generated .tsx is a single file with `export default GeneratedComponent`',
({ files }) => {
@@ -437,8 +453,11 @@ ASSERTIONS.set(
ASSERTIONS.set(
'For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs',
- ({ files }) => {
+ ({ files, fixture }) => {
if (files.length <= 1) return skip('single-page fixture');
+ const result = gradeEvidence(navigationProblems, { ...fixture, files });
+ if (result.status === 'fail') return result;
+ if (fixture?.manifest?.navigation || fixture?.manifest?.navigationPhase === 'resolved') return result;
const hasPageref = files.some((f) => /["']PAGEREF_[a-zA-Z0-9_-]+["']/.test(f.content));
const hasNav = files.some((f) => /Xrm\.Navigation\.navigateTo/.test(f.content));
if (hasNav && !hasPageref) {
@@ -468,6 +487,16 @@ ASSERTIONS.set(
const PHASE5_EXPECTATIONS = new Map();
+PHASE5_EXPECTATIONS.set(
+ 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree',
+ ({ fixture, files }) => gradeEvidence(customApiProblems, { ...fixture, files })
+);
+
+PHASE5_EXPECTATIONS.set(
+ 'Phase 5: A rejected worker artifact prevents upload until a stamped, complete regeneration passes the production gate',
+ ({ fixture, files }) => gradeEvidence(workerProblems, { ...fixture, files })
+);
+
PHASE5_EXPECTATIONS.set(
'Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names',
() => skip('column-name verification requires RuntimeTypes.ts fixture')
diff --git a/evals/model-apps/genpage/lib/custom-api-contract.js b/evals/model-apps/genpage/lib/custom-api-contract.js
new file mode 100644
index 000000000..ccbb48a95
--- /dev/null
+++ b/evals/model-apps/genpage/lib/custom-api-contract.js
@@ -0,0 +1,206 @@
+'use strict';
+
+const { isDeepStrictEqual } = require('node:util');
+const { PARAMETER_KIND_BY_TYPE } = require('../../../../plugins/model-apps/scripts/list-custom-apis.js');
+const { pageStructureProblems } = require('../../../../plugins/model-apps/scripts/lib/page-structure.js');
+const { workflowCalls, isGeneration, isUpload, isMutation, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
+const { artifactText, artifactJson, commandInfo, fileName, isGuid, pathKey } = require('./evidence-utils.js');
+const { planSection, parseMarkdownRows } = require('./plan-evidence.js');
+const { actionCalls, literalString, objectFields, receiverIsDataApi, escapeRe } = require('./source-evidence.js');
+const { desiredBindings, sameBindings } = require('./upload-contract.js');
+
+const KINDS = new Set(Object.values(PARAMETER_KIND_BY_TYPE));
+const isGate = (command) => /\bfeature-flags\.js\b[^\n]*\bcustom-api\b/.test(command);
+const gateValue = (call) => {
+ const raw = typeof call.result === 'string' ? call.result.trim() : '';
+ if (raw === 'enabled' || raw === 'disabled') return raw;
+ return call.historical ? /(?:\u2192|->|Result:)\s*(enabled|disabled)\b/.exec(call.text || '')?.[1] || null : null;
+};
+
+function planBindings(fixture) {
+ const body = planSection(fixture.genpagePlan, 'Custom API Bindings');
+ if (body === 'No custom API bindings.') return [];
+ if (!body) throw new Error('Custom API Bindings section is missing or unreadable, not a no-bindings sentinel');
+ const rows = parseMarkdownRows(body, ['Name', 'Kind', 'Bound Entity', 'Display Name', 'Parameters (name: kind)']);
+ if (!rows.length) throw new Error('Custom API Bindings must be a populated table or the exact no-bindings sentinel');
+ return rows.map((row) => {
+ if (!['Action', 'Function'].includes(row.kind)) throw new Error(`invalid API kind for ${row.name}`);
+ const parameterKinds = {};
+ for (const parameter of row['parameters (name: kind)'].split(',').filter((value) => value.trim())) {
+ const match = /^\s*([\w]+)\s*:\s*([A-Za-z]+)\s*$/.exec(parameter);
+ if (!match || !KINDS.has(match[2]) || Object.hasOwn(parameterKinds, match[1])) throw new Error(`unreadable parameter kinds for ${row.name}`);
+ parameterKinds[match[1]] = match[2];
+ }
+ return {
+ name: row.name, isFunction: row.kind === 'Function', displayName: row['display name'], parameterKinds,
+ ...(row['bound entity'] !== '(Global)' && { boundEntityLogicalName: row['bound entity'] }),
+ };
+ });
+}
+
+function projectBinding(entry) {
+ if (!entry || typeof entry.name !== 'string' || typeof entry.isFunction !== 'boolean' || !entry.displayName
+ || !entry.parameterKinds || Object.values(entry.parameterKinds).some((kind) => !KINDS.has(kind))) {
+ throw new Error('discovered/bound API is missing its name, kind, display name or parameter kinds');
+ }
+ if (entry.bindingType && !['Global', 'Entity'].includes(entry.bindingType)) throw new Error('collection-bound API is not a supported record binding');
+ if (entry.bindingType === 'Global' && entry.boundEntityLogicalName) throw new Error('global API incorrectly declares a bound entity');
+ return { name: entry.name, isFunction: entry.isFunction, displayName: entry.displayName, parameterKinds: entry.parameterKinds,
+ ...(entry.boundEntityLogicalName && { boundEntityLogicalName: entry.boundEntityLogicalName }) };
+}
+
+function customApiGateProblems(fixture) {
+ const bindings = planBindings(fixture);
+ const calls = workflowCalls(fixture);
+ const problems = unassociatedCallProblems(fixture);
+ let latest = null;
+ let gateIndex = -1;
+ let discoveryIndex = -1;
+ for (const [index, call] of calls.entries()) {
+ if (isGate(call.command)) {
+ latest = gateValue(call);
+ gateIndex = index;
+ } else if (/\blist-custom-apis\.js\b/.test(call.command)) {
+ if (latest !== 'enabled') problems.push('Custom API discovery ran before an enabled feature gate');
+ discoveryIndex = index;
+ } else if (bindings.length && (isGeneration(call.command) || isUpload(call.command))) {
+ if (latest !== 'enabled') problems.push('disabled or unreadable Custom API gate must halt before generation or upload');
+ else if (gateIndex <= discoveryIndex) problems.push('Custom API generation must re-probe the feature gate after planning discovery');
+ }
+ }
+ if (bindings.length && !calls.some((call) => isGate(call.command))) problems.push('Custom API table has no applicable feature gate');
+ if (fixture.manifest?.expectedOutcome === 'refused') {
+ if (latest === 'enabled' || !bindings.length || (fixture.files || []).length || calls.some((call) => isGeneration(call.command) || isMutation(call.command))) {
+ problems.push('Custom API refusal must have a blocked gate and zero generation or mutations');
+ }
+ if (!/\bhalt(?:ed)?\b|\bneeds_input\b/i.test(fixture.workflowLog || '')) problems.push('Custom API gate refusal did not surface a halt');
+ }
+ return problems;
+}
+
+function parameterMatches(value, kind, prefix) {
+ const literal = literalString(value);
+ const identifier = /^[\w$]+$/.test(value) ? value : null;
+ const annotation = identifier ? new RegExp(`\\b${identifier}\\s*:\\s*(string\\[\\]|string|number|boolean|Date)\\b`).exec(prefix)?.[1] : null;
+ if (kind === 'String') return literal !== null || annotation === 'string';
+ if (kind === 'Guid') return literal !== null ? isGuid(literal) : annotation === 'string';
+ if (['Integer', 'Decimal', 'Float', 'Money', 'Picklist'].includes(kind)) return /^-?\d+(?:\.\d+)?$/.test(value) || annotation === 'number';
+ if (kind === 'Boolean') return /^(true|false)$/.test(value) || annotation === 'boolean';
+ if (kind === 'DateTime') return annotation === 'Date' || (literal !== null && /^\d{4}-\d\d-\d\dT/.test(literal));
+ if (kind === 'StringArray') return annotation === 'string[]';
+ return value.trim().startsWith('{') || (kind === 'EntityCollection' && value.trim().startsWith('['));
+}
+
+function runtimeProblems(code, bindings, declaredOutputs) {
+ const problems = pageStructureProblems(code);
+ const calls = actionCalls(code);
+ const known = new Map(bindings.map((binding) => [binding.name, binding]));
+ const used = new Set();
+ for (const call of calls) {
+ const name = literalString(call.fields.get('name') || '');
+ const binding = known.get(name);
+ if (!binding) { problems.push(`runtime calls unbound or undiscovered Custom API ${name || '(dynamic name)'}`); continue; }
+ used.add(name);
+ if (call.method !== (binding.isFunction ? 'executeFunction' : 'executeAction')) problems.push(`${name}: runtime method disagrees with discovered Action/Function kind`);
+ const prefix = code.slice(call.scope.start, call.start);
+ const prefixMask = call.mask.slice(call.scope.start, call.start);
+ const post = code.slice(call.end + 1, call.scope.end);
+ const postMask = call.mask.slice(call.end + 1, call.scope.end);
+ if (!receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start)) {
+ problems.push(`${name}: ${call.method} is called on ${call.receiver || 'an expression'}, which is not the page's dataApi prop`);
+ }
+ // The presence check must test the same object the call uses; a check on another object proves nothing.
+ const receiverPattern = call.receiver ? call.receiver.split('.').map(escapeRe).join('\\s*\\??\\.\\s*') : '(?!)';
+ const presence = new RegExp(`\\btypeof\\s+${receiverPattern}\\s*\\??\\.\\s*${call.method}\\s*!==?\\s*(['"])`);
+ const match = presence.exec(prefixMask);
+ if (!match || !/^['"]function['"]/.test(prefix.slice(match.index + match[0].length - 1))) problems.push(`${name}: method is not presence-checked on the same receiver in its helper before the call`);
+ const parameters = call.fields.has('parameters') ? objectFields(call.fields.get('parameters')) : new Map();
+ if ([...parameters.keys()].sort().join('|') !== Object.keys(binding.parameterKinds).sort().join('|')) problems.push(`${name}: runtime parameter names differ from the declared kinds`);
+ for (const [parameter, kind] of Object.entries(binding.parameterKinds)) {
+ if (!parameterMatches(parameters.get(parameter) || '', kind, prefix)) problems.push(`${name}.${parameter}: runtime value does not match ${kind}`);
+ }
+ if (binding.boundEntityLogicalName) {
+ if (!call.fields.has('boundTo')) problems.push(`${name}: entity-bound operation omits boundTo`);
+ else {
+ const bound = objectFields(call.fields.get('boundTo'));
+ if (literalString(bound.get('entityName') || '') !== binding.boundEntityLogicalName) problems.push(`${name}: boundTo uses the wrong entity`);
+ const id = bound.get('id') || '';
+ if (literalString(id) !== null || !/^[\w$.]+$/.test(id) || !parameterMatches(id, 'Guid', prefix)) {
+ problems.push(`${name}: bound record id must come from string-typed existing page input, never a hard-coded GUID or numeric value`);
+ }
+ }
+ } else if (call.fields.has('boundTo')) problems.push(`${name}: global operation must omit boundTo`);
+
+ const result = call.resultName;
+ const ok = new RegExp(`\\bif\\s*\\(\\s*(?:!\\s*${result}\\.ok|${result}\\.ok\\s*===?\\s*false)\\s*\\)\\s*\\{[^}]*\\breturn\\b[^}]*\\}`);
+ const okMatch = ok.exec(postMask);
+ const outputsAt = postMask.search(new RegExp(`\\b${result}\\.outputs\\b`));
+ if (!okMatch || outputsAt < 0 || okMatch.index + okMatch[0].length > outputsAt) problems.push(`${name}: response.ok must refuse before outputs are read`);
+ if (!new RegExp(`\\b${result}\\.error\\??\\.message\\b`).test(postMask) || new RegExp(`\\b${result}\\.(?:value|body)\\b|\\.error\\??\\.(?:stack|detail|details)\\b`).test(postMask)) {
+ problems.push(`${name}: outputs/error handling must use outputs and sanitized error.message only`);
+ }
+ const outputs = [...postMask.matchAll(new RegExp(`\\b${result}\\.outputs(?:\\?\\.)?\\.?([A-Za-z_$][\\w$]*)`, 'g'))].map((entry) => entry[1]);
+ if (!Array.isArray(declaredOutputs?.[name]) || outputs.some((output) => !declaredOutputs[name].includes(output))) problems.push(`${name}: runtime reads an undeclared output`);
+ if (!binding.isFunction) {
+ if (!/\bif\s*\(\s*(?:pending\.current|isSubmitting)(?:\s*\|\|[^)]*)?\)\s*(?:return\b|\{\s*return\b)/.test(prefixMask)
+ || !/\bpending\.current\s*=\s*true\b|\bsetIsSubmitting\s*\(\s*true\s*\)/.test(prefixMask)
+ || !/\bfinally\b[\s\S]*(?:pending\.current\s*=\s*false\b|setIsSubmitting\s*\(\s*false\s*\))/.test(postMask)) {
+ problems.push(`${name}: mutating action lacks a helper-scoped double-submit latch and reset`);
+ }
+ if (!new RegExp(`\\bif\\s*\\(\\s*${result}\\.indeterminate\\s*\\)\\s*\\{[^}]*\\breturn\\b`).test(postMask)) problems.push(`${name}: indeterminate action is not stopped before retry`);
+ if (/\bsetTimeout\b|\bsetInterval\b|\bwhile\s*\(|\bfor\s*\(/.test(postMask) || new RegExp(`\\b${call.scope.name}\\s*\\(`).test(postMask)) problems.push(`${name}: action may auto-retry after dispatch`);
+ }
+ }
+ for (const name of known.keys()) if (!used.has(name)) problems.push(`${name}: selected binding has no runtime call in this lifecycle stage`);
+ return problems;
+}
+
+function customApiProblems(fixture) {
+ const problems = customApiGateProblems(fixture);
+ if (fixture.manifest?.expectedOutcome === 'refused') return problems;
+ const contract = fixture.manifest?.customApi;
+ if (!contract?.stages?.length) return [...problems, 'Custom API lifecycle has no source/config stages'];
+ const declared = planBindings(fixture);
+ const calls = workflowCalls(fixture);
+ const discovered = new Map();
+ for (const call of calls.filter((entry) => /\blist-custom-apis\.js\b/.test(entry.command))) {
+ const result = resultObject(call);
+ if (result?.ok !== true || !Array.isArray(result.customApis)) problems.push('Custom API discovery failed or returned unreadable metadata');
+ else for (const entry of result.customApis) discovered.set(entry.name, projectBinding(entry));
+ }
+ for (const binding of declared) if (!isDeepStrictEqual(discovered.get(binding.name), binding)) problems.push(`${binding.name}: plan kind, bound entity or parameter kinds do not match discovery`);
+ let previousId = null;
+ for (const stage of contract.stages) {
+ const uploadIndex = calls.findIndex((call) => call.id === stage.upload);
+ const call = calls[uploadIndex];
+ if (!call || !isUpload(call.command)) { problems.push(`${stage.id}: missing associated API upload`); continue; }
+ const { flags } = commandInfo(call);
+ const result = resultObject(call);
+ if (fileName(flags['code-file']) !== stage.target || result?.ok !== true) problems.push(`${stage.id}: upload target/result does not match the generated API page`);
+ if (previousId && (flags['page-id'] !== previousId || result.pageId !== previousId)) problems.push(`${stage.id}: update changes the API page's identity`);
+ previousId = result?.pageId;
+ const before = stage.beforeConfig ? artifactJson(fixture, stage.beforeConfig).actionBindings || [] : declared;
+ const desired = stage.beforeConfig ? desiredBindings(before, stage.change, 'name') : declared;
+ if (stage.beforeConfig && stage.change === undefined && flags.actions) problems.push(`${stage.id}: unchanged APIs must omit --actions`);
+ if (!stage.beforeConfig || stage.change !== undefined) {
+ if (!flags.actions || pathKey(flags.actions) !== pathKey(stage.actions) || !sameBindings(artifactJson(fixture, flags.actions), desired, 'name')) {
+ problems.push(`${stage.id}: actions file must be the full desired bare array, including explicit [] to clear`);
+ }
+ }
+ const after = artifactJson(fixture, stage.afterConfig).actionBindings;
+ if (!sameBindings(after, desired, 'name')) problems.push(`${stage.id}: API config read-back loses preservation or explicit-clear intent`);
+ for (const binding of desired) {
+ const projected = projectBinding(binding);
+ if (!isDeepStrictEqual(discovered.get(binding.name), projected)) problems.push(`${binding.name}: actions file differs from discovered metadata`);
+ }
+ const code = artifactText(fixture, stage.source);
+ const write = calls.slice(0, uploadIndex).filter((entry) => /^Write\s+/.test(entry.command) && fileName(entry.command.slice(6)) === stage.target).at(-1);
+ if (!write || artifactText(fixture, write.artifact) !== code) problems.push(`${stage.id}: uploaded API source is not the actual preceding generated snapshot`);
+ problems.push(...runtimeProblems(code, desired, contract.outputs));
+ }
+ const last = contract.stages.at(-1);
+ if (artifactText(fixture, last.target) !== artifactText(fixture, last.source)) problems.push('final API TSX differs from the final lifecycle stage');
+ return problems;
+}
+
+module.exports = { customApiProblems, customApiGateProblems };
diff --git a/evals/model-apps/genpage/lib/evidence-utils.js b/evals/model-apps/genpage/lib/evidence-utils.js
new file mode 100644
index 000000000..1c63b4974
--- /dev/null
+++ b/evals/model-apps/genpage/lib/evidence-utils.js
@@ -0,0 +1,50 @@
+'use strict';
+
+const pathKey = (name) => String(name || '').replace(/\\/g, '/');
+const fileName = (name) => pathKey(name).split('/').at(-1);
+const isGuid = (value) => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
+
+function artifactText(fixture, name) {
+ const key = pathKey(name);
+ const value = fixture.artifacts?.[key] ?? fixture.files?.find((file) => file.name === key)?.content;
+ if (typeof value !== 'string') throw new Error(`missing artifact ${key || '(no path)'}`);
+ return value;
+}
+
+function artifactJson(fixture, name) {
+ try { return JSON.parse(artifactText(fixture, name).replace(/^\uFEFF/, '')); } catch (error) {
+ throw new Error(`${name}: ${error.message}`);
+ }
+}
+
+function commandInfo(call) {
+ // Current evidence may keep argv directly. The fallback only tokenizes recorded command TEXT;
+ // it never expands variables, evaluates quotes or executes a shell. Maker text must be in files,
+ // so the current transport does not need a shell parser for arbitrary prompt/name contents.
+ const tokens = call.argv || (String(call.command || '').match(/"[^"]*"|'[^']*'|[^\s"']+/g) || [])
+ .map((token) => /^["']/.test(token) ? token.slice(1, -1) : token);
+ const flags = {};
+ const positional = [];
+ const problems = [];
+ for (let i = 0; i < tokens.length; i += 1) {
+ const match = /^--([\w-]+)(?:=(.*))?$/.exec(tokens[i]);
+ if (!match) { positional.push(tokens[i]); continue; }
+ const name = match[1];
+ if (Object.hasOwn(flags, name)) problems.push(`duplicate --${name}`);
+ flags[name] = match[2] !== undefined ? match[2]
+ : tokens[i + 1] && !tokens[i + 1].startsWith('--') ? tokens[++i] : true;
+ }
+ return { flags, positional, problems };
+}
+
+function gradeEvidence(check, fixture) {
+ try {
+ const problems = check(fixture);
+ return problems.length ? { status: 'fail', reason: problems[0] } : { status: 'pass', reason: '' };
+ } catch (error) {
+ // Missing/malformed evidence is an eval FAILURE, never a success-shaped skip.
+ return { status: 'fail', reason: error.message };
+ }
+}
+
+module.exports = { pathKey, fileName, isGuid, artifactText, artifactJson, commandInfo, gradeEvidence };
diff --git a/evals/model-apps/genpage/lib/fixture-loader.js b/evals/model-apps/genpage/lib/fixture-loader.js
index 27ff822df..c32c2924c 100644
--- a/evals/model-apps/genpage/lib/fixture-loader.js
+++ b/evals/model-apps/genpage/lib/fixture-loader.js
@@ -12,7 +12,7 @@ const path = require('node:path');
// page.tsx ← .tsx output (consumed by Layer 2)
// workflow-log.md ← log of agent actions (consumed by Layer 1)
// genpage-plan.md ← plan doc (consumed by Layer 1)
-// entity-creation-log.md ← entity-builder transactions (Layer 1)
+// genpage-entity-creation-log.md ← entity-builder transactions (Layer 1)
// 2-mock-dashboard/
// dashboard.tsx
//
@@ -22,7 +22,66 @@ const path = require('node:path');
// workflowLog: string | null ← workflow-log.md content (Layer 1)
// genpagePlan: string | null ← genpage-plan.md content (Layer 1)
// genpageEditPlan: string | null ← genpage-edit-plan.md content (Layer 1 edit flow)
-// entityCreationLog: string | null ← entity-creation-log.md content (Layer 1)
+// entityCreationLog: string | null ← current log or legacy alias (Layer 1)
+// contractVersion, manifest, events, artifacts ← versioned synthetic evidence
+
+const ENTITY_CREATION_LOG = 'genpage-entity-creation-log.md';
+// Historical captures predate the skill-specific prefix; keep their old name as a read-only alias.
+const LEGACY_ENTITY_CREATION_LOG = 'entity-creation-log.md';
+
+function readJson(dir, name) {
+ const text = readOptional(dir, name);
+ if (text === null) return null;
+ try {
+ return JSON.parse(text.replace(/^\uFEFF/, ''));
+ } catch (error) {
+ throw new Error(`${path.basename(dir)}: invalid JSON in ${name}: ${error.message}`);
+ }
+}
+
+function evidenceFile(dir, name) {
+ if (typeof name !== 'string' || !name || path.win32.isAbsolute(name) || path.posix.isAbsolute(name)
+ || name.split(/[\\/]/).some((part) => part === '..' || part === '.' || !part)) {
+ throw new Error(`${path.basename(dir)}: invalid artifact path ${JSON.stringify(name)}`);
+ }
+ const full = path.resolve(dir, ...name.split(/[\\/]/));
+ const root = fs.realpathSync(dir);
+ const real = fs.realpathSync(full);
+ const relative = path.relative(root, real);
+ const stat = fs.lstatSync(full);
+ if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative) || !stat.isFile() || stat.nlink > 1) {
+ throw new Error(`${path.basename(dir)}: artifact path is outside the fixture or not a plain file: ${name}`);
+ }
+ return fs.readFileSync(full, 'utf8');
+}
+
+function fixtureEvidence(dir, dirName, historicalContracts) {
+ const manifest = readJson(dir, 'fixture.json') || historicalContracts[dirName]
+ || { contractVersion: 1, provenance: 'historical' };
+ if (!manifest || ![1, 2].includes(manifest.contractVersion)) {
+ throw new Error(`${dirName}: unsupported fixture contract version`);
+ }
+ if (manifest.contractVersion === 2 && manifest.provenance !== 'synthetic') {
+ throw new Error(`${dirName}: current eval fixtures must be labelled synthetic`);
+ }
+ const artifacts = {};
+ for (const name of manifest.artifacts || []) {
+ artifacts[name.replace(/\\/g, '/')] = evidenceFile(dir, name);
+ }
+ let events;
+ if (manifest.toolResults) {
+ const text = evidenceFile(dir, manifest.toolResults);
+ try { events = JSON.parse(text); } catch (error) {
+ throw new Error(`${dirName}: invalid JSON in ${manifest.toolResults}: ${error.message}`);
+ }
+ if (!Array.isArray(events) || events.some((event) => !event || typeof event.command !== 'string' || !event.command.trim())) {
+ throw new Error(`${dirName}: tool results must be an ordered array of command/result events`);
+ }
+ const ids = events.map((event) => event.id).filter((id) => id !== undefined);
+ if (new Set(ids).size !== ids.length) throw new Error(`${dirName}: duplicate tool-result event id`);
+ }
+ return { contractVersion: manifest.contractVersion, manifest, events, artifacts };
+}
function loadFixtures(fixturesDir) {
if (!fs.existsSync(fixturesDir)) {
@@ -31,6 +90,9 @@ function loadFixtures(fixturesDir) {
const entries = fs.readdirSync(fixturesDir, { withFileTypes: true })
.filter((e) => e.isDirectory())
.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
+ // Labels live beside, not INSIDE, captured directories: updating compatibility metadata must
+ // never rewrite the original transcript/source evidence.
+ const historicalContracts = readJson(fixturesDir, 'contracts.json') || {};
const fixtures = [];
for (const entry of entries) {
@@ -46,7 +108,9 @@ function loadFixtures(fixturesDir) {
workflowLog: readOptional(dir, 'workflow-log.md'),
genpagePlan: readOptional(dir, 'genpage-plan.md'),
genpageEditPlan: readOptional(dir, 'genpage-edit-plan.md'),
- entityCreationLog: readOptional(dir, 'entity-creation-log.md'),
+ // Only absence permits the legacy alias. An empty current log must not borrow old transactions.
+ entityCreationLog: readOptional(dir, ENTITY_CREATION_LOG) ?? readOptional(dir, LEGACY_ENTITY_CREATION_LOG),
+ ...fixtureEvidence(dir, entry.name, historicalContracts),
});
}
return fixtures;
@@ -71,4 +135,4 @@ function readOptional(dir, fileName) {
return fs.readFileSync(full, 'utf8');
}
-module.exports = { loadFixtures, listTsxFiles, readOptional };
+module.exports = { loadFixtures, listTsxFiles, readOptional, ENTITY_CREATION_LOG, LEGACY_ENTITY_CREATION_LOG };
diff --git a/evals/model-apps/genpage/lib/navigation-contract.js b/evals/model-apps/genpage/lib/navigation-contract.js
new file mode 100644
index 000000000..5d7bf6e81
--- /dev/null
+++ b/evals/model-apps/genpage/lib/navigation-contract.js
@@ -0,0 +1,109 @@
+'use strict';
+
+const { extractNavTargets, resolvePageRefs, navTargetParity } = require('../../../../plugins/model-apps/scripts/lib/pageref-resolver.js');
+const { workflowCalls, isUpload, resultObject } = require('./workflow-evidence.js');
+const { artifactText, commandInfo, fileName, isGuid, pathKey } = require('./evidence-utils.js');
+
+function historicalPageMap(log) {
+ const map = {};
+ // A resolved capture records `PAGEREF_ map: candidate-list -> <guid>, ...`.
+ // Read that deployment evidence, not GUIDs in the TSX being judged.
+ const line = /^\s*-\s*PAGEREF_ map:\s*(.+)$/m.exec(log || '');
+ if (line) {
+ for (const match of line[1].matchAll(/([A-Za-z0-9_-]+)\s*(?:\u2192|->)\s*([0-9a-f-]{36})/gi)) map[match[1]] = match[2];
+ }
+ return map;
+}
+
+function sourceProblems(files, { phase = 'authored', pageMap = {}, legacy = false } = {}) {
+ const keys = new Set(files.map((file) => file.name.replace(/\.tsx$/i, '')));
+ const ids = new Set(Object.values(pageMap).filter(isGuid).map((id) => id.toLowerCase()));
+ const problems = [];
+ for (const file of files) {
+ // This one capture predates `pageType:"generative"` and double-quoted PAGEREFs. The
+ // compatibility view admits those historical spellings ONLY; it still checks every actual
+ // target against sibling files. It is never used to claim current-contract compliance.
+ const code = legacy ? file.content.replace(/\bpageType\s*:\s*(["'])custom\1/g, 'pageType: "generative"') : file.content;
+ for (const target of extractNavTargets(code)) {
+ if (target.kind === 'dynamic') problems.push(`${file.name}: effective navigation target is dynamic or overridden`);
+ else if (target.kind === 'pageref' || (legacy && target.kind === 'pageref-malformed')) {
+ if (phase === 'resolved') problems.push(`${file.name}: PAGEREF_${target.key} remains after resolution`);
+ if (!keys.has(target.key)) problems.push(`${file.name}: unknown sibling target PAGEREF_${target.key}`);
+ } else if (target.kind === 'pageref-malformed') {
+ problems.push(`${file.name}: navigation placeholder is not a canonical double-quoted PAGEREF`);
+ } else if (target.kind === 'literal') {
+ if (phase !== 'resolved') problems.push(`${file.name}: literal page id appears before resolution`);
+ if (!isGuid(target.pageId) || !ids.has(target.pageId.toLowerCase())) {
+ problems.push(`${file.name}: resolved target is not a deployed GUID from the page map`);
+ }
+ }
+ }
+ }
+ return problems;
+}
+
+function navigationProblems(fixture) {
+ const contract = fixture.manifest?.navigation;
+ if (!contract) {
+ const phase = fixture.manifest?.navigationPhase || 'authored';
+ const pageMap = fixture.manifest?.pageMap || historicalPageMap(fixture.workflowLog);
+ return sourceProblems(fixture.files || [], { phase, pageMap, legacy: phase === 'legacy-authored' });
+ }
+ const problems = [];
+ const pageMap = contract.pageMap || {};
+ const rows = contract.sources || [];
+ const keys = rows.map((row) => row.key);
+ const files = fixture.files || [];
+ if (!rows.length || new Set(keys).size !== keys.length) problems.push('navigation sources are missing or have duplicate keys');
+ if (Object.keys(pageMap).sort().join('|') !== [...keys].sort().join('|')) problems.push('navigation page map does not contain exactly the generated pages');
+ for (const [key, id] of Object.entries(pageMap)) if (!isGuid(id)) problems.push(`${key}: deployed page id is not a GUID`);
+ if (files.length !== rows.length || rows.some((row) => !files.some((file) => file.name === row.file))) {
+ problems.push('navigation evidence must cover every actual before/after TSX file');
+ }
+ const before = rows.map((row) => ({ name: row.file, content: artifactText(fixture, row.before) }));
+ problems.push(...sourceProblems(before, { pageMap, phase: 'authored' }));
+ for (const row of rows) {
+ const declared = contract.expectedTargets?.[row.key];
+ if (!Array.isArray(declared)) { problems.push(`${row.key}: missing declared target set`); continue; }
+ const targets = extractNavTargets(artifactText(fixture, row.before)).filter((target) => target.kind === 'pageref').map((target) => target.key);
+ const parity = navTargetParity(declared, targets);
+ if (parity.declaredNotReferenced.length || parity.referencedNotDeclared.length) problems.push(`${row.key}: effective target set differs from the declared navigation`);
+ }
+ const sources = new Map(rows.map((row) => [row.key, { code: artifactText(fixture, row.before) }]));
+ const resolved = resolvePageRefs(sources, new Map(Object.entries(pageMap)));
+ if (resolved.unresolved.length) problems.push(`unresolved navigation targets: ${resolved.unresolved.join(', ')}`);
+ const changed = [];
+ for (const row of rows) {
+ const expected = resolved.deployment.get(row.key);
+ if (artifactText(fixture, row.file) !== expected) problems.push(`${row.file}: after TSX is not the exact structural substitution (non-navigation bytes changed or a target was missed)`);
+ if (sources.get(row.key).code !== expected) changed.push(row.key);
+ }
+ problems.push(...sourceProblems(files, { pageMap, phase: 'resolved' }));
+ const updates = [];
+ const creates = [];
+ for (const call of workflowCalls(fixture).filter((entry) => isUpload(entry.command))) {
+ const { flags, problems: flagProblems } = commandInfo(call);
+ problems.push(...flagProblems);
+ const row = rows.find((entry) => entry.file === fileName(flags['code-file']));
+ if (!row) { problems.push('navigation upload names a page outside the source map'); continue; }
+ const result = resultObject(call);
+ if (result?.ok !== true || result.pageId?.toLowerCase() !== pageMap[row.key]?.toLowerCase()) problems.push(`${row.key}: upload result does not match its deployed page-map id`);
+ if (flags['page-id']) {
+ updates.push(row.key);
+ if (new Set(creates).size !== keys.length) problems.push('navigation fix-up ran before all sibling page ids were returned');
+ if (pathKey(flags['code-file']) !== pathKey(row.file)) problems.push(`${row.key}: re-upload must use the actual resolved TSX snapshot`);
+ if (flags['page-id'] !== pageMap[row.key] || flags['add-to-sitemap']) problems.push(`${row.key}: fix-up must update its own id without sitemap placement`);
+ const prompt = flags['prompt-file'] ? artifactText(fixture, flags['prompt-file']) : '';
+ if (!/^Resolve cross-page navigation placeholders to real page GUIDs\b/.test(prompt)) problems.push(`${row.key}: navigation re-upload prompt is not the fix-up delta`);
+ } else {
+ creates.push(row.key);
+ if (pathKey(flags['code-file']) !== pathKey(row.before)) problems.push(`${row.key}: first upload must use the actual authored before-resolution TSX snapshot`);
+ if (!flags['add-to-sitemap']) problems.push(`${row.key}: first upload does not place the page`);
+ }
+ }
+ if (creates.sort().join('|') !== [...keys].sort().join('|')) problems.push('navigation map is not backed by exactly one successful create per page');
+ if (updates.sort().join('|') !== changed.sort().join('|')) problems.push('only affected navigation pages must reupload, exactly once');
+ return problems;
+}
+
+module.exports = { navigationProblems, sourceProblems };
diff --git a/evals/model-apps/genpage/lib/packaging-contract.js b/evals/model-apps/genpage/lib/packaging-contract.js
new file mode 100644
index 000000000..87a427a93
--- /dev/null
+++ b/evals/model-apps/genpage/lib/packaging-contract.js
@@ -0,0 +1,143 @@
+'use strict';
+
+const { isDeepStrictEqual } = require('node:util');
+const { APPMODULE_COMPONENT_TYPE } = require('../../../../plugins/model-apps/scripts/add-page-to-solution.js');
+const { workflowCalls, isUpload, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
+const { artifactJson, commandInfo, fileName, isGuid } = require('./evidence-utils.js');
+const { planSection } = require('./plan-evidence.js');
+
+const isPackaging = (command) => /\badd-page-to-solution\.js\b/.test(command);
+const csv = (value) => typeof value === 'string' ? [...new Set(value.split(',').map((entry) => entry.trim().toLowerCase()).filter(Boolean))] : [];
+const okResponse = (request) => Number.isInteger(request.response?.status) && request.response.status >= 200 && request.response.status < 300;
+
+function packagingProblems(fixture) {
+ const calls = workflowCalls(fixture);
+ const packages = calls.filter((call) => isPackaging(call.command));
+ const section = planSection(fixture.genpagePlan, 'Solution Packaging');
+ const optedIn = /Package into solution:\s*true\b/i.test(section || '');
+ if (!optedIn) return packages.length ? ['packaging ran without explicit plan opt-in'] : [];
+ const contract = fixture.manifest?.packaging;
+ if (!contract) return ['packaging has no deployed identity/attempt evidence'];
+ const problems = unassociatedCallProblems(fixture);
+ const pages = contract.pages || [];
+ const pageIds = pages.map((page) => page.pageId?.toLowerCase());
+ if (!isGuid(contract.appId) || !pages.length || pageIds.some((id) => !isGuid(id)) || new Set(pageIds).size !== pageIds.length) problems.push('deployed packaging app/pages need distinct valid GUID identities');
+ const solution = /^\s*[-*]?\s*Solution:\s*(\S+)/m.exec(section)?.[1];
+ if (solution !== contract.solution || !/^[A-Za-z][A-Za-z0-9_]*$/.test(solution || '')) problems.push('packaging solution does not match the approved unique name');
+ const deployed = new Map();
+ for (const call of calls.filter((entry) => isUpload(entry.command))) {
+ const result = resultObject(call);
+ const { flags } = commandInfo(call);
+ if (result?.ok === true && flags['app-id'] === contract.appId) deployed.set(fileName(flags['code-file']), result.pageId);
+ }
+ if ([...deployed.keys()].sort().join('|') !== pages.map((page) => page.file).sort().join('|')) {
+ problems.push('packaging declared page set omits an actual deployed upload');
+ }
+ for (const page of pages) {
+ const deploy = calls.filter((call) => isUpload(call.command) && fileName(commandInfo(call).flags['code-file']) === page.file).at(-1);
+ if (resultObject(deploy || {})?.ok !== true || resultObject(deploy || {}).pageId !== page.pageId
+ || commandInfo(deploy || {}).flags['app-id'] !== contract.appId) problems.push(`${page.file}: explicit packaging id is not backed by its deployed result/app`);
+ }
+ const refs = [...new Set((contract.connectionReferences || []).map((name) => name.toLowerCase()))].sort();
+ const boundRefs = [...new Set((contract.configs || []).flatMap((name) => (artifactJson(fixture, name).connectorBindings || []).map((binding) => binding.logicalName?.toLowerCase())))].sort();
+ if (!isDeepStrictEqual(refs, boundRefs)) problems.push('packaging references must include exactly the deployed connector logical names');
+ const solutionCall = calls.filter((call) => /\bprovision-solution\.js\b/.test(call.command)).at(-1);
+ const resolvedSolution = resultObject(solutionCall || {});
+ if (resolvedSolution?.ok !== true || resolvedSolution.uniqueName !== solution || resolvedSolution.solutionId !== contract.solutionId || !isGuid(contract.solutionId)) {
+ problems.push('target solution identity is not backed by successful provision/discovery evidence');
+ }
+ const attempts = contract.attempts || [];
+ if (!attempts.length || attempts.length !== packages.length || new Set(attempts.map((attempt) => attempt.event)).size !== attempts.length) problems.push('packaging evidence must account for every command/result attempt');
+ for (const attempt of attempts) {
+ const call = packages.find((entry) => entry.id === attempt.event);
+ if (!call) { problems.push(`missing packaging result ${attempt.event}`); continue; }
+ const { flags, positional, problems: flagProblems } = commandInfo(call);
+ problems.push(...flagProblems);
+ if (Object.keys(flags).some((flag) => !['page-ids', 'connection-refs'].includes(flag))) problems.push('packaging command has an unsupported flag');
+ const script = positional.findIndex((token) => fileName(token) === 'add-page-to-solution.js');
+ const args = positional.slice(script + 1);
+ const [env, requestedSolution, appId] = args;
+ if (script < 0 || args.length !== 3 || requestedSolution !== solution || !/^https:\/\//.test(env || '')) problems.push('packaging command omits or changes environment/solution/app arguments');
+ const requestedPages = csv(flags['page-ids']);
+ const malformed = !isGuid(appId) || requestedPages.some((id) => !isGuid(id));
+ const requests = call.requests;
+ const result = resultObject(call);
+ if (!Array.isArray(requests)) { problems.push('packaging needs recorded request/write evidence'); continue; }
+ if (malformed) {
+ if (attempt.outcome !== 'refused' || result?.ok !== false || requests.length || !/GUID|identity/i.test(result?.error || '') || call.userMessage !== result.error) {
+ problems.push('bad packaging identities must refuse before any read/write and surface the error');
+ }
+ continue;
+ }
+ if (appId !== contract.appId || [...requestedPages].sort().join('|') !== [...pageIds].sort().join('|')) problems.push('every deployed page id must be passed explicitly to packaging, never inferred from the app');
+ if (csv(flags['connection-refs']).sort().join('|') !== refs.join('|')) problems.push('packaging command omits or changes a deployed connection reference');
+ const posts = requests.filter((request) => request.method === 'POST');
+ const firstPost = requests.findIndex((request) => request.method === 'POST');
+ const types = new Map();
+ const refIds = new Map();
+ for (const [index, request] of requests.entries()) {
+ if (request.method === 'GET') {
+ if (firstPost !== -1 && index > firstPost) problems.push('component types/reference lookups must complete before the first write');
+ const entity = /EntityDefinitions\(LogicalName='(uxagentproject|connectionreference)'\)/.exec(request.path);
+ if (entity && okResponse(request)) {
+ const type = Number(request.response.data?.ObjectTypeCode);
+ if (!Number.isInteger(type) || type <= 0) problems.push('component type metadata is invalid');
+ else types.set(entity[1], type);
+ }
+ const ref = /connectionreferencelogicalname eq '([^']+)'/.exec(request.path);
+ if (ref && okResponse(request)) {
+ const id = request.response.data?.value?.[0]?.connectionreferenceid;
+ if (!isGuid(id)) problems.push('connection reference lookup returned no valid id');
+ else refIds.set(ref[1].toLowerCase(), id);
+ }
+ } else if (request.method !== 'POST' || request.path !== 'AddSolutionComponent') problems.push('unexpected packaging write/request');
+ if (!okResponse(request) && index !== requests.length - 1) problems.push('packaging continued after a failed preflight/component request');
+ }
+ const failure = requests.some((request) => !okResponse(request));
+ if (posts.length && (!types.has('uxagentproject') || (refs.length && (!types.has('connectionreference') || refs.some((name) => !refIds.has(name)))))) {
+ problems.push('packaging wrote before resolving all environment-specific component types/references');
+ }
+ const expected = [
+ { type: 'appmodule', id: contract.appId, componentType: APPMODULE_COMPONENT_TYPE, required: true },
+ ...requestedPages.map((id) => ({ type: 'uxagentproject', id, componentType: types.get('uxagentproject'), required: true })),
+ ...refs.map((name) => ({ type: 'connectionreference', logicalName: name, id: refIds.get(name), componentType: types.get('connectionreference'), required: false })),
+ ];
+ const completed = [];
+ for (const [index, request] of posts.entries()) {
+ const entry = expected[index];
+ const body = entry && { ComponentId: entry.id, ComponentType: entry.componentType, SolutionUniqueName: solution, AddRequiredComponents: entry.required };
+ if (!entry || !isDeepStrictEqual(request.body, body)) problems.push('packaging must add the app before every explicit page/reference with correct solution/types/required flags');
+ if (entry && okResponse(request)) completed.push(entry);
+ }
+ if (failure) {
+ if (attempt.outcome !== 'failed' || result?.ok !== false || !result.error || call.userMessage !== result.error) problems.push('partial/preflight packaging failure was hidden or reported as success');
+ } else if (attempt.outcome !== 'success' || result?.ok !== true || completed.length !== expected.length) problems.push('packaging omitted components or did not report complete success');
+ if (result?.ok === true) {
+ const added = expected.map(({ type, id, logicalName }) => ({ type, id, ...(logicalName && { logicalName }) }));
+ if (!isDeepStrictEqual(result.added, added)) problems.push('packaging result added list differs from explicit requested components');
+ }
+ if (completed.length || attempt.readback) {
+ const readback = calls.find((entry) => entry.id === attempt.readback);
+ const readResult = resultObject(readback || {});
+ if (!readback || calls.indexOf(readback) <= calls.indexOf(call) || !readback.command.includes(contract.solutionId) || readResult?.ok !== true || !Array.isArray(readResult.data?.value)) {
+ problems.push('packaging needs a successful subsequent read-back from the same solution');
+ } else {
+ const key = (entry) => `${entry.id.toLowerCase()}:${entry.componentType}`;
+ const wanted = completed.map(key).sort();
+ const directIds = new Set(expected.map((entry) => entry.id).filter(isGuid).map((id) => id.toLowerCase()));
+ if (readResult.data.value.some((entry) => !isGuid(entry.objectid) || !Number.isInteger(entry.componenttype) || entry.componenttype <= 0)) {
+ problems.push('solution read-back contains malformed component identities/types');
+ }
+ // AddRequiredComponents also pulls sitemap/project-file dependencies; an existing solution
+ // may contain unrelated rows too. Grade the explicit app/page/reference scope, not the whole
+ // solution as though the packaging CLI had promised to empty it (SKILL.md Phase 6.7).
+ const actual = readResult.data.value.filter((entry) => directIds.has(String(entry.objectid).toLowerCase()))
+ .map((entry) => `${String(entry.objectid).toLowerCase()}:${entry.componenttype}`).sort();
+ if (!isDeepStrictEqual(wanted, actual)) problems.push('solution read-back does not contain exactly the completed component writes');
+ }
+ }
+ }
+ return problems;
+}
+
+module.exports = { packagingProblems, isPackaging };
diff --git a/evals/model-apps/genpage/lib/plan-evidence.js b/evals/model-apps/genpage/lib/plan-evidence.js
new file mode 100644
index 000000000..6d8faa1d1
--- /dev/null
+++ b/evals/model-apps/genpage/lib/plan-evidence.js
@@ -0,0 +1,44 @@
+'use strict';
+
+function planSection(plan, heading) {
+ if (!plan) return null;
+ const lines = plan.split('\n');
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const startRe = new RegExp(`^##\\s+${escaped}\\s*$`, 'i');
+ let i = 0;
+ while (i < lines.length && !startRe.test(lines[i])) i++;
+ if (i >= lines.length) return null;
+ i++;
+ const out = [];
+ while (i < lines.length && !/^##\s/.test(lines[i])) out.push(lines[i++]);
+ return out.join('\n').trim();
+}
+
+function findMarkdownTable(sectionText, requiredColumns) {
+ const lines = sectionText.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ if (!/^\s*\|.*\|\s*$/.test(lines[i])) continue;
+ const headers = lines[i].split('|').slice(1, -1).map((header) => header.trim().toLowerCase());
+ if (requiredColumns.every((column) => headers.includes(column.toLowerCase()))) {
+ return { lineIndex: i, headers, lines: lines.slice(i) };
+ }
+ }
+ return null;
+}
+
+function parseMarkdownRows(sectionText, requiredColumns) {
+ const table = findMarkdownTable(sectionText, requiredColumns);
+ if (!table) return [];
+ const rows = [];
+ for (const line of table.lines.slice(2)) {
+ if (!/^\s*\|.*\|\s*$/.test(line)) break;
+ const cells = line.split('|').slice(1, -1).map((cell) => cell.trim());
+ if (cells.length === 0 || cells.every((cell) => cell === '')) continue;
+ const row = {};
+ for (let i = 0; i < table.headers.length; i++) row[table.headers[i]] = cells[i] || '';
+ rows.push(row);
+ }
+ return rows;
+}
+
+module.exports = { planSection, findMarkdownTable, parseMarkdownRows };
diff --git a/evals/model-apps/genpage/lib/source-evidence.js b/evals/model-apps/genpage/lib/source-evidence.js
new file mode 100644
index 000000000..b01223819
--- /dev/null
+++ b/evals/model-apps/genpage/lib/source-evidence.js
@@ -0,0 +1,488 @@
+'use strict';
+
+const { blankNonCodePreservingTemplateExpressions } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+
+function groupEnd(mask, open) {
+ const pairs = { '(': ')', '{': '}', '[': ']' };
+ const stack = [];
+ for (let i = open; i < mask.length; i += 1) {
+ if (pairs[mask[i]]) stack.push(pairs[mask[i]]);
+ else if (/[)}\]]/.test(mask[i])) {
+ if (stack.pop() !== mask[i]) throw new Error('unbalanced source evidence');
+ if (!stack.length) return i;
+ }
+ }
+ throw new Error('truncated source evidence');
+}
+
+function literalString(text) {
+ const value = text.trim();
+ if (value.startsWith('"')) {
+ try {
+ const parsed = JSON.parse(value);
+ return typeof parsed === 'string' ? parsed : null;
+ } catch { return null; }
+ }
+ const match = /^'((?:\\.|[^'\\])*)'$/.exec(value);
+ if (!match) return null;
+ // The scorer accepts literal ASCII request names/values and ordinary quote/backslash escapes.
+ // Unsupported expressions fail closed; no page source is ever evaluated to discover a value.
+ if (/\\[^\\']/.test(match[1])) return null;
+ return match[1].replace(/\\(['\\])/g, '$1');
+}
+
+function objectFields(text) {
+ const source = text.trim();
+ const mask = blankNonCodePreservingTemplateExpressions(source);
+ if (mask[0] !== '{' || groupEnd(mask, 0) !== mask.length - 1) throw new Error('request must be one literal object');
+ const fields = new Map();
+ let i = 1;
+ while (i < mask.length - 1) {
+ while (/[\s,]/.test(mask[i])) i++;
+ if (i >= mask.length - 1) break;
+ let name;
+ if (/["']/.test(mask[i])) {
+ const quote = mask[i];
+ const end = mask.indexOf(quote, i + 1);
+ name = literalString(source.slice(i, end + 1));
+ i = end + 1;
+ } else {
+ const key = /^[A-Za-z_$][\w$]*/.exec(mask.slice(i));
+ if (!key) throw new Error('computed, spread or dynamic request properties are not gradeable');
+ name = key[0];
+ i += name.length;
+ }
+ while (/\s/.test(mask[i])) i++;
+ if (!name || mask[i++] !== ':') throw new Error('request properties require literal names and values');
+ while (/\s/.test(mask[i])) i++;
+ const start = i;
+ while (i < mask.length - 1 && mask[i] !== ',') {
+ if (/[({[]/.test(mask[i])) i = groupEnd(mask, i) + 1;
+ else i++;
+ }
+ if (fields.has(name)) throw new Error(`duplicate request property ${name}`);
+ fields.set(name, source.slice(start, i).trim());
+ }
+ return fields;
+}
+
+function actionCalls(code) {
+ const mask = blankNonCodePreservingTemplateExpressions(code);
+ const scopes = [];
+ for (const match of mask.matchAll(/\b(?:async\s+)?function\s+([\w$]+)\s*\(/g)) {
+ const paramsOpen = match.index + match[0].length - 1;
+ const paramsEnd = groupEnd(mask, paramsOpen);
+ const body = mask.indexOf('{', paramsEnd);
+ if (body !== -1) scopes.push({ name: match[1], start: match.index, paramsOpen, paramsEnd, body, end: groupEnd(mask, body) });
+ }
+ const calls = [];
+ for (const match of mask.matchAll(/\.\s*(executeAction|executeFunction)\s*(?:\?\.\s*)?\(/g)) {
+ const open = match.index + match[0].length - 1;
+ const end = groupEnd(mask, open);
+ const scope = innermostScope(scopes, match.index, end);
+ if (!scope) throw new Error('Custom API calls require a gradeable named helper scope');
+ const assignment = /\b(?:const|let)\s+([\w$]+)\s*=\s*await\s+[\w$.?]+\s*$/.exec(mask.slice(scope.body, match.index));
+ if (!assignment) throw new Error('Custom API call has no associated awaited result');
+ // The receiver is the identifier chain right before the dot: `api`, `actionApi`, `props.dataApi`
+ // (`api?.executeAction` too). Anything else, such as a parenthesised cast, stays null, and the
+ // receiver check fails it rather than guessing what it refers to.
+ const chain = /([A-Za-z_$][\w$]*(?:\s*\??\.\s*[A-Za-z_$][\w$]*)*)\s*\??$/.exec(mask.slice(0, match.index));
+ const receiver = chain ? normalizeChain(chain[1]) : null;
+ calls.push({ method: match[1], start: match.index, end, scope, scopes, receiver, resultName: assignment[1], fields: objectFields(code.slice(open + 1, end)), mask });
+ }
+ return calls;
+}
+
+const normalizeChain = (text) => String(text).replace(/\s+/g, '').replace(/\?\./g, '.');
+const escapeRe = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+const IDENT = /^[A-Za-z_$][\w$]*$/;
+const CHAIN = '[A-Za-z_$][\\w$]*(?:\\s*\\??\\.\\s*[A-Za-z_$][\\w$]*)*';
+
+function innermostScope(scopes, at, end = at) {
+ return scopes.filter((entry) => entry.body < at && entry.end > end).sort((a, b) => b.body - a.body)[0];
+}
+
+// At a `<`, the index of the `>` closing a TypeScript type-argument list (`new Map<string, number>()`,
+// `x as Record<string, unknown>`, a `Record<string, number>` parameter type), or -1 when the `<` reads
+// as a comparison. A type list holds only type syntax and is followed by something that can follow a
+// type: `(`, `)`, `,`, `[`, `>`, `;`, ` =`, `{`, `}`, `|`, `&`, a line break or nothing. The `>` of an
+// arrow `=>` never closes it, and `>=` is a comparison.
+function typeArgsEnd(mask, open) {
+ let depth = 0;
+ for (let i = open; i < mask.length; i += 1) {
+ const ch = mask[i];
+ if (ch === '<') depth += 1;
+ else if (ch === '>' && mask[i - 1] === '=') continue; // the arrow of a function type: `() => void`
+ else if (ch === '>') {
+ depth -= 1;
+ if (depth === 0) {
+ const after = mask.slice(i + 1);
+ if (after[0] === '=') return -1;
+ const next = /^[ \t]*(\r?\n|.?)/.exec(after)[1];
+ return next === '' || /^[\r\n]/.test(next) || '(),[>;={}|&'.includes(next) ? i : -1;
+ }
+ } else if ('({['.includes(ch)) {
+ try { i = groupEnd(mask, i); } catch { return -1; }
+ } else if (!/[\s\w$.,|&?:'"\]=]/.test(ch)) return -1;
+ }
+ return -1;
+}
+
+// Split `(a, b, c)` at its top-level commas; a type-argument list is one unit.
+function splitTopLevel(mask, open, close) {
+ const parts = [];
+ let start = open + 1;
+ for (let i = open + 1; i < close; i += 1) {
+ const ch = mask[i];
+ if ('({['.includes(ch)) { i = groupEnd(mask, i); continue; }
+ if (ch === '<') {
+ const end = typeArgsEnd(mask, i);
+ if (end > i && end < close) { i = end; continue; }
+ }
+ if (ch === ',') { parts.push(mask.slice(start, i)); start = i + 1; }
+ }
+ const last = mask.slice(start, close);
+ if (last.trim() || parts.length) parts.push(last);
+ return parts.map((part) => part.trim());
+}
+
+// `dataApi, pageInput: input, ...rest` → local name → property name.
+// A rest entry (`...others`) is a copy of the remaining properties, not a property, so it is
+// skipped: `const { ...dataApi } = props` names a copy of the props, not their dataApi.
+function destructuredNames(list) {
+ const names = new Map();
+ for (const entry of list.split(',').map((part) => part.trim()).filter(Boolean)) {
+ if (entry.startsWith('...')) continue;
+ const match = /^([A-Za-z_$][\w$]*)(?:\s*:\s*([A-Za-z_$][\w$]*))?/.exec(entry);
+ if (match) names.set(match[2] || match[1], match[1]);
+ }
+ return names;
+}
+
+// Every call of a named helper, with its arguments. The declaration itself and member calls
+// (`obj.name(...)`) are not calls of the helper.
+function callSites(mask, name) {
+ const sites = [];
+ for (const match of mask.matchAll(new RegExp(`(?<![\\w$.])${escapeRe(name)}\\s*\\(`, 'g'))) {
+ if (/\bfunction\s*$/.test(mask.slice(Math.max(0, match.index - 20), match.index))) continue;
+ const open = match.index + match[0].length - 1;
+ sites.push({ at: match.index, args: splitTopLevel(mask, open, groupEnd(mask, open)) });
+ }
+ return sites;
+}
+
+// The page component is the default export; React passes its first parameter the props. Returns
+// that parameter's name (or, for a destructured parameter, each property's local name) and the
+// component's lexical range as a scope, so its bindings are visible only inside it. A named
+// function component already has a scope; an arrow component's body is found after its `=>`.
+function pageComponent(mask, scopes) {
+ const exported = /\bexport\s+default\s+(?:async\s+)?(?:function\s+)?([A-Za-z_$][\w$]*)/.exec(mask);
+ if (!exported) return null;
+ const id = escapeRe(exported[1]);
+ const decl = new RegExp(`(?:\\bfunction\\s+${id}\\s*|\\b(?:const|let|var)\\s+${id}\\s*(?::[^=;]+)?=\\s*(?:async\\s*)?)\\(`).exec(mask);
+ if (!decl) return null;
+ const open = decl.index + decl[0].length - 1;
+ const close = groupEnd(mask, open);
+ const first = splitTopLevel(mask, open, close)[0] || '';
+ const pattern = /^\{([^{}]*)\}/.exec(first);
+ let scope = scopes.find((entry) => entry.paramsOpen === open);
+ if (!scope) {
+ const arrow = /^\s*(?::[^=]*?)?=>\s*/.exec(mask.slice(close + 1));
+ if (!arrow) return null;
+ const body = close + 1 + arrow[0].length;
+ const end = '({'.includes(mask[body]) ? groupEnd(mask, body) : (mask.indexOf(';', body) + 1 || mask.length);
+ scope = { name: exported[1], start: decl.index, paramsOpen: open, paramsEnd: close, body, end };
+ }
+ return {
+ scope: { ...scope, isComponent: true },
+ propsName: pattern ? null : (/^([A-Za-z_$][\w$]*)/.exec(first) || [])[1] || null,
+ destructured: pattern ? destructuredNames(pattern[1]) : new Map(),
+ };
+}
+
+// A declaration's complete initializer, from `start` to the end of its statement: a `;`, a
+// top-level `,` (the next declarator) or the end of the enclosing group. A line break ends it too
+// unless the next line continues the expression (`|| other`, `as Api`, `.member`).
+function initializerText(mask, start) {
+ // `const x =` followed by a line break: the initializer starts on a later line.
+ while (start < mask.length && /\s/.test(mask[start])) start += 1;
+ return mask.slice(start, expressionEnd(mask, start));
+}
+
+// Where the expression starting at `start` ends: a `;`, a top-level `,`, the end of the enclosing
+// group, or a line break where automatic semicolon insertion ends the statement — the text so far is
+// complete and the next line does not continue it (`dataApi as\n Api` and `dataApi\n || other`
+// both continue; a next line starting with `(`, `[` or a template continues it too).
+function expressionEnd(mask, start) {
+ for (let i = start; i < mask.length; i += 1) {
+ const ch = mask[i];
+ if ('({['.includes(ch)) { i = groupEnd(mask, i); continue; }
+ if (ch === '<') { const end = typeArgsEnd(mask, i); if (end > i) { i = end; continue; } }
+ if (';,)}]'.includes(ch)) return i;
+ if (ch === '\n') {
+ const unfinished = /(?:[=|&?:,.+\-*/%<>!]|\bas|\bsatisfies)\s*$/.test(mask.slice(start, i));
+ const continued = /^\s*(?:[|&?:.+\-*/%=<>,!([`]|as\b|satisfies\b)/.test(mask.slice(i + 1));
+ if (!unfinished && !continued) return i;
+ }
+ }
+ return mask.length;
+}
+// The name an initializer passes on unchanged: a reference chain, optionally cast (`as T`,
+// `satisfies T`) or non-null asserted. Anything that computes a different value (`a && b`,
+// `a ?? b`, a call, a conditional) returns null, so the alias proves nothing.
+function identityChain(text) {
+ const head = new RegExp(`^\\s*(${CHAIN})`).exec(text);
+ if (!head) return null;
+ // An arrow's `>` is not a closing angle, so name it before collapsing brackets.
+ let rest = text.slice(head[0].length).replace(/=>/g, ' fn ');
+ // Collapse bracketed type syntax (`{ … }`, `( … ) => T`, `[ … ]`, `< … >`) so only its outline is checked.
+ let previous;
+ do {
+ previous = rest;
+ rest = rest.replace(/\([^()]*\)|\{[^{}]*\}|\[[^[\]]*\]|<[^<>]*>/g, ' T ');
+ } while (rest !== previous);
+ return /^(?:\s*(?:as|satisfies)\s+(?:[\w$.]+|\s|\|(?!\|)|&(?!&))+)*\s*!?\s*$/.test(rest) ? head[1] : null;
+}
+
+// True when `name` is assigned or bound again anywhere (`name = x`, `name ??= x`, `name += x`) — any spot
+// that is not its declaration. The binding then no longer proves what it holds at the call, so it
+// is not trusted. Conservative: a same-named variable reassigned in another scope counts too, and a
+// default value (`{ name = x }`, `(name = x) =>`) does as well; both only ever refuse.
+function reassigned(mask, name) {
+ const id = escapeRe(name);
+ const word = new RegExp(`(?<![\\w$.])${id}(?![\\w$])`);
+ const re = new RegExp(`(?<![\\w$.])${id}\\s*(?:\\*\\*|<<|>>>?|&&|\\|\\||\\?\\?|[-+*/%&|^])?=(?![=>])`, 'g');
+ for (const match of mask.matchAll(re)) {
+ if (!/\b(?:const|let|var)\s+$/.test(mask.slice(Math.max(0, match.index - 12), match.index))) return true;
+ }
+ // A destructuring assignment writes every name in its pattern: `[client] = [other]`, `({ client } = x)`.
+ for (const match of mask.matchAll(/[\]}]\s*=(?![=>])/g)) {
+ const open = groupStart(mask, match.index);
+ if (open < 0 || /\b(?:const|let|var)\s*$/.test(mask.slice(Math.max(0, open - 8), open))) continue;
+ if (word.test(mask.slice(open, match.index))) return true;
+ }
+ // `for (client of list)` assigns without declaring.
+ if (new RegExp(`\\bfor\\s*\\(\\s*${id}\\s+(?:of|in)\\b`).test(mask)) return true;
+ // A loop head or catch clause that DECLARES the name binds it again, shadowing an outer binding
+ // (`for (const dataApi of [other])`, `catch (dataApi)`); treated the same way, everywhere.
+ for (const match of mask.matchAll(/\bfor\s*\(\s*(?:const|let|var)\s+([^;]*?)\s+(?:of|in)\b|\bcatch\s*\(([^)]*)\)/g)) {
+ if (word.test(match[1] || match[2] || '')) return true;
+ }
+ return false;
+}
+
+// The index of the bracket that `close` closes, scanning back; -1 when unbalanced.
+function groupStart(mask, close) {
+ const pairs = { ')': '(', '}': '{', ']': '[' };
+ const stack = [];
+ for (let i = close; i >= 0; i -= 1) {
+ if (pairs[mask[i]]) stack.push(pairs[mask[i]]);
+ else if ('({['.includes(mask[i])) {
+ if (stack.pop() !== mask[i]) return -1;
+ if (!stack.length) return i;
+ }
+ }
+ return -1;
+}
+
+// Every identifier a parameter list binds. Deliberately over-approximate: every name in it counts —
+// destructured, nested, array, rest and default patterns alike, and type names too — because a name
+// this misses would let an outer binding show through, while an extra one only ever refuses.
+function boundNames(paramsText) {
+ return [...String(paramsText).matchAll(/[A-Za-z_$][\w$]*/g)].map((m) => m[0]);
+}
+
+// Walk back from `end` (the index just before an arrow's `=>`, trailing spaces trimmed) over a return
+// type annotation (`): { result: T }`, `): Promise<void>`, `): A | B`) to the `)` closing the parameter
+// list. Returns that index, or -1 when there is no `:` annotation to skip.
+function paramsCloseBeforeReturnType(mask, end) {
+ let i = end;
+ while (i >= 0) {
+ const ch = mask[i];
+ if (/\s/.test(ch)) { i -= 1; continue; }
+ if (')}]'.includes(ch)) { const open = groupStart(mask, i); if (open < 0) return -1; i = open - 1; continue; }
+ if (ch === '>') {
+ let depth = 0;
+ let j = i;
+ for (; j >= 0; j -= 1) {
+ if (mask[j] === '>' && mask[j - 1] !== '=') depth += 1;
+ else if (mask[j] === '<') { depth -= 1; if (depth === 0) break; }
+ }
+ if (j < 0) return -1;
+ i = j - 1;
+ continue;
+ }
+ if (/[\w$.|&?,'"]/.test(ch) || (ch === '>' && mask[i - 1] === '=')) { i -= 1; continue; }
+ if (ch === ':') {
+ let k = i - 1;
+ while (k >= 0 && /\s/.test(mask[k])) k -= 1;
+ return mask[k] === ')' ? k : -1;
+ }
+ return -1;
+ }
+ return -1;
+}
+
+// Every function the named-helper list does not cover, as a scope whose callers cannot be traced:
+// arrows (`(a) =>`, `a =>`, with or without a return type) and anonymous `function (…) {}`
+// expressions. Their parameters bind as opaque names and shadow the same names outside them.
+function arrowScopes(mask) {
+ const scopes = [];
+ for (const match of mask.matchAll(/=>/g)) {
+ const before = mask.slice(0, match.index).replace(/\s+$/, '');
+ let names = [];
+ let paramsOpen = -1;
+ let close = before.length - 1;
+ if (before[close] !== ')') {
+ const typed = paramsCloseBeforeReturnType(mask, close);
+ if (typed >= 0) close = typed;
+ }
+ if (before[close] === ')') {
+ paramsOpen = groupStart(mask, close);
+ if (paramsOpen < 0) continue;
+ names = boundNames(mask.slice(paramsOpen + 1, close));
+ } else {
+ const single = /([A-Za-z_$][\w$]*)$/.exec(before);
+ if (!single || /^(?:async|await|return)$/.test(single[1])) continue;
+ names = [single[1]];
+ paramsOpen = before.length - single[1].length;
+ }
+ let body = match.index + 2;
+ while (/\s/.test(mask[body] || '')) body += 1;
+ const bodyEnd = mask[body] === '{' ? groupEnd(mask, body) : expressionEnd(mask, body);
+ scopes.push({ arrow: true, names, paramsOpen, body: match.index, end: bodyEnd });
+ }
+ // `function (…) {` and `function* (…) {` with no name: a value, so its callers are untraceable too.
+ for (const match of mask.matchAll(/\bfunction\s*\*?\s*\(/g)) {
+ const paramsOpen = match.index + match[0].length - 1;
+ const paramsEnd = groupEnd(mask, paramsOpen);
+ const body = mask.indexOf('{', paramsEnd);
+ if (body < 0) continue;
+ scopes.push({ arrow: true, names: boundNames(mask.slice(paramsOpen + 1, paramsEnd)), paramsOpen, body: paramsOpen, end: groupEnd(mask, body) });
+ }
+ return scopes;
+}
+// The bindings of `name` visible at `at`, innermost only: a parameter of an enclosing named helper
+// or of the page component (its first parameter is the props), or a declaration (`const x = …`,
+// `const { … } = …`) inside an enclosing scope or outside every scope. A binding inside a scope
+// that does not enclose `at` (another helper, or the component seen from a helper outside it) is
+// not visible. Several bindings at the same level must all resolve.
+function bindingsOf(ctx, name, at) {
+ const { mask, scopes, component } = ctx;
+ const found = [];
+ const levelOf = (index) => {
+ const scope = innermostScope(scopes, index);
+ if (!scope) return -1;
+ return scope.body < at && scope.end > at ? scope.body : null;
+ };
+ for (const scope of scopes.filter((entry) => entry.body < at && entry.end > at)) {
+ if (scope.arrow) {
+ if (scope.names.includes(name)) found.push({ level: scope.body, kind: 'opaque' });
+ continue;
+ }
+ if (scope.isComponent) {
+ if (component.propsName === name) found.push({ level: scope.body, kind: 'props' });
+ const property = component.destructured.get(name);
+ if (property) found.push({ level: scope.body, kind: 'prop-member', property });
+ continue;
+ }
+ // A named helper's parameter is what its callers pass. A plain one (`api`, `api: ActionApi`,
+ // `api = fallback`) is traced through every call; a destructured `{ dataApi }` / `{ dataApi: api }`
+ // is that property of what every call passes; any other name a parameter binds (a nested, array
+ // or rest pattern, a rest parameter) is opaque. Each of them shadows the same name outside.
+ splitTopLevel(mask, scope.paramsOpen, scope.paramsEnd).forEach((param, index) => {
+ const plain = param.startsWith('...') ? null : /^([A-Za-z_$][\w$]*)/.exec(param);
+ if (plain) {
+ if (plain[1] === name) found.push({ level: scope.body, kind: 'param', scope, index, name });
+ return;
+ }
+ const pattern = /^\{([^{}]*)\}/.exec(param);
+ const property = pattern ? destructuredNames(pattern[1]).get(name) : undefined;
+ if (property) found.push({ level: scope.body, kind: 'param-member', scope, index, name, property });
+ else if (boundNames(param).includes(name)) found.push({ level: scope.body, kind: 'opaque' });
+ });
+ }
+ for (const match of mask.matchAll(new RegExp(`\\b(?:const|let|var)\\s+${escapeRe(name)}\\s*(?::[^=;]+)?=`, 'g'))) {
+ const level = levelOf(match.index);
+ if (level === null) continue;
+ // The whole initializer must pass the value on: `const a = dataApi && other` is not `dataApi`.
+ const expr = identityChain(initializerText(mask, match.index + match[0].length));
+ found.push(expr ? { level, kind: 'alias', expr, at: match.index } : { level, kind: 'opaque' });
+ }
+ for (const match of mask.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*(?::[^=;]+)?=/g)) {
+ const property = destructuredNames(match[1]).get(name);
+ const level = property ? levelOf(match.index) : null;
+ if (level === null) continue;
+ const object = identityChain(initializerText(mask, match.index + match[0].length));
+ found.push(object ? { level, kind: 'member', object, property, at: match.index } : { level, kind: 'opaque' });
+ }
+ if (!found.length) return [];
+ const innermost = Math.max(...found.map((binding) => binding.level));
+ const visible = found.filter((binding) => binding.level === innermost);
+ // A name assigned again after its declaration (or a parameter overwritten in its helper) proves nothing.
+ return reassigned(mask, name) ? visible.map((binding) => ({ ...binding, kind: 'opaque' })) : visible;
+}
+
+// A helper parameter is what its callers pass. A recursive call that passes the same PLAIN parameter on
+// adds no provenance, so it is not counted; with no other caller, nothing is proven. A destructured
+// parameter's local is not the argument it came from — `run(dataApi)` inside `run({ dataApi })` hands
+// the next call the property, not the props — so for one of those every call is checked.
+function paramFilledWith(ctx, binding, depth, resolve) {
+ const { scope, index, name, kind } = binding;
+ const sites = callSites(ctx.mask, scope.name)
+ .filter((site) => !(kind === 'param' && site.at > scope.body && site.at < scope.end && identityChain(site.args[index] || '') === name));
+ return sites.length > 0 && sites.every((site) => resolve(ctx, site.args[index], site.at, depth + 1));
+}
+
+// Is `expr` the props object React passed the page component?
+function isPropsObject(ctx, expr, at, depth = 0) {
+ if (!expr || depth > 8) return false;
+ // The whole expression must pass the value on: `props as Props && other` is `other`.
+ const chain = identityChain(expr);
+ const name = chain ? normalizeChain(chain) : null;
+ if (!name || !IDENT.test(name)) return false;
+ const bindings = bindingsOf(ctx, name, at);
+ return bindings.length > 0 && bindings.every((binding) => {
+ if (binding.kind === 'props') return true;
+ if (binding.kind === 'param') return paramFilledWith(ctx, binding, depth, isPropsObject);
+ if (binding.kind === 'alias') return isPropsObject(ctx, binding.expr, binding.at, depth + 1);
+ return false;
+ });
+}
+
+// Is `expr` the props' `dataApi`?
+function isDataApi(ctx, expr, at, depth = 0) {
+ if (!expr || depth > 8) return false;
+ const chain = identityChain(expr);
+ if (!chain) return false;
+ const name = normalizeChain(chain);
+ const member = /^([A-Za-z_$][\w$]*)\.dataApi$/.exec(name);
+ if (member) return isPropsObject(ctx, member[1], at, depth + 1);
+ if (!IDENT.test(name)) return false;
+ const bindings = bindingsOf(ctx, name, at);
+ return bindings.length > 0 && bindings.every((binding) => {
+ if (binding.kind === 'param') return paramFilledWith(ctx, binding, depth, isDataApi);
+ if (binding.kind === 'alias') return isDataApi(ctx, binding.expr, binding.at, depth + 1);
+ if (binding.kind === 'member') return binding.property === 'dataApi' && isPropsObject(ctx, binding.object, binding.at, depth + 1);
+ if (binding.kind === 'param-member') return binding.property === 'dataApi' && paramFilledWith(ctx, binding, depth, isPropsObject);
+ if (binding.kind === 'prop-member') return binding.property === 'dataApi';
+ return false; // the props object itself is not its dataApi
+ });
+}
+
+// The Custom API surface is the page's `dataApi` prop, so a call or presence check on any other
+// object proves nothing. A receiver counts only when it provably is that prop: `<props>.dataApi`
+// where <props> is the page component's props parameter, a name destructured from those props or
+// assigned from such a name (casts allowed), or a parameter of an enclosing helper that every
+// outside call fills with one of those. Anything unresolvable fails.
+function receiverIsDataApi(mask, scopes, expr, at) {
+ const component = pageComponent(mask, scopes);
+ const named = component
+ ? [...scopes.filter((scope) => scope.paramsOpen !== component.scope.paramsOpen), component.scope]
+ : scopes;
+ // The component itself may be an arrow; it is already in the list as the component scope.
+ const arrows = arrowScopes(mask).filter((scope) => !component || scope.paramsOpen !== component.scope.paramsOpen);
+ const all = [...named, ...arrows];
+ return isDataApi({ mask, scopes: all, component }, expr, at);
+}
+module.exports = { groupEnd, literalString, objectFields, actionCalls, receiverIsDataApi, escapeRe };
diff --git a/evals/model-apps/genpage/lib/upload-contract.js b/evals/model-apps/genpage/lib/upload-contract.js
new file mode 100644
index 000000000..933588a51
--- /dev/null
+++ b/evals/model-apps/genpage/lib/upload-contract.js
@@ -0,0 +1,210 @@
+'use strict';
+
+const { isDeepStrictEqual } = require('node:util');
+const { unescapePacName } = require('../../../../plugins/model-apps/scripts/lib/genpage-cli.js');
+const { currentContract, workflowCalls, isUpload, isObject, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
+const { artifactText, artifactJson, commandInfo, isGuid, pathKey } = require('./evidence-utils.js');
+
+const sameJson = (left, right) => isDeepStrictEqual(JSON.parse(JSON.stringify(left)), JSON.parse(JSON.stringify(right)));
+const switchOn = (value) => value === true || value === 'true';
+
+function bindingSet(value, idKey) {
+ if (!Array.isArray(value)) throw new Error(`${idKey} bindings must be an array`);
+ const names = value.map((entry) => entry?.[idKey]);
+ if (names.some((name) => typeof name !== 'string' || !name.trim()) || new Set(names).size !== names.length) {
+ throw new Error(`${idKey} bindings need unique non-empty names`);
+ }
+ return [...value].sort((a, b) => a[idKey].localeCompare(b[idKey]));
+}
+
+function desiredBindings(before, change, idKey) {
+ bindingSet(before, idKey);
+ if (change === undefined) return before;
+ if (!isObject(change)) throw new Error(`invalid ${idKey} binding change`);
+ if (change.clear === true) {
+ if ((change.add || []).length || (change.remove || []).length) throw new Error(`clear ${idKey} cannot also add or remove bindings`);
+ return [];
+ }
+ const rows = new Map(before.map((entry) => [entry[idKey], entry]));
+ for (const name of change.remove || []) {
+ if (!rows.delete(name)) throw new Error(`cannot remove unknown ${idKey} ${name}`);
+ }
+ for (const row of change.add || []) rows.set(row[idKey], row);
+ return bindingSet([...rows.values()], idKey);
+}
+
+function sameBindings(left, right, idKey) {
+ return sameJson(bindingSet(left, idKey), bindingSet(right, idKey));
+}
+
+function warningPresent(result, pattern) {
+ return Array.isArray(result?.warnings) && result.warnings.some((warning) => typeof warning === 'string' && pattern.test(warning));
+}
+
+function uploadTransportProblems(fixture) {
+ if (!currentContract(fixture)) return [];
+ const problems = unassociatedCallProblems(fixture);
+ const calls = workflowCalls(fixture).filter((entry) => isUpload(entry.command));
+ if (!calls.length) problems.push('no upload invocation recorded');
+ for (const call of calls) {
+ const { flags, problems: flagProblems } = commandInfo(call);
+ problems.push(...flagProblems);
+ if (!/\bgenpage-upload\.js\b/.test(call.command) || /\bpac(?:\.exe|\.cmd)?\s+model\s+genpage\s+upload\b/.test(call.command)) {
+ problems.push('current uploads must use scripts/genpage-upload.js, never raw pac transport');
+ }
+ for (const flag of ['name', 'prompt', 'agent-message']) {
+ if (Object.hasOwn(flags, flag)) problems.push(`current upload uses inline --${flag} instead of file transport`);
+ }
+ for (const flag of ['prompt-file', 'agent-message-file', ...(!flags['page-id'] ? ['name-file'] : [])]) {
+ if (typeof flags[flag] !== 'string' || !artifactText(fixture, flags[flag]).trim()) problems.push(`upload lacks a non-empty --${flag} artifact`);
+ }
+ if (!isGuid(flags['app-id'])) problems.push('upload app-id is not a GUID');
+ const result = resultObject(call);
+ if (!result || typeof result.ok !== 'boolean') problems.push('upload result is malformed or missing');
+ if (flags['page-id'] && (!isGuid(flags['page-id']) || switchOn(flags['add-to-sitemap']))) problems.push('update must name a valid page id and omit sitemap placement');
+ if (!flags['page-id'] && !switchOn(flags['add-to-sitemap'])) problems.push('create must include --add-to-sitemap');
+ if (result?.ok && (!isGuid(result.pageId) || result.appId !== flags['app-id'] || (flags['page-id'] && result.pageId !== flags['page-id']))) {
+ problems.push('upload result does not preserve the requested app/page identity');
+ }
+ for (const [flag, idKey] of [['connectors', 'logicalName'], ['actions', 'name']]) {
+ if (flags[flag]) {
+ const bindings = artifactJson(fixture, flags[flag]);
+ bindingSet(bindings, idKey);
+ if (flag === 'connectors' && bindings.some((entry) => Object.keys(entry).some((key) => /^connectionid$/i.test(key)))) {
+ problems.push('connector binding files must not contain environment-specific ConnectionId values');
+ }
+ }
+ }
+ }
+ return problems;
+}
+
+function uploadProblems(fixture) {
+ const problems = uploadTransportProblems(fixture);
+ if (!currentContract(fixture)) return problems;
+ const calls = workflowCalls(fixture).filter((call) => isUpload(call.command));
+ const rows = fixture.manifest?.uploads;
+ if (!rows) return problems;
+ if (!Array.isArray(rows) || rows.length !== calls.length || new Set(rows.map((row) => row.event)).size !== rows.length) {
+ return [...problems, 'upload evidence must cover every associated upload exactly once'];
+ }
+ for (const row of rows) {
+ const call = calls.find((entry) => entry.id === row.event);
+ if (!call) { problems.push(`missing upload result ${row.event}`); continue; }
+ const { flags } = commandInfo(call);
+ const result = resultObject(call);
+ const update = row.mode === 'update';
+ if (update !== Boolean(flags['page-id'])) problems.push(`${row.event}: create/update flags disagree with the approved operation`);
+ for (const [field, fileFlag, approved] of [
+ ['prompt', 'prompt-file', row.approvedPrompt],
+ ['agentMessage', 'agent-message-file', row.approvedAgentMessage],
+ ]) {
+ const text = artifactText(fixture, flags[fileFlag]).replace(/^\uFEFF/, '');
+ if (typeof approved !== 'string' || text !== approved) problems.push(`${row.event}: ${field} file rewrites approved text`);
+ if (result?.ok && call.forwarded?.[field] !== text) problems.push(`${row.event}: ${field} forwarded to PAC differs from exact file text`);
+ }
+ const changes = row.changes || {};
+ const explicitName = update ? changes.name : row.approvedName;
+ let suppliedName;
+ if (flags['name-file']) suppliedName = artifactText(fixture, flags['name-file']).replace(/^\uFEFF/, '').replace(/(?:\r?\n)+$/, '');
+ if (explicitName !== undefined && (suppliedName !== explicitName || typeof explicitName !== 'string')) problems.push(`${row.event}: name-file does not preserve the approved name`);
+ if (update && explicitName === undefined && flags['name-file']) problems.push(`${row.event}: unrelated edit supplied an unapproved rename`);
+ const shim = /\.cmd$/i.test(call.pacExecutable || '');
+ const refusedName = suppliedName?.includes('"') || (shim && suppliedName?.includes('%'));
+ if (row.outcome === 'refused') {
+ if (!refusedName || result?.ok !== false || call.pacWrites !== 0 || call.forwarded !== undefined) {
+ problems.push(`${row.event}: unsafe name was not refused before PAC writes`);
+ }
+ const expected = suppliedName?.includes('"') ? /ASCII|double quote/i : /pac\.cmd.*%|%.*pac\.cmd/i;
+ if (!expected.test(result?.error || result?.message || '')) problems.push(`${row.event}: name refusal lacks actionable quote/shim advice`);
+ continue;
+ }
+ if (refusedName || result?.ok !== true || call.pacWrites !== 1) problems.push(`${row.event}: expected successful upload is refused or has no single PAC write`);
+ const afterConfig = artifactJson(fixture, row.afterConfig);
+ const afterPage = artifactJson(fixture, row.afterPage);
+ if (!isObject(afterConfig) || !isObject(afterPage)) throw new Error(`${row.event}: after config/page metadata must be objects`);
+ if (afterPage.pageId !== result?.pageId || afterPage.appId !== result?.appId) problems.push(`${row.event}: read-back identity differs from the upload result`);
+ const beforeConfig = update ? artifactJson(fixture, row.beforeConfig) : {};
+ const beforePage = update ? artifactJson(fixture, row.beforePage) : {};
+ if (!isObject(beforeConfig) || !isObject(beforePage)) throw new Error(`${row.event}: before config/page metadata must be objects`);
+ if (update && (beforePage.pageId !== flags['page-id'] || beforePage.appId !== flags['app-id'])) problems.push(`${row.event}: update does not target the downloaded page in its app`);
+ if (update && afterPage.navigationTitle !== beforePage.navigationTitle) problems.push(`${row.event}: rename changed the untouched sitemap title`);
+
+ let expectedSentName = explicitName;
+ let expectedStoredName = explicitName;
+ if (update && explicitName === undefined) {
+ const read = call.reads?.name;
+ if (!read || typeof read.ok !== 'boolean') problems.push(`${row.event}: omitted name lacks an associated own-name read`);
+ const current = read?.ok ? read.value : null;
+ if (read?.ok && current !== beforePage.name) problems.push(`${row.event}: name read is not the page's own name`);
+ const unsent = shim && typeof current === 'string' && /[%"]/.test(current);
+ if (!current || unsent) {
+ expectedSentName = undefined;
+ expectedStoredName = beforePage.navigationTitle;
+ const warning = unsent ? /name.*could not be sent.*(?:pac\.cmd|%|quote)/i : /could not read.*name|name.*could not be read/i;
+ if (!warningPresent(result, warning)) problems.push(`${row.event}: unreadable/unsendable implicit name changed without a warning`);
+ } else {
+ expectedSentName = unescapePacName(current);
+ expectedStoredName = expectedSentName.replace(/"/g, '\\"');
+ if (/(?:^|[^\\])"/.test(current) && !warningPresent(result, /name.*double quote|double quote.*name/i)) {
+ problems.push(`${row.event}: native PAC's quote-storage loss is not warning-visible`);
+ }
+ }
+ }
+ if (call.forwarded?.name !== expectedSentName || afterPage.name !== expectedStoredName) problems.push(`${row.event}: own page name was changed or escaped again without approved intent`);
+ if (!update && afterPage.navigationTitle !== explicitName) problems.push(`${row.event}: create navigation title differs from the approved name`);
+
+ const configRead = call.reads?.config;
+ const explicitModel = changes.model !== undefined ? changes.model : flags.model;
+ if (changes.model !== undefined && flags.model !== changes.model) problems.push(`${row.event}: explicit model does not match the approved change`);
+ if (update && changes.model === undefined && flags.model && flags.model !== beforeConfig.model) problems.push(`${row.event}: model changed without approved intent`);
+ let expectedModel = explicitModel || (typeof beforeConfig.model === 'string' ? beforeConfig.model.trim() : '');
+ if (update && !flags.model && configRead?.ok === false) {
+ expectedModel = '';
+ if (!warningPresent(result, /could not read.*model|model.*could not be read/i)) problems.push(`${row.event}: unreadable model loss is not warning-visible`);
+ } else if (update && !flags.model && (!configRead || configRead.ok !== true || pathKey(configRead.artifact) !== pathKey(row.beforeConfig))) {
+ problems.push(`${row.event}: omitted model lacks an associated config read`);
+ }
+ if (call.forwarded?.model !== (expectedModel || undefined) || (afterConfig.model || '') !== expectedModel) problems.push(`${row.event}: model read-back/forwarding does not preserve omission or explicit intent`);
+
+ const beforeSources = beforeConfig.dataSources || [];
+ if (!Array.isArray(beforeSources)) throw new Error(`${row.event}: dataSources is not an array`);
+ const clearSources = switchOn(flags['clear-data-sources']);
+ if (clearSources && flags['data-sources']) problems.push(`${row.event}: clear-data-sources contradicts data-sources`);
+ const sentSources = typeof flags['data-sources'] === 'string' ? flags['data-sources'].split(',').map((source) => source.trim()) : clearSources ? [] : beforeSources;
+ const expectedSources = changes.dataSources || beforeSources;
+ if (!sameJson(sentSources, expectedSources) || !sameJson(afterConfig.dataSources || [], expectedSources)
+ || !sameJson(call.forwarded?.dataSources || [], expectedSources)) problems.push(`${row.event}: data-source bindings changed without explicit intent`);
+ if (update && !flags['data-sources'] && !clearSources && configRead?.ok !== true) problems.push(`${row.event}: unreadable data sources must refuse, not become an empty success`);
+
+ for (const [kind, flag, field, idKey] of [
+ ['connectors', 'connectors', 'connectorBindings', 'logicalName'],
+ ['actions', 'actions', 'actionBindings', 'name'],
+ ]) {
+ const before = beforeConfig[field] || [];
+ const desired = desiredBindings(before, changes[kind], idKey);
+ if (changes[kind] === undefined) {
+ if (flags[flag]) problems.push(`${row.event}: unchanged ${kind} must omit --${flag}`);
+ } else {
+ if (!flags[flag] || !sameBindings(artifactJson(fixture, flags[flag]), desired, idKey)) problems.push(`${row.event}: ${kind} full replacement drops untouched bindings or differs from approved add/remove/clear`);
+ }
+ if (!sameBindings(afterConfig[field] || [], desired, idKey)) problems.push(`${row.event}: ${kind} read-back loses preserved or intended bindings`);
+ }
+ }
+ return problems;
+}
+
+// The two dedicated preservation assertions grade the recorded before/after snapshots in
+// manifest.uploads. uploadProblems falls back to the transport verdict when a fixture records
+// none (right for the common upload assertion), but here that let both assertions pass with
+// their evidence deleted. So each requires a row for its own mode: a non-refused create, or an
+// update.
+function uploadPreservationProblems(fixture, mode) {
+ const rows = fixture.manifest?.uploads;
+ if (!currentContract(fixture) || !Array.isArray(rows) || !rows.some((row) => row && row.mode === mode && row.outcome !== 'refused')) {
+ return [`no ${mode} upload preservation evidence (manifest.uploads) to grade`];
+ }
+ return uploadProblems(fixture);
+}
+
+module.exports = { uploadProblems, uploadPreservationProblems, uploadTransportProblems, desiredBindings, sameBindings };
diff --git a/evals/model-apps/genpage/lib/worker-contract.js b/evals/model-apps/genpage/lib/worker-contract.js
new file mode 100644
index 000000000..6c6cf8ad0
--- /dev/null
+++ b/evals/model-apps/genpage/lib/worker-contract.js
@@ -0,0 +1,53 @@
+'use strict';
+
+const { pageStructureProblems } = require('../../../../plugins/model-apps/scripts/lib/page-structure.js');
+const { workflowCalls, isUpload, resultObject } = require('./workflow-evidence.js');
+const { artifactText, commandInfo, fileName } = require('./evidence-utils.js');
+
+function workerProblems(fixture) {
+ const targets = fixture.manifest?.worker?.targets;
+ if (!Array.isArray(targets) || !targets.length) return ['worker evidence omits its target files'];
+ const states = new Map(targets.map((target) => [target, { stamp: false, written: null, accepted: null, attempts: 0, uploaded: false }]));
+ const problems = [];
+ for (const call of workflowCalls(fixture)) {
+ const { flags } = commandInfo(call);
+ const gate = /\bgenpage-worker-output\.js\b/.test(call.command);
+ const writing = /^Write\s+/.test(call.command);
+ if (!gate && !writing && !isUpload(call.command)) continue;
+ const target = gate ? fileName(flags.file) : writing ? fileName(call.command.slice(6)) : fileName(flags['code-file']);
+ const state = states.get(target);
+ if (!state) { problems.push(`worker command names an undeclared target ${target}`); continue; }
+ const result = resultObject(call);
+ if (gate && flags.stamp) {
+ if (result?.ok !== true || result.action !== 'stamp') problems.push(`${target}: dispatch stamp failed or is missing`);
+ state.stamp = result?.ok === true;
+ state.written = null;
+ state.accepted = null;
+ } else if (writing) {
+ if (!state.stamp) problems.push(`${target}: regeneration was not freshly stamped`);
+ state.written = artifactText(fixture, call.artifact);
+ state.accepted = null;
+ } else if (gate) {
+ state.attempts += 1;
+ if (!state.stamp || state.written === null) problems.push(`${target}: worker did not write since dispatch`);
+ const snapshot = artifactText(fixture, call.artifact);
+ if (snapshot !== state.written) problems.push(`${target}: completeness gate checked different bytes from the worker write`);
+ const actual = pageStructureProblems(snapshot);
+ if (result?.ok !== (actual.length === 0) || JSON.stringify(result?.problems) !== JSON.stringify(actual)) {
+ problems.push(`${target}: recorded gate result disagrees with the production completeness gate`);
+ }
+ state.accepted = result?.ok === true && !actual.length ? snapshot : null;
+ state.stamp = false;
+ if (state.attempts > 2) problems.push(`${target}: failed worker was regenerated more than once`);
+ } else {
+ if (state.accepted === null) problems.push(`${target}: rejected worker output reached upload before a successful regeneration gate`);
+ if (artifactText(fixture, target) !== state.accepted) problems.push(`${target}: uploaded TSX is not the complete accepted artifact`);
+ if (result?.ok !== true) problems.push(`${target}: regenerated page upload did not succeed`);
+ state.uploaded = true;
+ }
+ }
+ for (const [target, state] of states) if (!state.uploaded) problems.push(`${target}: no upload of the accepted regeneration`);
+ return problems;
+}
+
+module.exports = { workerProblems };
diff --git a/evals/model-apps/genpage/lib/workflow-evidence.js b/evals/model-apps/genpage/lib/workflow-evidence.js
new file mode 100644
index 000000000..556417321
--- /dev/null
+++ b/evals/model-apps/genpage/lib/workflow-evidence.js
@@ -0,0 +1,257 @@
+'use strict';
+
+const { parsePacConnectionList } = require('../../../../plugins/model-apps/scripts/list-connections.js');
+const { commandInfo } = require('./evidence-utils.js');
+const { planSection } = require('./plan-evidence.js');
+
+const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+const currentContract = (fixture) => (fixture.contractVersion || fixture.manifest?.contractVersion || 1) >= 2;
+const isUpload = (command) => /\bgenpage-upload\.js\b|\bpac(?:\.exe|\.cmd)?\s+model\s+genpage\s+upload\b/i.test(command);
+const isAuth = (command) => /\bcheck-auth\.js\b/.test(command);
+const isDiscovery = (command) => /\blist-connections\.js\b/.test(command);
+const isMutation = (command) => isUpload(command)
+ || /\b(?:provision-entities|create-table|add-column|create-relationship|create-record|create-connection-reference|add-page-to-solution|provision-solution)\.js\b/.test(command)
+ || /\bpac(?:\.exe|\.cmd)?\s+model\s+create\b|\b(?:create-connection|auth-switch)\b/.test(command)
+ || /\b(?:Task|Dispatched)\s+genpage-entity-builder\b|\bgenpage-entity-builder\s+invoked\b/i.test(command);
+const isGeneration = (command) => /\b(?:Task|Write|Edit|Generate)\b[^\n]*(?:genpage-page-builder|\.tsx\b)/i.test(command);
+
+function resultObject(call) {
+ if (isObject(call.result)) return call.result;
+ if (typeof call.result !== 'string') return null;
+ try {
+ const value = JSON.parse(call.result);
+ return isObject(value) ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+function historicalResult(text) {
+ // Captures use `node check-auth.js -> ok: true`, `Result: ok=false, blocker=whoami_403`,
+ // or an abbreviated `{ ok: true, ... }`. Read the FIRST attached result only, never an
+ // arbitrary later `ok:true` in the log. JSON-looking but broken results must not fall
+ // back to a substring match. These summaries are compatibility evidence, not current JSON.
+ const match = /(?:^\s*[-*]?\s*Result:\s*|(?:\u2192|->)\s*(?:returned\s*)?)([^\n]*)/im.exec(text);
+ const raw = match ? match[1].trim().replace(/^`|`$/g, '') : '';
+ if (/^\{\s*"/.test(raw) || /^\[/.test(raw)) {
+ try { return JSON.parse(raw); } catch { return null; }
+ }
+ const abbreviated = /^\{\s*ok:\s*(true|false)\s*,\s*\.\.\.\s*\}$/.exec(raw);
+ if (abbreviated) return { ok: abbreviated[1] === 'true' };
+ const ok = /^ok\s*[:=]\s*(true|false)\b/i.exec(raw);
+ if (ok) {
+ const blocker = /\bblocker\s*[:=]\s*['"]?([a-z_]+)/i.exec(raw);
+ const identities = /\bidentitiesMatch\s*[:=]\s*(true|false)\b/i.exec(raw);
+ return {
+ ok: ok[1].toLowerCase() === 'true',
+ ...(blocker && { blocker: blocker[1] }),
+ ...(identities && { identitiesMatch: identities[1].toLowerCase() === 'true' }),
+ };
+ }
+ const connections = /^(\d+)\s+connections?\s+found\b/i.exec(raw);
+ if (connections) return { ok: true, connectionsFound: Number(connections[1]) };
+ return null;
+}
+
+function workflowCalls(fixture) {
+ if (Array.isArray(fixture.events)) return fixture.events;
+ const lines = String(fixture.workflowLog || '').split(/\r?\n/);
+ const calls = [];
+ let active = null;
+ for (const line of lines) {
+ const command = /\b(?:node(?:\.exe)?\s+|pac(?:\.exe|\.cmd)?\s+|npx(?:\.cmd)?\s+|Task\s+genpage-|Dispatched\s+genpage-|genpage-entity-builder\s+invoked\b)/i.exec(line);
+ if (command && !/^\s*#/.test(line) && !/\bnot\s+(?:run|invoked)\b|\bSKIPPED\b/i.test(line)) {
+ if (active) calls.push({ ...active, result: historicalResult(active.text) });
+ active = { id: `log-${calls.length + 1}`, command: line.slice(command.index), text: line, historical: true };
+ } else if (active) {
+ // A heading ends the result block, even if its next phase contains no command.
+ if (/^\s*#/.test(line)) {
+ calls.push({ ...active, result: historicalResult(active.text) });
+ active = null;
+ } else {
+ active.text += '\n' + line;
+ }
+ }
+ }
+ if (active) calls.push({ ...active, result: historicalResult(active.text) });
+ return calls;
+}
+
+function unassociatedCallProblems(fixture) {
+ if (!currentContract(fixture) || !Array.isArray(fixture.events)) return [];
+ const operation = (command) => /\bpac(?:\.exe|\.cmd)?\s+model\s+genpage\s+upload\b/.test(command)
+ ? 'raw-pac-upload' : command.match(/\b([\w-]+)\.js\b/)?.[1]
+ || command.match(/\b(?:create-connection|auth-switch|genpage-entity-builder)\b/)?.[0] || command;
+ const risky = (call) => isAuth(call.command) || isDiscovery(call.command) || isMutation(call.command) || isGeneration(call.command);
+ const counts = (calls) => {
+ const map = new Map();
+ for (const call of calls.filter(risky)) {
+ const key = operation(call.command);
+ map.set(key, (map.get(key) || 0) + 1);
+ }
+ return map;
+ };
+ const logged = counts(workflowCalls({ workflowLog: fixture.workflowLog }));
+ const recorded = counts(fixture.events);
+ return [...logged].filter(([key, count]) => count > (recorded.get(key) || 0))
+ .map(([key]) => `${key}: logged command has no associated result event`);
+}
+
+function authGateProblems(fixture, { required = false } = {}) {
+ const calls = workflowCalls(fixture);
+ const gates = calls.filter((call) => isAuth(call.command));
+ const problems = unassociatedCallProblems(fixture);
+ if (gates.length === 0) return required ? [...problems, 'check-auth.js not invoked'] : problems;
+ const strict = currentContract(fixture);
+ let latest = null;
+ let timeoutAttempts = 0;
+ const normalizedEnv = (value) => typeof value === 'string' ? value.trim().replace(/\/+$/, '').toLowerCase() : null;
+ const plannedEnv = /^\s*[-*]?\s*URL:\s*(https:\/\/\S+)/m.exec(planSection(fixture.genpagePlan, 'Environment') || '')?.[1];
+ for (const call of calls) {
+ if (isAuth(call.command)) {
+ const result = resultObject(call);
+ latest = { call, result };
+ if (!result || typeof result.ok !== 'boolean') {
+ problems.push(`${call.id || 'check-auth'}: malformed or missing auth result`);
+ continue;
+ }
+ if (strict && !/--require-pac\b/.test(call.command)) problems.push('genpage auth gate is missing --require-pac');
+ if (strict && (typeof result.message !== 'string' || !result.message.trim()
+ || !Array.isArray(result.warnings) || result.warnings.some((warning) => typeof warning !== 'string'))) {
+ problems.push('auth result has malformed message/warnings fields');
+ }
+ if (result.ok) {
+ if (result.blocker != null || (strict && (result.blocker !== null || result.whoAmI?.ok !== true))) {
+ problems.push('auth ok:true contradicts its blocker or WhoAmI result');
+ }
+ if (strict && typeof result.identitiesMatch !== 'boolean') problems.push('auth result omits identitiesMatch');
+ if (strict && (typeof result.envUrl !== 'string' || !/^https:\/\/[^/\s]+\/?$/.test(result.envUrl))) problems.push('successful auth result omits its environment URL');
+ const requestedEnv = commandInfo(call).flags.env;
+ if (strict && ((typeof requestedEnv === 'string' && /^https:\/\//.test(requestedEnv) && normalizedEnv(requestedEnv) !== normalizedEnv(result.envUrl))
+ || (plannedEnv && normalizedEnv(plannedEnv) !== normalizedEnv(result.envUrl)))) {
+ problems.push('successful auth gate belongs to a different command/plan environment');
+ }
+ if (strict && result.identitiesMatch === false && call.userMessage !== result.message) {
+ problems.push('warning-only identity mismatch was not surfaced verbatim');
+ }
+ timeoutAttempts = 0;
+ } else {
+ if (strict && (typeof result.blocker !== 'string' || !result.blocker || typeof result.message !== 'string' || !result.message)) {
+ problems.push('failed auth result omits its blocker or advice');
+ }
+ if (strict && call.userMessage !== result.message) problems.push('auth failure advice was not surfaced verbatim');
+ if (/^(az|pac)_timeout$/.test(result.blocker || '')) {
+ timeoutAttempts += 1;
+ if (timeoutAttempts > 2) problems.push('auth timeout retried more than once');
+ if (strict && (!/did not answer|timed? out|too slow|timeout/i.test(result.message || '')
+ || /\bis (?:not installed|signed out|not logged in)\b/i.test(result.message || ''))) {
+ problems.push(`${result.blocker} was misreported as absent or signed out`);
+ }
+ } else {
+ timeoutAttempts = 0;
+ }
+ }
+ } else if (isMutation(call.command)) {
+ if (!latest || latest.result?.ok !== true || latest.result.blocker != null) {
+ problems.push(`${call.command}: mutation attempted without the latest successful auth gate`);
+ } else if (strict) {
+ // A successful WhoAmI for one environment does not authorize a write to another.
+ // Only visible literal URLs are compared; evaluating shell variables would execute evidence.
+ const info = commandInfo(call);
+ const env = info.flags.env || info.positional.find((value) => /^https:\/\//.test(value));
+ if (typeof env === 'string' && /^https:\/\//.test(env) && normalizedEnv(env) !== normalizedEnv(latest.result.envUrl)) {
+ problems.push('mutation environment differs from the latest successful auth gate');
+ }
+ }
+ }
+ }
+ if (latest?.result?.ok === false && strict) {
+ if (!/\bhalt(?:ed)?\b|\bstop(?:ped)?\b|\bneeds_input\b/i.test(fixture.workflowLog || '')) {
+ problems.push('final failed auth gate did not halt the workflow');
+ }
+ if (/^(az|pac)_timeout$/.test(latest.result.blocker || '')) {
+ if (timeoutAttempts !== 2) problems.push('final auth timeout lacks the one bounded retry');
+ if (latest.result.blocker === 'az_timeout' && !/POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS/.test(latest.result.message || '')) {
+ problems.push('final Azure CLI timeout omits the configurable budget advice');
+ }
+ }
+ }
+ return problems;
+}
+
+function discoveryProblems(fixture, { required = false, needsBinding = false } = {}) {
+ const calls = workflowCalls(fixture);
+ let latest = null;
+ const strict = currentContract(fixture);
+ const problems = unassociatedCallProblems(fixture);
+ for (const call of calls) {
+ if (isDiscovery(call.command)) {
+ const result = resultObject(call);
+ latest = { call, result };
+ if (!result || typeof result.ok !== 'boolean') {
+ problems.push('connection discovery returned malformed or missing results');
+ continue;
+ }
+ if (result.ok && strict && (!Array.isArray(result.connections) || !Array.isArray(result.connectionReferences))) {
+ problems.push('successful discovery must include connections and connectionReferences arrays');
+ }
+ if (typeof call.rawOutput === 'string') {
+ try {
+ const rows = parsePacConnectionList(call.rawOutput);
+ if (result.ok && Array.isArray(result.connections) && rows.length !== result.connections.length) {
+ problems.push('discovery result does not match the recorded PAC rows');
+ }
+ } catch (error) {
+ if (result.ok) problems.push(`unreadable connection listing was treated as success: ${error.message}`);
+ }
+ }
+ if (!result.ok && strict && call.userMessage !== (result.message || result.error)) {
+ problems.push('failed discovery error was not surfaced verbatim');
+ }
+ if (Array.isArray(result.connections)) {
+ let sawUnready = false;
+ for (const row of result.connections) {
+ if (!isObject(row) || !row.connectionId || !row.connectorId) problems.push('discovery contains an unusable connection row');
+ if (row.readyToBind === false) sawUnready = true;
+ if (row.readyToBind === true && sawUnready) problems.push('ready-to-bind connections must be offered first');
+ }
+ }
+ } else if (latest && latest.result?.ok !== true
+ && (isUpload(call.command) || /\b(?:create-connection|auth-switch)\b|\bcreate-connection-reference\.js\b/.test(call.command))) {
+ problems.push('failed discovery must never create a connection or reference, switch auth, or upload');
+ }
+ }
+ if (!latest) return required ? [...problems, 'list-connections.js not invoked'] : problems;
+ if (needsBinding && latest.result?.ok !== true) problems.push('a planned binding cannot be derived from failed discovery');
+ if (strict && latest.result?.ok === false && !/\bneeds_input\b/i.test(fixture.workflowLog || '')) {
+ problems.push('failed discovery must return needs_input rather than claim no connections');
+ }
+ return problems;
+}
+
+function refusalProblems(fixture) {
+ if (fixture.manifest?.expectedOutcome !== 'refused') return ['fixture does not declare an expected refusal'];
+ const stage = fixture.manifest.refusal?.stage;
+ const calls = workflowCalls(fixture);
+ const problems = [];
+ if ((fixture.files || []).length || calls.some((call) => isGeneration(call.command) || isMutation(call.command))) {
+ problems.push('refused workflow generated a page or attempted a mutation');
+ }
+ if (stage === 'custom-api') {
+ // Loaded only while scoring this refusal to keep the shared evidence primitives independent
+ // of the API lifecycle module (which itself consumes those primitives).
+ const { customApiGateProblems } = require('./custom-api-contract.js');
+ return problems.concat(customApiGateProblems(fixture));
+ }
+ const predicate = stage === 'auth' ? isAuth : stage === 'discovery' ? isDiscovery : null;
+ if (!predicate) return [...problems, `unsupported refusal stage: ${stage}`];
+ const gate = calls.filter((call) => predicate(call.command)).at(-1);
+ if (resultObject(gate || {})?.ok !== false) problems.push('refusal has no associated failed gate');
+ return problems.concat(stage === 'auth' ? authGateProblems(fixture, { required: true }) : discoveryProblems(fixture, { required: true }));
+}
+
+module.exports = {
+ currentContract, isObject, isUpload, isAuth, isDiscovery, isMutation, isGeneration,
+ resultObject, workflowCalls, authGateProblems, discoveryProblems, refusalProblems,
+ unassociatedCallProblems,
+};
diff --git a/evals/model-apps/genpage/run-layer-1.js b/evals/model-apps/genpage/run-layer-1.js
index 5544b4971..a1417fb11 100644
--- a/evals/model-apps/genpage/run-layer-1.js
+++ b/evals/model-apps/genpage/run-layer-1.js
@@ -2,9 +2,9 @@
'use strict';
// Layer 1 eval runner — grades workflow artifacts (workflow-log.md,
-// genpage-plan.md, entity-creation-log.md) against the common_workflow_assertions
-// and per-eval Phase/Edit-Phase expectations defined in evals.json. Pure file
-// I/O + regex; no Anthropic API, no Dataverse.
+// genpage-plan.md, genpage-entity-creation-log.md or its legacy alias) against the common_workflow_assertions
+// and per-eval Phase/Edit-Phase expectations defined in evals.json. Offline file
+// I/O, associated result evidence and pure contract helpers; no agent or Dataverse calls.
//
// Usage:
// node run-layer-1.js [--fixtures <dir>] [--eval <id>] [--tier <tier>]
@@ -53,9 +53,10 @@ Fixtures directory layout:
dashboard.tsx (consumed by Layer 2)
workflow-log.md (consumed by Layer 1)
genpage-plan.md (consumed by Layer 1)
- [entity-creation-log.md] (consumed by Layer 1 when entities created)
+ [genpage-entity-creation-log.md] (consumed by Layer 1 when entities created)
-Layer 1 reads workflow-log.md / genpage-plan.md / entity-creation-log.md and
+Layer 1 reads workflow-log.md / genpage-plan.md / genpage-entity-creation-log.md
+(or the legacy entity-creation-log.md alias) and
greps them for evidence of the assertions in evals.json. Workflow assertions
that need AST analysis or schema cross-check are marked SKIP rather than
guessed.
@@ -71,6 +72,34 @@ function isPhaseExpectation(text) {
return /^Phase\s|^Edit Phase\s/.test(text);
}
+function getExpectationCheck(text) {
+ return isPhaseExpectation(text) ? PHASE_EXPECTATIONS.get(text) : undefined;
+}
+
+// Grades one fixture: the common workflow assertions, then its eval's per-eval Phase/Edit Phase
+// expectations, in report order. `kind` says which list a result came from. main() reports exactly
+// these results, and evals/model-apps/tests/eval-coverage-contract.test.js reads the same ones, so
+// the contract can never grade something the runner does not.
+function gradeFixture(fix, ev, evalsData) {
+ if (!ev) {
+ return [{ kind: 'gate', text: `fixture references eval id ${fix.id}`, result: { status: 'fail', reason: `no eval with id ${fix.id} in evals.json` } }];
+ }
+ const results = [];
+ for (const text of evalsData.common_workflow_assertions) {
+ const check = WORKFLOW_ASSERTIONS.get(text);
+ results.push({ kind: 'common', text, result: check
+ ? check({ fixture: fix, eval: ev })
+ : { status: 'skip', reason: 'no check registered for this assertion text' } });
+ }
+ for (const text of ev.expectations.filter(isPhaseExpectation)) {
+ const check = getExpectationCheck(text);
+ results.push({ kind: 'expectation', text, result: check
+ ? check({ fixture: fix, eval: ev })
+ : { status: 'skip', reason: 'no check registered for this expectation' } });
+ }
+ return results;
+}
+
function main() {
const args = parseArgs(process.argv.slice(2));
const fixturesDir = args.fixtures
@@ -113,35 +142,9 @@ function main() {
for (const fix of selected) {
reporter.startFixture(fix.dirName);
- const ev = evalById.get(fix.id);
- if (!ev) {
- reporter.assertion(
- `fixture references eval id ${fix.id}`,
- { status: 'fail', reason: `no eval with id ${fix.id} in evals.json` }
- );
- reporter.endFixture();
- continue;
- }
-
- // common workflow assertions
- for (const assertionText of evalsData.common_workflow_assertions) {
- const check = WORKFLOW_ASSERTIONS.get(assertionText);
- const result = check
- ? check({ fixture: fix, eval: ev })
- : { status: 'skip', reason: 'no check registered for this assertion text' };
- reporter.assertion(assertionText, result);
+ for (const { text, result } of gradeFixture(fix, evalById.get(fix.id), evalsData)) {
+ reporter.assertion(text, result);
}
-
- // per-eval Phase/Edit Phase expectations
- const phaseExp = ev.expectations.filter(isPhaseExpectation);
- for (const expectationText of phaseExp) {
- const check = PHASE_EXPECTATIONS.get(expectationText);
- const result = check
- ? check({ fixture: fix, eval: ev })
- : { status: 'skip', reason: 'no check registered for this expectation' };
- reporter.assertion(expectationText, result);
- }
-
reporter.endFixture();
}
@@ -151,4 +154,4 @@ function main() {
if (require.main === module) main();
-module.exports = { main, parseArgs };
+module.exports = { main, parseArgs, isPhaseExpectation, getExpectationCheck, gradeFixture };
diff --git a/evals/model-apps/genpage/run-layer-2.js b/evals/model-apps/genpage/run-layer-2.js
index 03bbf976f..1813e334f 100644
--- a/evals/model-apps/genpage/run-layer-2.js
+++ b/evals/model-apps/genpage/run-layer-2.js
@@ -3,7 +3,8 @@
// Layer 2 eval runner — grades generated .tsx fixtures against the
// common_code_assertions and per-eval Phase 5 expectations defined in
-// evals.json. Pure file I/O + regex; no Anthropic API, no Dataverse.
+// evals.json. Offline file I/O, static checks and pure production gates/resolver;
+// no agent, TypeScript compiler, React rendering or Dataverse calls.
//
// Usage:
// node run-layer-2.js [--fixtures <dir>] [--eval <id>] [--tier <smoke|full|stress>]
@@ -24,6 +25,7 @@ const fs = require('node:fs');
const { loadFixtures } = require('./lib/fixture-loader.js');
const { parseEvalArgs } = require('../lib/eval-args.js');
const { TapReporter } = require('./lib/reporter.js');
+const { refusalProblems } = require('./lib/workflow-evidence.js');
const {
ASSERTIONS,
PHASE5_EXPECTATIONS,
@@ -66,7 +68,45 @@ function loadEvals() {
}
function isPhase5Expectation(text) {
- return /^Phase 5\b/.test(text);
+ // The letter is part of the phase name, so \b after "5" alone silently excluded 5b's registered check.
+ return /^Phase 5(?:[abc])?\b/.test(text);
+}
+
+function getExpectationCheck(text) {
+ return isPhase5Expectation(text) ? PHASE5_EXPECTATIONS.get(text) : undefined;
+}
+
+// Grades one fixture in report order: an expected refusal or a fixture without pages is a single
+// gate result; otherwise the common code assertions, then the eval's Phase 5 / 5a / 5b / 5c
+// expectations. `kind` says which list a result came from. main() reports exactly these results,
+// and evals/model-apps/tests/eval-coverage-contract.test.js reads the same ones.
+function gradeFixture(fix, ev, evalsData) {
+ if (!ev) {
+ return [{ kind: 'gate', text: `fixture references eval id ${fix.id}`, result: { status: 'fail', reason: `no eval with id ${fix.id} in evals.json` } }];
+ }
+ if (fix.manifest?.expectedOutcome === 'refused') {
+ const problems = refusalProblems(fix);
+ return [{ kind: 'gate', text: 'expected refusal has a failed gate and no generated pages or mutations', result: problems.length
+ ? { status: 'fail', reason: problems[0] }
+ : { status: 'pass', reason: '' } }];
+ }
+ if (fix.files.length === 0) {
+ return [{ kind: 'gate', text: 'fixture has at least one .tsx file', result: { status: 'fail', reason: 'no .tsx files in fixture (excluding RuntimeTypes.ts)' } }];
+ }
+ const results = [];
+ for (const text of evalsData.common_code_assertions) {
+ const check = ASSERTIONS.get(text);
+ results.push({ kind: 'common', text, result: check
+ ? check({ files: fix.files, fixture: fix, eval: ev })
+ : { status: 'skip', reason: 'no check registered for this assertion text' } });
+ }
+ for (const text of ev.expectations.filter(isPhase5Expectation)) {
+ const check = getExpectationCheck(text);
+ results.push({ kind: 'expectation', text, result: check
+ ? check({ files: fix.files, fixture: fix, eval: ev })
+ : { status: 'skip', reason: 'no check registered for this Phase 5 expectation' } });
+ }
+ return results;
}
function main() {
@@ -114,43 +154,9 @@ function main() {
for (const fix of selected) {
reporter.startFixture(fix.dirName);
- const ev = evalById.get(fix.id);
- if (!ev) {
- reporter.assertion(
- `fixture references eval id ${fix.id}`,
- { status: 'fail', reason: `no eval with id ${fix.id} in evals.json` }
- );
- reporter.endFixture();
- continue;
- }
- if (fix.files.length === 0) {
- reporter.assertion(
- 'fixture has at least one .tsx file',
- { status: 'fail', reason: 'no .tsx files in fixture (excluding RuntimeTypes.ts)' }
- );
- reporter.endFixture();
- continue;
- }
-
- // Apply every common_code_assertion
- for (const assertionText of evalsData.common_code_assertions) {
- const check = ASSERTIONS.get(assertionText);
- const result = check
- ? check({ files: fix.files, eval: ev })
- : { status: 'skip', reason: 'no check registered for this assertion text' };
- reporter.assertion(assertionText, result);
+ for (const { text, result } of gradeFixture(fix, evalById.get(fix.id), evalsData)) {
+ reporter.assertion(text, result);
}
-
- // Apply each per-eval Phase 5 expectation
- const phase5 = ev.expectations.filter(isPhase5Expectation);
- for (const expectationText of phase5) {
- const check = PHASE5_EXPECTATIONS.get(expectationText);
- const result = check
- ? check({ files: fix.files, eval: ev })
- : { status: 'skip', reason: 'no check registered for this Phase 5 expectation' };
- reporter.assertion(expectationText, result);
- }
-
reporter.endFixture();
}
@@ -160,4 +166,4 @@ function main() {
if (require.main === module) main();
-module.exports = { main, parseArgs };
+module.exports = { main, parseArgs, isPhase5Expectation, getExpectationCheck, gradeFixture };
diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
index a2554c4a4..bbcf987a7 100644
--- a/evals/model-apps/genpage/tests/assertions-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
@@ -144,6 +144,21 @@ test('validateGenpagePlanSchema: valid canonical plan passes', () => {
assert.deepEqual(validateGenpagePlanSchema(validPlan()), []);
});
+test('Pages-table and per-page filenames agree instead of dispatching to different targets', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md');
+ const evaluate = (plan) => check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });
+ assert.deepEqual(validateGenpagePlanSchema(validPlan()), []);
+ assert.equal(evaluate(validPlan()).status, 'pass');
+ for (const file of ['wrong-page.tsx', 'ACCOUNT-OVERVIEW.tsx', '']) {
+ const plan = validPlan().replace('- **File:** account-overview.tsx', `- **File:** ${file}`);
+ const errors = validateGenpagePlanSchema(plan);
+ assert.ok(errors.some((error) => error.code === 'page-file-mismatch' && error.page === 'Account Overview'), JSON.stringify(errors));
+ assert.equal(evaluate(plan).status, 'fail', file || '(empty File)');
+ }
+ const ambiguous = validPlan().replace('- **File:** account-overview.tsx', '- **File:** account-overview.tsx\n- **File:** wrong-page.tsx');
+ assert.equal(evaluate(ambiguous).status, 'fail', 'two competing File fields are not an agreed dispatch target');
+});
+
test('validateGenpagePlanSchema: missing each required per-page field fails clearly', () => {
const requiredFields = [
'File',
@@ -452,6 +467,196 @@ node check-auth.js → ok: true`;
assert.equal(result.status, 'fail');
});
+const AUTH_GATE = [...WORKFLOW_ASSERTIONS.keys()].find((text) => text.startsWith('Phase 2a: When entities need creating'));
+
+function authFixture(events, overrides = {}) {
+ return fix({
+ contractVersion: 2,
+ manifest: { contractVersion: 2, provenance: 'synthetic' },
+ events,
+ workflowLog: events.map((event) => `${event.command}\nResult: ok: ${event.result?.ok}\n${JSON.stringify(event.result)}\n${event.userMessage || ''}`).join('\n'),
+ genpagePlan: '## Entity Creation Required\n### widget\n',
+ ...overrides,
+ });
+}
+
+function authResult(overrides = {}) {
+ return {
+ ok: true,
+ blocker: null,
+ message: 'Ready.',
+ warnings: [],
+ envUrl: 'https://contoso.crm.dynamics.com',
+ identitiesMatch: true,
+ whoAmI: { ok: true },
+ ...overrides,
+ };
+}
+
+test('failed auth cannot borrow a later ok result', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ const log = `node check-auth.js --require-pac
+Result: {"ok":false,"blocker":"az_timeout","message":"Azure CLI timed out; retry once."}
+node provision-entities.js --env https://contoso.crm.dynamics.com --input @input.json --apply
+Provisioning result: ok:true`;
+ assert.equal(check({
+ fixture: fix({ workflowLog: log, genpagePlan: '## Entity Creation Required\n### widget\n' }),
+ eval: evalStub(),
+ }).status, 'fail');
+
+ const events = [
+ { command: 'node check-auth.js --require-pac', result: authResult() },
+ { command: 'node provision-entities.js --input @input.json --apply', result: { ok: true } },
+ ];
+ assert.equal(check({ fixture: authFixture(events), eval: evalStub() }).status, 'pass');
+
+ const captured = fs.readFileSync(path.join(__dirname, '..', 'fixtures', '15-support-tickets-real', 'workflow-log.md'), 'utf8');
+ const probe = captured.replace('Result: ok=true, identitiesMatch=true', 'Result: ok=false, blocker=az_timeout')
+ + '\nProvisioning result: ok:true\n';
+ assert.equal(check({
+ fixture: fix({ workflowLog: probe, genpagePlan: '## Entity Creation Required\n### ticket\n' }),
+ eval: evalStub(),
+ }).status, 'fail');
+ assert.equal(check({
+ fixture: fix({ workflowLog: captured, genpagePlan: '## Entity Creation Required\n### ticket\n' }),
+ eval: evalStub(),
+ }).status, 'pass');
+});
+
+test('auth gates use the latest applicable result before every mutation', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ const message = 'Azure CLI did not answer within 60 s; retry once or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.';
+ const slow = { command: 'node check-auth.js --require-pac', result: authResult({ ok: false, blocker: 'az_timeout', message, whoAmI: null }), userMessage: message };
+ const upload = { command: 'node scripts\\genpage-upload.js --page-id 22222222-2222-4222-8222-222222222222', result: { ok: true } };
+ const success = { command: 'node check-auth.js --require-pac', result: authResult() };
+ assert.equal(check({ fixture: authFixture([success, slow, upload]), eval: evalStub() }).status, 'fail');
+ assert.equal(check({ fixture: authFixture([slow, success, upload]), eval: evalStub() }).status, 'pass');
+ assert.equal(check({ fixture: authFixture([upload, success]), eval: evalStub() }).status, 'fail');
+ assert.equal(check({ fixture: authFixture([slow, slow, slow]), eval: evalStub() }).status, 'fail');
+ assert.equal(check({ fixture: authFixture([slow, slow], { workflowLog: `${message}\nHalted; no provisioning or upload.` }), eval: evalStub() }).status, 'pass');
+});
+
+test('malformed auth results fail closed rather than authorizing a builder', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ for (const result of [null, [], {}, '{"ok":true,', { ok: 'true' }, authResult({ blocker: 'az_timeout' }), authResult({ whoAmI: { ok: false } }),
+ authResult({ message: null }), authResult({ warnings: {} }), authResult({ envUrl: null })]) {
+ const events = [
+ { command: 'node check-auth.js --require-pac', result },
+ { command: 'node provision-entities.js --input @input.json --apply', result: { ok: true } },
+ ];
+ assert.equal(check({ fixture: authFixture(events), eval: evalStub() }).status, 'fail', JSON.stringify(result));
+ }
+ const valid = [{ command: 'node check-auth.js --require-pac', result: authResult() }];
+ assert.equal(check({ fixture: authFixture(valid), eval: evalStub() }).status, 'pass');
+ valid[0].command = 'node check-auth.js';
+ assert.equal(check({ fixture: authFixture(valid), eval: evalStub() }).status, 'fail', 'current genpage gates require --require-pac');
+});
+
+test('warning-only identity mismatch proceeds only after the warning is surfaced', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ const message = 'Ready, but az and pac use different identities. WhoAmI passed; run az login --username [email protected] if provisioning returns 403.';
+ const gate = { command: 'node check-auth.js --require-pac', result: authResult({ identitiesMatch: false, message }), userMessage: message };
+ const provision = { command: 'node provision-entities.js --input @input.json --apply', result: { ok: true } };
+ assert.equal(check({ fixture: authFixture([gate, provision]), eval: evalStub() }).status, 'pass');
+ assert.equal(check({ fixture: authFixture([{ ...gate, userMessage: '' }, provision]), eval: evalStub() }).status, 'fail');
+});
+
+test('auth failure distinguishes slow, absent and signed-out CLIs and preserves advice', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ const cases = [
+ ['az_timeout', 'Azure CLI did not answer within 60 s; retry once or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.'],
+ ['pac_timeout', 'pac org who did not answer within 60 s. Login is unknown, not missing; retry once.'],
+ ['az_missing', 'Azure CLI is not installed. Install Azure CLI, then run az login.'],
+ ['az_not_logged_in', 'Azure CLI is installed but signed out. Run az login.'],
+ ['pac_not_logged_in', 'PAC is signed out. Run pac auth create --environment https://contoso.crm.dynamics.com.'],
+ ];
+ for (const [blocker, message] of cases) {
+ const failed = { command: 'node check-auth.js --require-pac', result: authResult({ ok: false, blocker, message, whoAmI: null }), userMessage: message };
+ const attempts = /timeout$/.test(blocker) ? [failed, failed] : [failed];
+ const fixture = authFixture(attempts, { workflowLog: `${message}\nHalted; no provisioning or upload.` });
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'pass', blocker);
+ fixture.events = [...attempts, { command: 'node create-table.js widget --solution Default', result: { ok: true } }];
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'fail', `${blocker} must halt`);
+ fixture.events = attempts.map((event) => ({ ...event, userMessage: 'Please log in again.' }));
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'fail', `${blocker} advice must not be rewritten`);
+ }
+});
+
+test('associated auth evidence cannot conceal an unrecorded provisioning command', () => {
+ const message = 'Azure CLI did not answer within 60 s; retry once or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.';
+ const failed = { command: 'node check-auth.js --require-pac', result: authResult({ ok: false, blocker: 'az_timeout', message, whoAmI: null }), userMessage: message };
+ const fixture = authFixture([failed, failed], { workflowLog: `${message}\nHalted; no provisioning or upload.` });
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'pass');
+ fixture.workflowLog += '\nnode provision-entities.js --input @input.json --apply\nResult: ok:true\n';
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'fail');
+});
+
+test('the latest auth gate must authorize the mutation environment, not another profile', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ const gate = { command: 'node check-auth.js --env https://contoso.crm.dynamics.com --require-pac', result: authResult() };
+ const provision = { command: 'node provision-entities.js --env https://contoso.crm.dynamics.com/ --input @input.json --apply', result: { ok: true } };
+ assert.equal(check({ fixture: authFixture([gate, provision]), eval: evalStub() }).status, 'pass');
+ provision.command = provision.command.replace('contoso.crm', 'contoso-other.crm');
+ assert.equal(check({ fixture: authFixture([gate, provision]), eval: evalStub() }).status, 'fail');
+});
+
+test('an absent historical auth result cannot borrow a named operation result in the same prose block', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ const plan = '## Entity Creation Required\n### widget\n';
+ const command = 'node provision-entities.js --input @input.json --apply';
+ for (const log of [
+ `node check-auth.js\nProvisioning result: ok:true\n${command}`,
+ `node check-auth.js\nResult: {"ok":true,\nProvisioning result: ok:true\n${command}`,
+ ]) assert.equal(check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() }).status, 'fail');
+ const log = `node check-auth.js\n - Result: ok:true\n${command}`;
+ assert.equal(check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() }).status, 'pass');
+});
+
+test('timeout blocker advice cannot be reclassified as installation or sign-in failure', () => {
+ const check = WORKFLOW_ASSERTIONS.get(AUTH_GATE);
+ for (const [blocker, badMessage] of [
+ ['az_timeout', 'Azure CLI is missing. Install Azure CLI and run az login.'],
+ ['pac_timeout', 'PAC is signed out. Run pac auth create.'],
+ ]) {
+ const goodMessage = blocker === 'az_timeout' ? 'Azure CLI did not answer in 60 s; retry once or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.'
+ : 'pac org who did not answer in 60 s; login is unknown, not missing. Retry once.';
+ const call = { command: 'node check-auth.js --require-pac', result: authResult({ ok: false, blocker, message: goodMessage, whoAmI: null }), userMessage: goodMessage };
+ const fixture = authFixture([call, call], { workflowLog: 'Halted; no provisioning or upload.' });
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'pass');
+ call.result.message = badMessage;
+ call.userMessage = badMessage;
+ assert.equal(check({ fixture, eval: evalStub() }).status, 'fail');
+ }
+});
+
+test('failed discovery never creates a connection or reference', () => {
+ const text = [...PHASE_EXPECTATIONS.keys()].find((key) => key.startsWith('Phase 1 (Planner): For a connector-backed page'));
+ const check = PHASE_EXPECTATIONS.get(text);
+ const plan = validPlan().replace('No connector bindings.', '| Logical Name | Connector Id |\n|---|---|\n| cnt_docs | /providers/Microsoft.PowerApps/apis/shared_sharepointonline |');
+ const failure = { command: 'node scripts\\list-connections.js https://contoso.crm.dynamics.com', result: { ok: false, message: 'Unrecognized PAC connection header.' }, userMessage: 'Unrecognized PAC connection header.' };
+ const refused = fix({ contractVersion: 2, manifest: { contractVersion: 2 }, events: [failure], genpagePlan: plan, workflowLog: 'node list-connections.js\nneeds_input: Unrecognized PAC connection header.' });
+ assert.equal(check({ fixture: refused, eval: evalStub(18) }).status, 'fail', 'a binding cannot come from failed discovery');
+ for (const command of [
+ 'npx power-apps create-connection --api-id shared_sharepointonline',
+ 'node create-connection-reference.js https://contoso.crm.dynamics.com cnt_docs shared_sharepointonline',
+ 'npx power-apps auth-switch --account maker',
+ 'node genpage-upload.js --connectors connectors.json',
+ ]) {
+ const fixture = { ...refused, events: [failure, { command, result: { ok: true } }], workflowLog: `${refused.workflowLog}\n${command}\nResult: {"ok":true}` };
+ assert.equal(check({ fixture, eval: evalStub(18) }).status, 'fail', command);
+ }
+ const connectorId = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+ const discovered = { ok: true, connections: [{ connectorId, connectionId: 'synthetic-connection', readyToBind: true }], connectionReferences: [{ logicalName: 'cnt_docs', connectorId, connectionId: 'synthetic-connection' }] };
+ const ready = { ...refused, events: [{ ...failure, result: discovered }], workflowLog: 'node list-connections.js\nResult: {"ok":true,"connections":[{}]}' };
+ assert.equal(check({ fixture: ready, eval: evalStub(18) }).status, 'pass');
+
+ const captured = fs.readFileSync(path.join(__dirname, '..', 'fixtures', '18-sharepoint-connectors', 'workflow-log.md'), 'utf8');
+ const probe = captured.replace('2 connections found:', '{"ok":false,"message":"Unrecognized PAC connection header."}')
+ + '\nnpx power-apps create-connection --api-id shared_sharepointonline\nResult: {"ok":true}\n';
+ assert.equal(check({ fixture: fix({ workflowLog: probe, genpagePlan: plan }), eval: evalStub(18) }).status, 'fail');
+});
+
// ---------- prefix discipline plan format ----------
test('prefix discipline plan format: pass on suffix-only names', () => {
@@ -483,7 +688,7 @@ test('prefix discipline plan format: fail when prefix bled into suffix', () => {
// ---------- prefix discipline resolved names ----------
test('prefix resolved names: pass when all names start with publisher prefix', () => {
- const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).');
+ const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — resolved names: For every operation in `genpage-entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).');
const plan = `## Environment\nPublisher Prefix: crb2b\n`;
const elog = `- Create table widget: Resolved Full Name: crb2b_widget\n`;
const result = check({ fixture: fix({ genpagePlan: plan, entityCreationLog: elog }), eval: evalStub() });
@@ -491,7 +696,7 @@ test('prefix resolved names: pass when all names start with publisher prefix', (
});
test('prefix resolved names: fail on prefix mismatch', () => {
- const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).');
+ const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — resolved names: For every operation in `genpage-entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).');
const plan = `## Environment\nPublisher Prefix: crb2b\n`;
const elog = `- Resolved Full Name: cr_widget\n`;
const result = check({ fixture: fix({ genpagePlan: plan, entityCreationLog: elog }), eval: evalStub() });
diff --git a/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js b/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
new file mode 100644
index 000000000..e5c70540b
--- /dev/null
+++ b/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
@@ -0,0 +1,206 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { loadFixtures } = require('../lib/fixture-loader.js');
+const { PHASE_EXPECTATIONS, WORKFLOW_ASSERTIONS } = require('../lib/assertions-layer-1.js');
+const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
+
+const RULE = 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree';
+const bindings = [
+ { name: 'cnt_ApproveOrder', isFunction: false, boundEntityLogicalName: 'salesorder', displayName: 'Approve Order', parameterKinds: { Comment: 'String', Amount: 'Decimal' } },
+ { name: 'cnt_GetOrderSummary', isFunction: true, displayName: 'Summary', parameterKinds: { OrderId: 'Guid' } },
+];
+const source = `
+async function approveOrder(api: ActionApi, recordId: string, amount: number, pending: Pending) {
+ if (typeof api.executeAction !== 'function') return;
+ if (pending.current || !recordId) return;
+ pending.current = true;
+ try {
+ const res = await api.executeAction({
+ name: 'cnt_ApproveOrder',
+ parameters: { Comment: 'Approved', Amount: amount },
+ boundTo: { entityName: 'salesorder', id: recordId },
+ });
+ if (res.indeterminate) { setError('Refresh before retrying.'); return; }
+ if (!res.ok) { setError(res.error?.message ?? 'Action failed.'); return; }
+ setStatus(res.outputs?.NewStatus);
+ } catch { setError('Network failed.'); }
+ finally { pending.current = false; }
+}
+async function readSummary(api: ActionApi, recordId: string) {
+ if (typeof api.executeFunction !== 'function') return;
+ const res = await api.executeFunction({ name: 'cnt_GetOrderSummary', parameters: { OrderId: recordId } });
+ if (!res.ok) { setError(res.error?.message ?? 'Summary failed.'); return; }
+ setTotal(res.outputs?.Total);
+}
+const GeneratedComponent = (props: Props) => {
+ const { dataApi } = props;
+ const pending = { current: false };
+ void approveOrder(dataApi, 'record', 1, pending);
+ void readSummary(dataApi, 'record');
+ return null;
+};
+export default GeneratedComponent;
+`;
+const cleared = 'const GeneratedComponent = () => null;\nexport default GeneratedComponent;\n';
+
+function apiFixture() {
+ const populated = JSON.stringify({ actionBindings: bindings });
+ return {
+ contractVersion: 2,
+ files: [{ name: 'page.tsx', content: cleared }],
+ artifacts: {
+ 'stages/with-api.tsx': source, 'actions.json': JSON.stringify(bindings), 'empty-actions.json': '[]',
+ 'created/config.json': populated, 'preserved/config.json': populated, 'cleared/config.json': '{"actionBindings":[]}',
+ },
+ genpagePlan: `## Custom API Bindings
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| cnt_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |
+| cnt_GetOrderSummary | Function | (Global) | Summary | OrderId: Guid |
+`,
+ workflowLog: 'Custom API lifecycle, latest enabled gate before each generation and upload.',
+ manifest: {
+ customApi: {
+ outputs: { cnt_ApproveOrder: ['NewStatus'], cnt_GetOrderSummary: ['Total'] },
+ stages: [
+ { id: 'create', target: 'page.tsx', source: 'stages/with-api.tsx', actions: 'actions.json', afterConfig: 'created/config.json', upload: 'create' },
+ { id: 'preserve', target: 'page.tsx', source: 'stages/with-api.tsx', beforeConfig: 'created/config.json', afterConfig: 'preserved/config.json', upload: 'preserve' },
+ { id: 'clear', target: 'page.tsx', source: 'page.tsx', actions: 'empty-actions.json', beforeConfig: 'preserved/config.json', afterConfig: 'cleared/config.json', upload: 'clear', change: { clear: true } },
+ ],
+ },
+ },
+ events: [
+ { id: 'gate-create', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'discovery', command: 'node list-custom-apis.js https://contoso.crm.dynamics.com --entities salesorder', result: { ok: true, customApis: structuredClone(bindings).map((binding) => ({ ...binding, bindingType: binding.boundEntityLogicalName ? 'Entity' : 'Global' })) } },
+ { id: 'gate-generate', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'write-create', command: 'Write page.tsx', artifact: 'stages/with-api.tsx' },
+ { id: 'create', command: 'node genpage-upload.js --code-file page.tsx --actions actions.json --add-to-sitemap', result: { ok: true, pageId: '99999999-9999-4999-8999-999999999999' } },
+ { id: 'gate-preserve', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'write-preserve', command: 'Write page.tsx', artifact: 'stages/with-api.tsx' },
+ { id: 'preserve', command: 'node genpage-upload.js --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx', result: { ok: true, pageId: '99999999-9999-4999-8999-999999999999' } },
+ { id: 'gate-clear', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'write-clear', command: 'Write page.tsx', artifact: 'page.tsx' },
+ { id: 'clear', command: 'node genpage-upload.js --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx --actions empty-actions.json', result: { ok: true, pageId: '99999999-9999-4999-8999-999999999999' } },
+ ],
+ };
+}
+
+const event = (fixture, id) => fixture.events.find((call) => call.id === id);
+
+function score(fixture, layer = 1) {
+ const map = layer === 1 ? PHASE_EXPECTATIONS : PHASE5_EXPECTATIONS;
+ const check = map.get(RULE);
+ assert.equal(typeof check, 'function', `Custom API lifecycle scorer must exist in layer ${layer}`);
+ return check({ fixture, files: fixture.files, eval: { id: 24 } });
+}
+
+test('custom API gate and bindings match generated runtime calls', () => {
+ const good = apiFixture();
+ for (const layer of [1, 2]) assert.equal(score(good, layer).status, 'pass');
+ for (const mutate of [
+ (fixture) => { event(fixture, 'gate-create').result = 'disabled'; },
+ (fixture) => { event(fixture, 'gate-preserve').result = 'unreadable'; },
+ (fixture) => { event(fixture, 'discovery').result.ok = false; },
+ (fixture) => { event(fixture, 'discovery').result.customApis[0].parameterKinds.Amount = 'Boolean'; },
+ (fixture) => { fixture.artifacts['actions.json'] = JSON.stringify({ actionBindings: bindings }); },
+ (fixture) => { const rows = JSON.parse(fixture.artifacts['actions.json']); rows[0].name = 'cnt_Invented'; fixture.artifacts['actions.json'] = JSON.stringify(rows); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace('api.executeAction({', 'api.executeFunction({'); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace("Comment: 'Approved'", "Commet: 'Approved'"); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace('Amount: amount', "Amount: 'wrong type'"); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace("entityName: 'salesorder'", "entityName: 'account'"); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace('parameters: { OrderId: recordId }', "parameters: { OrderId: recordId }, boundTo: { entityName: 'salesorder', id: recordId }"); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace('id: recordId', 'id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"'); },
+ (fixture) => { fixture.artifacts['stages/with-api.tsx'] = source.replace('id: recordId', 'id: amount'); },
+ ]) {
+ const bad = apiFixture();
+ mutate(bad);
+ for (const layer of [1, 2]) assert.equal(score(bad, layer).status, 'fail');
+ }
+});
+
+test('Custom API response handling is scoped, sanitized and never auto-retries indeterminate actions', () => {
+ assert.equal(score(apiFixture()).status, 'pass');
+ for (const mutate of [
+ (text) => text.replace("if (typeof api.executeAction !== 'function') return;", ''),
+ (text) => text.replace('pending.current = true;', ''),
+ (text) => text.replace('if (pending.current || !recordId) return;', ''),
+ (text) => text.replace('if (!res.ok)', 'if (false)'),
+ (text) => text.replace('res.outputs', 'res.value'),
+ (text) => text.replace('res.error?.message', 'res.error?.stack'),
+ (text) => text.replace('res.outputs?.NewStatus', 'res.outputs?.Undeclared'),
+ (text) => text.replace("setError('Refresh before retrying.'); return;", 'return approveOrder(api, recordId, amount, pending);'),
+ ]) {
+ const bad = apiFixture();
+ bad.artifacts['stages/with-api.tsx'] = mutate(source) + '\n// res.ok; res.outputs; typeof api.executeAction; pending.current = true;\n';
+ assert.equal(score(bad).status, 'fail');
+ }
+});
+
+test('Custom API calls and their presence checks must use the page dataApi prop', () => {
+ assert.equal(score(apiFixture()).status, 'pass');
+ const other = 'const other = { executeAction: async () => ({ ok: true }), executeFunction: async () => ({ ok: true }) };\n';
+ for (const [label, mutate, reason] of [
+ ['call on an unrelated object', (text) => other + text.replace('await api.executeAction({', 'await other.executeAction({'), /called on other, which is not the page's dataApi prop/],
+ ['call and presence check both on an unrelated object', (text) => other + text.replace('await api.executeAction({', 'await other.executeAction({').replace('typeof api.executeAction', 'typeof other.executeAction'), /called on other, which is not the page's dataApi prop/],
+ ['presence check on an unrelated object', (text) => other + text.replace('typeof api.executeAction', 'typeof other.executeAction'), /not presence-checked on the same receiver/],
+ ['helper filled with an unrelated object', (text) => other + text.replace('approveOrder(dataApi,', 'approveOrder(other,'), /called on api, which is not the page's dataApi prop/],
+ ['helper never called with the prop', (text) => text.replace("void approveOrder(dataApi, 'record', 1, pending);", ''), /called on api, which is not the page's dataApi prop/],
+ ]) {
+ const bad = apiFixture();
+ bad.artifacts['stages/with-api.tsx'] = mutate(source);
+ const result = score(bad);
+ assert.equal(result.status, 'fail', label);
+ assert.match(result.reason, reason, label);
+ }
+});
+
+test('Custom API bindings preserve omission and only an explicit empty array clears', () => {
+ assert.equal(score(apiFixture()).status, 'pass');
+ for (const mutate of [
+ (fixture) => { fixture.artifacts['preserved/config.json'] = '{"actionBindings":[]}'; },
+ (fixture) => { event(fixture, 'preserve').command += ' --actions empty-actions.json'; },
+ (fixture) => { event(fixture, 'clear').command = event(fixture, 'clear').command.replace(' --actions empty-actions.json', ''); },
+ (fixture) => { fixture.artifacts['empty-actions.json'] = '{"actionBindings":[]}'; },
+ (fixture) => { fixture.artifacts['cleared/config.json'] = JSON.stringify({ actionBindings: bindings }); },
+ (fixture) => { fixture.files[0].content = source; },
+ ]) {
+ const bad = apiFixture();
+ mutate(bad);
+ assert.equal(score(bad).status, 'fail');
+ }
+});
+
+test('disabled or unreadable Custom API gates refuse before generation, not as a no-bindings fallback', () => {
+ for (const result of ['disabled', 'unknown', null]) {
+ const stopped = apiFixture();
+ stopped.events = [{ ...stopped.events[0], result }];
+ stopped.files = [];
+ stopped.manifest.expectedOutcome = 'refused';
+ stopped.manifest.refusal = { stage: 'custom-api' };
+ stopped.workflowLog = 'Halted before generation: turn the feature back on or re-plan; the gate is disabled or unreadable.';
+ assert.equal(score(stopped).status, 'pass', String(result));
+ stopped.events.push({ command: 'Write page.tsx', artifact: 'stages/with-api.tsx' });
+ assert.equal(score(stopped).status, 'fail');
+ }
+});
+
+test('Custom API generation re-probes after discovery rather than borrowing the planning gate', () => {
+ const good = apiFixture();
+ assert.equal(score(good).status, 'pass');
+ good.events = good.events.filter((call) => call.id !== 'gate-generate');
+ assert.equal(score(good).status, 'fail');
+});
+
+test('a populated plan cannot continue the audit disabled-gate probe', () => {
+ const captured = loadFixtures(path.join(__dirname, '..', 'fixtures')).find((fixture) => fixture.id === 17);
+ const plan = captured.genpagePlan.replace('No custom API bindings.', apiFixture().genpagePlan.split('## Custom API Bindings\n')[1].trim());
+ const text = [...WORKFLOW_ASSERTIONS.keys()].find((key) => key.startsWith('Phase 4.6: A populated Custom API plan'));
+ const check = WORKFLOW_ASSERTIONS.get(text);
+ const disabled = { ...captured, genpagePlan: plan, workflowLog: 'node feature-flags.js custom-api -> disabled\n' + captured.workflowLog };
+ assert.equal(check({ fixture: disabled }).status, 'fail');
+ const enabled = { ...disabled, workflowLog: 'node feature-flags.js custom-api -> enabled\n' + captured.workflowLog };
+ assert.equal(check({ fixture: enabled }).status, 'pass');
+});
diff --git a/evals/model-apps/genpage/tests/fixture-loader.test.js b/evals/model-apps/genpage/tests/fixture-loader.test.js
new file mode 100644
index 000000000..fca735651
--- /dev/null
+++ b/evals/model-apps/genpage/tests/fixture-loader.test.js
@@ -0,0 +1,98 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { loadFixtures } = require('../lib/fixture-loader.js');
+
+function temporaryFixture(t, files) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-evidence-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const dir = path.join(root, '20-synthetic');
+ fs.mkdirSync(dir);
+ for (const [name, content] of Object.entries(files)) {
+ // Keys may use either separator; split on both so Linux and macOS build the same tree
+ // as Windows instead of one file named `create\name.txt`.
+ const full = path.join(dir, ...name.split(/[\\/]/));
+ fs.mkdirSync(path.dirname(full), { recursive: true });
+ fs.writeFileSync(full, content, 'utf8');
+ }
+ return root;
+}
+
+test('fixture loader reads current synthetic contracts, associated results and exact artifact text', (t) => {
+ const text = 'Revenue $100 $(Get-Date)\nSecond line\n';
+ const root = temporaryFixture(t, {
+ 'fixture.json': JSON.stringify({ contractVersion: 2, provenance: 'synthetic', contracts: ['skills/genpage/SKILL.md Phase 6'], toolResults: 'tool-results.json', artifacts: ['create/name.txt', 'create/config.json'] }),
+ 'tool-results.json': JSON.stringify([{ id: 'create', command: 'node genpage-upload.js --name-file create/name.txt', result: { ok: true } }]),
+ 'create\\name.txt': text,
+ 'create\\config.json': '{"name":"Revenue $100 $(Get-Date)"}',
+ });
+ const fixture = loadFixtures(root)[0];
+ assert.equal(fixture.contractVersion, 2);
+ assert.equal(fixture.manifest.provenance, 'synthetic');
+ assert.equal(fixture.events[0].id, 'create');
+ assert.equal(fixture.artifacts['create/name.txt'], text);
+});
+
+test('fixture loader rejects malformed evidence, unknown contract versions and escaping paths', (t) => {
+ for (const manifest of [
+ { contractVersion: 99, provenance: 'synthetic' },
+ { contractVersion: 2, provenance: 'captured', toolResults: 'tool-results.json' },
+ { contractVersion: 2, provenance: 'synthetic', toolResults: '..\\outside.json' },
+ { contractVersion: 2, provenance: 'synthetic', artifacts: ['C:\\outside.txt'] },
+ ]) {
+ const root = temporaryFixture(t, { 'fixture.json': JSON.stringify(manifest) });
+ assert.throws(() => loadFixtures(root), /contract|synthetic|path|outside|artifact/i);
+ }
+ const root = temporaryFixture(t, {
+ 'fixture.json': JSON.stringify({ contractVersion: 2, provenance: 'synthetic', toolResults: 'tool-results.json' }),
+ 'tool-results.json': '[{"command":',
+ });
+ assert.throws(() => loadFixtures(root), /tool-results\.json|JSON/i);
+});
+
+test('all committed historical fixtures have an explicit replay contract without changing captures', () => {
+ const root = path.join(__dirname, '..', 'fixtures');
+ const catalog = JSON.parse(fs.readFileSync(path.join(root, 'contracts.json'), 'utf8'));
+ const fixtures = loadFixtures(root);
+ for (const fixture of fixtures) {
+ assert.ok(Object.hasOwn(catalog, fixture.dirName) || fs.existsSync(path.join(fixture.dir, 'fixture.json')), `${fixture.dirName}: missing explicit contract label`);
+ assert.ok([1, 2].includes(fixture.contractVersion), fixture.dirName);
+ assert.ok(fixture.manifest.provenance, fixture.dirName);
+ if (fixture.contractVersion === 1) assert.equal(fixture.manifest.provenance, 'historical');
+ else {
+ assert.equal(fixture.manifest.provenance, 'synthetic');
+ assert.ok(fixture.manifest.description && fixture.manifest.contracts.length, fixture.dirName);
+ }
+ }
+});
+
+test('current entity log name is loaded with an intentional legacy fallback', (t) => {
+ const root = temporaryFixture(t, {
+ 'genpage-entity-creation-log.md': 'Current log\n',
+ 'entity-creation-log.md': 'Legacy log\n',
+ });
+ assert.equal(loadFixtures(root)[0].entityCreationLog, 'Current log\n');
+ fs.unlinkSync(path.join(root, '20-synthetic', 'genpage-entity-creation-log.md'));
+ assert.equal(loadFixtures(root)[0].entityCreationLog, 'Legacy log\n');
+});
+
+test('current entity log loads without a legacy file and a missing log stays absent', (t) => {
+ const root = temporaryFixture(t, { 'genpage-entity-creation-log.md': 'Current-only log\n' });
+ assert.equal(loadFixtures(root)[0].entityCreationLog, 'Current-only log\n');
+ fs.unlinkSync(path.join(root, '20-synthetic', 'genpage-entity-creation-log.md'));
+ assert.equal(loadFixtures(root)[0].entityCreationLog, null);
+});
+
+test('an empty current entity log must not borrow a historical transaction log', (t) => {
+ const root = temporaryFixture(t, {
+ 'genpage-entity-creation-log.md': '',
+ 'entity-creation-log.md': 'Transactions from a historical run\n',
+ });
+ assert.equal(loadFixtures(root)[0].entityCreationLog, '');
+ fs.writeFileSync(path.join(root, '20-synthetic', 'genpage-entity-creation-log.md'), 'Fresh transactions\n');
+ assert.equal(loadFixtures(root)[0].entityCreationLog, 'Fresh transactions\n');
+});
diff --git a/evals/model-apps/genpage/tests/navigation-contract.test.js b/evals/model-apps/genpage/tests/navigation-contract.test.js
new file mode 100644
index 000000000..2b3279379
--- /dev/null
+++ b/evals/model-apps/genpage/tests/navigation-contract.test.js
@@ -0,0 +1,156 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { ASSERTIONS } = require('../lib/assertions-layer-2.js');
+const { PHASE_EXPECTATIONS } = require('../lib/assertions-layer-1.js');
+const { loadFixtures } = require('../lib/fixture-loader.js');
+
+const NAV = 'For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs';
+const FIXUP = 'Phase 6.5: Every effective navigation target resolves against the deployed page map; exact substitutions preserve non-navigation bytes and only affected pages reupload';
+const IDS = {
+ overview: '22222222-2222-4222-8222-222222222222',
+ pet: '33333333-3333-4333-8333-333333333333',
+ 'pet-gallery': '44444444-4444-4444-8444-444444444444',
+};
+const ev = { id: 22, expectations: [] };
+
+function navigationFixture() {
+ const before = {
+ overview: [
+ 'const label = "PAGEREF_pet";',
+ '// Xrm.Navigation.navigateTo({pageType:"generative",pageId:"PAGEREF_comment"});',
+ 'xrm?.Navigation?.navigateTo?.({pageType:"generative",pageId:"PAGEREF_unknown",pageId:"PAGEREF_pet-gallery",data:{pageId:"PAGEREF_data"}});',
+ 'xrm?.Navigation?.navigateTo({"page\\u0054ype":"generative","page\\u{49}d":"PAGEREF_pet"});',
+ ].join('\n'),
+ pet: 'xrm?.Navigation?.navigateTo?.({...base,pageType:"generative",/* pageId comment */pageId:"PAGEREF_pet-gallery"});',
+ 'pet-gallery': 'const label = "PAGEREF_pet";',
+ };
+ const after = {
+ overview: before.overview
+ .replace('pageId:"PAGEREF_pet-gallery",data', `pageId:"${IDS['pet-gallery']}",data`)
+ .replace('"page\\u{49}d":"PAGEREF_pet"', `"page\\u{49}d":"${IDS.pet}"`),
+ pet: before.pet.replace('pageId:"PAGEREF_pet-gallery"', `pageId:"${IDS['pet-gallery']}"`),
+ 'pet-gallery': before['pet-gallery'],
+ };
+ const events = Object.keys(IDS).map((key) => ({
+ id: `${key}-create`,
+ command: `node scripts\\genpage-upload.js --code-file before/${key}.tsx --add-to-sitemap`,
+ result: { ok: true, pageId: IDS[key] },
+ }));
+ for (const key of ['overview', 'pet']) events.push({
+ id: `${key}-fixup`,
+ command: `node scripts\\genpage-upload.js --page-id ${IDS[key]} --code-file ${key}.tsx --prompt-file fixup.txt`,
+ result: { ok: true, pageId: IDS[key], updated: true },
+ });
+ return {
+ contractVersion: 2,
+ files: Object.entries(after).map(([key, content]) => ({ name: `${key}.tsx`, content })),
+ artifacts: { ...Object.fromEntries(Object.entries(before).map(([key, text]) => [`before/${key}.tsx`, text])), 'fixup.txt': 'Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)' },
+ events,
+ manifest: {
+ contractVersion: 2, provenance: 'synthetic',
+ navigation: {
+ pageMap: { ...IDS },
+ sources: Object.keys(IDS).map((key) => ({ key, file: `${key}.tsx`, before: `before/${key}.tsx` })),
+ expectedTargets: { overview: ['pet', 'pet-gallery'], pet: ['pet-gallery'], 'pet-gallery': [] },
+ },
+ },
+ };
+}
+
+const score = (fixture) => ASSERTIONS.get(NAV)({ fixture, files: fixture.files, eval: ev });
+
+test('every effective navigation target resolves and only affected pages reupload', () => {
+ const good = navigationFixture();
+ assert.equal(score(good).status, 'pass');
+ const bad = structuredClone(good);
+ bad.files[0].content = bad.files[0].content.replace(IDS.pet, 'not-a-page-id');
+ assert.equal(score(bad).status, 'fail', 'optional-call literals must be GUIDs from the map');
+ const unknown = structuredClone(good);
+ unknown.artifacts['before/overview.tsx'] = unknown.artifacts['before/overview.tsx'].replace('"page\\u{49}d":"PAGEREF_pet"', '"page\\u{49}d":"PAGEREF_absent-sibling"');
+ assert.equal(score(unknown).status, 'fail', 'a valid sibling elsewhere cannot authorize an unknown target');
+ const wrongMap = structuredClone(good);
+ wrongMap.manifest.navigation.pageMap.pet = 'not-a-guid';
+ assert.equal(score(wrongMap).status, 'fail');
+});
+
+test('navigation fix-up rejects collateral edits, missing replacements and redundant uploads', () => {
+ const check = PHASE_EXPECTATIONS.get(FIXUP);
+ assert.equal(typeof check, 'function', 'navigation lifecycle scorer must be registered');
+ const good = navigationFixture();
+ assert.equal(check({ fixture: good, eval: ev }).status, 'pass');
+ for (const mutate of [
+ (fixture) => { fixture.files[0].content = fixture.files[0].content.replace('const label', 'let label'); },
+ (fixture) => { fixture.files[0].content = fixture.files[0].content.replace(IDS.pet, 'PAGEREF_pet'); },
+ (fixture) => { fixture.events.pop(); },
+ (fixture) => { fixture.events.push({ id: 'redundant', command: `node genpage-upload.js --page-id ${IDS['pet-gallery']} --code-file pet-gallery.tsx --prompt-file fixup.txt`, result: { ok: true, pageId: IDS['pet-gallery'] } }); },
+ (fixture) => { fixture.events.at(-1).command += ' --add-to-sitemap'; },
+ (fixture) => { fixture.events.at(-1).result.pageId = IDS.overview; },
+ (fixture) => { fixture.manifest.navigation.expectedTargets.overview = ['pet']; },
+ (fixture) => { fixture.artifacts['fixup.txt'] = 'Build the full original page again.'; },
+ (fixture) => { fixture.events[0].command = fixture.events[0].command.replace('before/overview.tsx', 'overview.tsx'); },
+ (fixture) => { const update = fixture.events.pop(); fixture.events.unshift(update); },
+ ]) {
+ const bad = structuredClone(good);
+ mutate(bad);
+ assert.equal(check({ fixture: bad, eval: ev }).status, 'fail');
+ }
+});
+
+test('navigation phases reject dynamic overrides and invented literal identities', () => {
+ const make = (code, phase = 'authored') => ({
+ contractVersion: 2,
+ manifest: { navigationPhase: phase, pageMap: IDS },
+ files: [{ name: 'overview.tsx', content: code }, { name: 'pet.tsx', content: '' }, { name: 'pet-gallery.tsx', content: '' }],
+ });
+ const call = (body) => `xrm?.Navigation?.navigateTo?.({pageType:"generative",${body}});`;
+ assert.equal(score(make(call('pageId:"PAGEREF_pet"'))).status, 'pass');
+ assert.equal(score(make(call(`pageId:"${IDS.pet}"`), 'resolved')).status, 'pass');
+ assert.equal(score(make(call(`pageId:"${IDS.pet}"`))).status, 'fail', 'GUIDs belong to the resolved phase only');
+ assert.equal(score(make(call('pageId:"PAGEREF_pet"'), 'resolved')).status, 'fail');
+ for (const override of ['...base', 'get pageId(){return "runtime";}', 'pageId', '["pageId"]: value', 'pageType(){return "entityrecord";}']) {
+ assert.equal(score(make(call(`pageId:"PAGEREF_pet",${override}`))).status, 'fail', override);
+ }
+ assert.equal(score(make(call('pageId:"PAGEREF_unknown",pageId:"PAGEREF_pet"'))).status, 'pass', 'last literal wins');
+ assert.equal(score(make(call('...base,pageType:"generative",pageId:"PAGEREF_pet"'))).status, 'pass', 'literal after spread wins');
+});
+
+test('navigation ignores inert text but sees executable calls after Unicode comment terminators', () => {
+ for (const terminator of ['\r', '\n', '\r\n', '\u2028', '\u2029']) {
+ const content = `// inert navigateTo({pageType:"generative",pageId:"PAGEREF_wrong"})${terminator}`
+ + 'xrm?.Navigation?.navigateTo?.({"page\\x54ype":"generative","page\\u0049d":"PAGEREF_pet"});';
+ const fixture = {
+ manifest: { navigationPhase: 'authored' },
+ files: [{ name: 'overview.tsx', content }, { name: 'pet.tsx', content: 'const help = "PAGEREF_absent";' }],
+ };
+ assert.equal(score(fixture).status, 'pass', JSON.stringify(terminator));
+ fixture.files[0].content = content.replace('"PAGEREF_pet"', '"PAGEREF_missing"');
+ assert.equal(score(fixture).status, 'fail', JSON.stringify(terminator));
+ }
+});
+
+test('historical navigation still rejects the audit unknown-sibling and optional-call probes', () => {
+ const fixtures = loadFixtures(path.join(__dirname, '..', 'fixtures'));
+ const authored = fixtures.find((fixture) => fixture.dirName === '11-recruitment-multi-page');
+ const resolved = fixtures.find((fixture) => fixture.dirName === '11-recruitment-pages-real');
+ assert.equal(score(authored).status, 'pass');
+ assert.equal(score(resolved).status, 'pass');
+ const badAuthored = structuredClone(authored);
+ badAuthored.files[0].content = badAuthored.files[0].content.replace('PAGEREF_interview-schedule', 'PAGEREF_absent-sibling');
+ assert.equal(score(badAuthored).status, 'fail');
+ const badResolved = structuredClone(resolved);
+ for (const file of badResolved.files) {
+ file.content = file.content.replace(/pageId:\s*"[^"]+"/g, 'pageId: "not-a-page-id"');
+ }
+ assert.equal(score(badResolved).status, 'fail');
+});
+
+test('a navigation-shaped record call cannot hide an executable PAGEREF sibling target', () => {
+ const good = navigationFixture();
+ assert.equal(score(good).status, 'pass');
+ good.artifacts['before/overview.tsx'] = good.artifacts['before/overview.tsx'].replace('navigateTo?.({pageType:"generative"', 'navigateTo?.({pageType:"custom"');
+ good.files[0].content = good.files[0].content.replace('navigateTo?.({pageType:"generative"', 'navigateTo?.({pageType:"custom"');
+ assert.equal(score(good).status, 'fail', 'current contract cannot silently treat a legacy custom-page target as compliant');
+});
diff --git a/evals/model-apps/genpage/tests/refusal-replay.test.js b/evals/model-apps/genpage/tests/refusal-replay.test.js
new file mode 100644
index 000000000..2a3abb9b5
--- /dev/null
+++ b/evals/model-apps/genpage/tests/refusal-replay.test.js
@@ -0,0 +1,62 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { loadFixtures } = require('../lib/fixture-loader.js');
+const { refusalProblems, discoveryProblems } = require('../lib/workflow-evidence.js');
+
+const root = path.join(__dirname, '..');
+const corpus = loadFixtures(path.join(root, 'fixtures'));
+
+test('declared auth and discovery refusals replay green without fabricated pages', () => {
+ for (const id of [10, 21]) {
+ const fixture = corpus.find((entry) => entry.id === id);
+ assert.ok(fixture);
+ assert.deepEqual(refusalProblems(fixture), [], fixture.dirName);
+ for (const layer of [1, 2]) {
+ const replay = spawnSync(process.execPath, [path.join(root, `run-layer-${layer}.js`), '--eval', String(id)], { encoding: 'utf8' });
+ assert.equal(replay.status, 0, replay.stdout + replay.stderr);
+ }
+ }
+});
+
+test('an expected refusal cannot hide a successful gate or generated output', (t) => {
+ const original = corpus.find((entry) => entry.id === 21);
+ for (const changed of [
+ { ...original, events: [{ ...original.events[0], result: { ok: true, connections: [], connectionReferences: [] } }] },
+ { ...original, files: [{ name: 'page.tsx', content: 'export default GeneratedComponent;' }] },
+ { ...original, events: [...original.events, { command: 'node genpage-upload.js --prompt-file prompt.txt', result: { ok: true } }] },
+ ]) assert.ok(refusalProblems(changed).length);
+
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-refusal-'));
+ t.after(() => fs.rmSync(temp, { recursive: true, force: true }));
+ const dir = path.join(temp, '21-false-refusal');
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, 'fixture.json'), JSON.stringify(original.manifest));
+ fs.writeFileSync(path.join(dir, 'tool-results.json'), JSON.stringify([{ ...original.events[0], result: { ok: true, connections: [], connectionReferences: [] } }]));
+ fs.writeFileSync(path.join(dir, 'workflow-log.md'), original.workflowLog);
+ const replay = spawnSync(process.execPath, [path.join(root, 'run-layer-2.js'), '--fixtures', temp], { encoding: 'utf8' });
+ assert.equal(replay.status, 1, replay.stdout);
+});
+
+test('discovery distinguishes unreadable output from a genuine empty success and orders ready bindings first', () => {
+ const make = (rawOutput, result) => ({
+ contractVersion: 2,
+ workflowLog: 'needs_input: failed discovery; stopped.',
+ events: [{ command: 'node list-connections.js https://contoso.crm.dynamics.com', rawOutput, result, userMessage: result.error }],
+ });
+ const empty = { ok: true, connections: [], connectionReferences: [] };
+ assert.deepEqual(discoveryProblems(make('No connections found.\n', empty)), []);
+ for (const raw of ['Warning: failed to retrieve connector metadata.\n', '----- -----\n', 'Unsupported header\n']) {
+ assert.ok(discoveryProblems(make(raw, empty)).length, raw);
+ }
+ const connectorId = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+ const unready = { connectionId: 'synthetic-unbound', connectorId, readyToBind: false };
+ const ready = { connectionId: 'synthetic-bound', connectorId, readyToBind: true };
+ assert.deepEqual(discoveryProblems(make(undefined, { ...empty, connections: [ready, unready] })), []);
+ assert.ok(discoveryProblems(make(undefined, { ...empty, connections: [unready, ready] })).length);
+});
diff --git a/evals/model-apps/genpage/tests/run-layer-2.test.js b/evals/model-apps/genpage/tests/run-layer-2.test.js
index 9da58f348..7405dd36b 100644
--- a/evals/model-apps/genpage/tests/run-layer-2.test.js
+++ b/evals/model-apps/genpage/tests/run-layer-2.test.js
@@ -20,8 +20,8 @@ function writeFixture(rootDir, fixtureName, files) {
}
}
-function runRunner(args) {
- const result = spawnSync(process.execPath, [runner, ...args], { encoding: 'utf8' });
+function runRunner(args, nodeArgs = []) {
+ const result = spawnSync(process.execPath, [...nodeArgs, runner, ...args], { encoding: 'utf8' });
return { code: result.status, stdout: result.stdout, stderr: result.stderr };
}
@@ -217,3 +217,67 @@ export default GeneratedComponent;`,
fs.rmSync(root, { recursive: true, force: true });
}
});
+
+test('runner: the registered Phase-5b column checker executes and can fail the replay', (t) => {
+ const root = mkTempFixturesDir();
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ writeFixture(root, '1-phase-5b', {
+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';
+const useStyles = makeStyles({ root: {} });
+const data = [{ name: 'First' }, { name: 'Second' }];
+const GeneratedComponent = (props) => {
+ const { pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ return <div className={styles.root}>{data.length}</div>;
+};
+export default GeneratedComponent;`,
+ });
+ const args = ['--fixtures', root, '--eval', '1'];
+ const green = runRunner(args);
+ assert.equal(green.code, 0, green.stdout + green.stderr);
+ assert.match(green.stdout, /Phase 5b: Generated \.tsx uses only column names verified from RuntimeTypes\.ts/);
+ assert.match(green.stdout, /# SKIP column-name verification requires RuntimeTypes\.ts fixture/);
+
+ // The column oracle is intentionally still a SKIP. Inject a failing result at its real
+ // registry entry to prove routing invokes that callback and propagates failure, not just text.
+ const preload = path.join(root, 'phase-5b-probe.cjs');
+ const library = path.join(__dirname, '..', 'lib', 'assertions-layer-2.js');
+ fs.writeFileSync(preload, `
+const { PHASE5_EXPECTATIONS } = require(${JSON.stringify(library)});
+const text = [...PHASE5_EXPECTATIONS.keys()].find((key) => key.startsWith('Phase 5b: Generated .tsx uses only column names'));
+const original = PHASE5_EXPECTATIONS.get(text);
+PHASE5_EXPECTATIONS.set(text, (args) => ({ status: 'fail', reason: 'Phase-5b callback executed: ' + original(args).reason }));
+`);
+ const red = runRunner(args, ['--require', preload]);
+ assert.equal(red.code, 1, red.stdout + red.stderr);
+ assert.match(red.stdout, /not ok \d+ - Phase 5b: Generated \.tsx uses only column names/);
+ assert.match(red.stdout, /Phase-5b callback executed: column-name verification requires RuntimeTypes\.ts fixture/);
+});
+
+test('runner routing and lookup functions expose every registered phase check', () => {
+ const workflow = require('../run-layer-1.js');
+ const code = require('../run-layer-2.js');
+ const { PHASE_EXPECTATIONS } = require('../lib/assertions-layer-1.js');
+ const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
+ assert.equal(typeof workflow.isPhaseExpectation, 'function');
+ assert.equal(typeof workflow.getExpectationCheck, 'function');
+ assert.equal(typeof code.isPhase5Expectation, 'function');
+ assert.equal(typeof code.getExpectationCheck, 'function');
+ for (const [text, check] of PHASE_EXPECTATIONS) {
+ assert.equal(workflow.isPhaseExpectation(text), true, text);
+ assert.equal(workflow.getExpectationCheck(text), check, text);
+ }
+ for (const [text, check] of PHASE5_EXPECTATIONS) {
+ assert.equal(code.isPhase5Expectation(text), true, text);
+ assert.equal(code.getExpectationCheck(text), check, text);
+ }
+ for (const text of ['Phase 5a: unknown', 'Phase 5b: unknown', 'Phase 5c: unknown', 'Phase 5: unknown']) {
+ assert.equal(code.isPhase5Expectation(text), true, text);
+ assert.equal(code.getExpectationCheck(text), undefined, text);
+ }
+ assert.equal(code.isPhase5Expectation('Phase 50: wrong phase'), false);
+ assert.equal(code.isPhase5Expectation('Edit Phase 5: not routed by this layer'), false);
+ assert.equal(workflow.getExpectationCheck('Phase 1: unregistered'), undefined);
+ assert.equal(code.getExpectationCheck('Phase 1: unregistered'), undefined);
+});
diff --git a/evals/model-apps/genpage/tests/solution-package.test.js b/evals/model-apps/genpage/tests/solution-package.test.js
new file mode 100644
index 000000000..c168cf812
--- /dev/null
+++ b/evals/model-apps/genpage/tests/solution-package.test.js
@@ -0,0 +1,158 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { PHASE_EXPECTATIONS, WORKFLOW_ASSERTIONS } = require('../lib/assertions-layer-1.js');
+
+const RULE = 'Phase 6.7: Packaging uses every deployed page id, the approved solution and discovered component types; invalid identities refuse before writes and results agree with read-back';
+const APP = '11111111-1111-4111-8111-111111111111';
+const SOLUTION = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const REF = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const PAGES = [
+ { file: 'list.tsx', pageId: '22222222-2222-4222-8222-222222222222' },
+ { file: 'schedule.tsx', pageId: '33333333-3333-4333-8333-333333333333' },
+ { file: 'metrics.tsx', pageId: '44444444-4444-4444-8444-444444444444' },
+];
+
+function packageFixture() {
+ const added = [{ type: 'appmodule', id: APP }, ...PAGES.map((page) => ({ type: 'uxagentproject', id: page.pageId })), { type: 'connectionreference', logicalName: 'cnt_docs', id: REF }];
+ const requests = [
+ { method: 'GET', path: "EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode", response: { status: 200, data: { ObjectTypeCode: 10401 } } },
+ { method: 'GET', path: "EntityDefinitions(LogicalName='connectionreference')?$select=ObjectTypeCode", response: { status: 200, data: { ObjectTypeCode: 10402 } } },
+ { method: 'GET', path: "connectionreferences?$filter=connectionreferencelogicalname eq 'cnt_docs'&$select=connectionreferenceid&$top=1", response: { status: 200, data: { value: [{ connectionreferenceid: REF }] } } },
+ ...added.map((entry) => ({
+ method: 'POST', path: 'AddSolutionComponent',
+ body: { ComponentId: entry.id, ComponentType: entry.type === 'appmodule' ? 80 : entry.type === 'uxagentproject' ? 10401 : 10402, SolutionUniqueName: 'ContosoPages', AddRequiredComponents: entry.type !== 'connectionreference' },
+ response: { status: 204, data: {} },
+ })),
+ ];
+ return {
+ contractVersion: 2,
+ genpagePlan: '## Solution Packaging\n- Package into solution: true\n- Solution: ContosoPages\n',
+ workflowLog: 'Phase 6.7: package successful; checked read-back.',
+ artifacts: { 'configs/list.json': '{"connectorBindings":[{"logicalName":"cnt_docs"}]}' },
+ manifest: { packaging: {
+ solution: 'ContosoPages', solutionId: SOLUTION, appId: APP, pages: structuredClone(PAGES), configs: ['configs/list.json'], connectionReferences: ['cnt_docs'],
+ attempts: [{ event: 'package', outcome: 'success', readback: 'readback' }],
+ } },
+ events: [
+ ...PAGES.map((page, index) => ({ id: `deploy-${index}`, command: `node genpage-upload.js --app-id ${APP} --code-file ${page.file} --add-to-sitemap`, result: { ok: true, appId: APP, pageId: page.pageId } })),
+ { id: 'solution', command: 'node provision-solution.js https://contoso.crm.dynamics.com ContosoPages Contoso', result: { ok: true, uniqueName: 'ContosoPages', solutionId: SOLUTION } },
+ { id: 'package', command: `node add-page-to-solution.js https://contoso.crm.dynamics.com ContosoPages ${APP} --page-ids ${PAGES.map((page) => page.pageId).join(',')} --connection-refs cnt_docs`, requests, result: { ok: true, added } },
+ { id: 'readback', command: `node dataverse-request.js https://contoso.crm.dynamics.com GET "solutioncomponents?$filter=_solutionid_value eq ${SOLUTION}&$select=objectid,componenttype"`, result: { ok: true, data: { value: requests.filter((request) => request.method === 'POST').map((request) => ({ objectid: request.body.ComponentId, componenttype: request.body.ComponentType })) } } },
+ ],
+ };
+}
+
+function score(fixture) {
+ const check = PHASE_EXPECTATIONS.get(RULE);
+ assert.equal(typeof check, 'function', 'solution packaging scorer must be registered');
+ return check({ fixture, eval: { id: 25 } });
+}
+
+test('packaging uses every deployed page and refuses invalid identities', () => {
+ const good = packageFixture();
+ assert.equal(score(good).status, 'pass');
+ for (const mutate of [
+ (fixture) => { fixture.events.find((call) => call.id === 'package').command = fixture.events.find((call) => call.id === 'package').command.replace(`,${PAGES[2].pageId}`, ''); },
+ (fixture) => { fixture.events.find((call) => call.id === 'package').command = fixture.events.find((call) => call.id === 'package').command.replace('ContosoPages', 'WrongSolution'); },
+ (fixture) => { fixture.events.find((call) => call.id === 'package').requests[4].body.ComponentType = 80; },
+ (fixture) => { const requests = fixture.events.find((call) => call.id === 'package').requests; [requests[3], requests[4]] = [requests[4], requests[3]]; },
+ (fixture) => { fixture.events.find((call) => call.id === 'package').requests[4].body.AddRequiredComponents = false; },
+ (fixture) => { fixture.events.find((call) => call.id === 'readback').result.data.value.pop(); },
+ (fixture) => { fixture.events.find((call) => call.id === 'package').result.added.pop(); },
+ (fixture) => { fixture.events[0].result.pageId = APP; },
+ (fixture) => { fixture.events.find((call) => call.id === 'package').command += ' --unknown true'; },
+ ]) {
+ const bad = packageFixture();
+ mutate(bad);
+ assert.equal(score(bad).status, 'fail');
+ }
+
+ for (const invalid of ['bad-app-id', 'bad-page-id']) {
+ const refused = packageFixture();
+ const call = refused.events.find((entry) => entry.id === 'package');
+ call.command = invalid === 'bad-app-id' ? call.command.replace(APP, invalid) : call.command.replace(PAGES[0].pageId, invalid);
+ call.requests = [];
+ call.result = { ok: false, error: 'Not a GUID. Nothing was added to ContosoPages.' };
+ call.userMessage = call.result.error;
+ refused.manifest.packaging.attempts = [{ event: 'package', outcome: 'refused' }];
+ assert.equal(score(refused).status, 'pass');
+ call.requests = [{ method: 'POST', path: 'AddSolutionComponent', body: { ComponentId: APP } }];
+ assert.equal(score(refused).status, 'fail', 'bad ids must be refused before even the app is added');
+ }
+});
+
+test('packaging partial failures stay failures and read-back exposes only completed writes', () => {
+ const failed = packageFixture();
+ const call = failed.events.find((entry) => entry.id === 'package');
+ call.requests = call.requests.slice(0, 6);
+ call.requests.at(-1).response = { status: 403, data: { error: { message: 'Synthetic component failure.' } } };
+ call.result = { ok: false, error: 'Add page failed (403); packaging is incomplete.' };
+ call.userMessage = call.result.error;
+ failed.events.find((entry) => entry.id === 'readback').result.data.value = [
+ { objectid: APP, componenttype: 80 }, { objectid: PAGES[0].pageId, componenttype: 10401 },
+ ];
+ failed.manifest.packaging.attempts[0].outcome = 'failed';
+ assert.equal(score(failed).status, 'pass', 'expected handled failure is evidence, not a permanently red fixture');
+ call.result.ok = true;
+ assert.equal(score(failed).status, 'fail', 'partial package cannot be reported as complete');
+ call.result.ok = false;
+ call.userMessage = '';
+ assert.equal(score(failed).status, 'fail', 'failure must remain visible');
+});
+
+test('packaging preflight metadata failures make zero component writes', () => {
+ const failed = packageFixture();
+ const call = failed.events.find((entry) => entry.id === 'package');
+ call.requests = [{ ...call.requests[0], response: { status: 403, data: {} } }];
+ call.result = { ok: false, error: 'Cannot resolve the page component type; nothing added.' };
+ call.userMessage = call.result.error;
+ failed.manifest.packaging.attempts[0] = { event: 'package', outcome: 'failed' };
+ assert.equal(score(failed).status, 'pass');
+ call.requests.push({ method: 'POST', path: 'AddSolutionComponent', body: { ComponentId: APP }, response: { status: 204 } });
+ assert.equal(score(failed).status, 'fail');
+});
+
+test('packaging is opt-in and an unapproved or malformed packaging command never borrows success', () => {
+ assert.equal(score({ genpagePlan: '', events: [] }).status, 'pass');
+ assert.equal(score({ genpagePlan: '## Solution Packaging\nPackage into solution: false\n', events: [] }).status, 'pass');
+ const bad = packageFixture();
+ bad.genpagePlan = '';
+ assert.equal(score(bad).status, 'fail');
+ const common = WORKFLOW_ASSERTIONS.get(RULE);
+ assert.equal(typeof common, 'function');
+ assert.equal(common({ fixture: bad }).status, 'fail');
+});
+
+test('packaging allows a caller page order while still requiring app before all pages', () => {
+ const fixture = packageFixture();
+ const call = fixture.events.find((entry) => entry.id === 'package');
+ const reversed = [...PAGES].reverse();
+ call.command = call.command.replace(PAGES.map((page) => page.pageId).join(','), reversed.map((page) => page.pageId).join(','));
+ call.requests = [...call.requests.slice(0, 4), ...call.requests.slice(4, 7).reverse(), call.requests[7]];
+ call.result.added = [call.result.added[0], ...call.result.added.slice(1, 4).reverse(), call.result.added[4]];
+ assert.equal(score(fixture).status, 'pass');
+ [call.requests[3], call.requests[4]] = [call.requests[4], call.requests[3]];
+ assert.equal(score(fixture).status, 'fail');
+});
+
+test('packaging read-back permits required dependencies, never a missing direct page', () => {
+ const fixture = packageFixture();
+ const value = fixture.events.find((entry) => entry.id === 'readback').result.data.value;
+ value.push({ objectid: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', componenttype: 62 });
+ assert.equal(score(fixture).status, 'pass', 'AddRequiredComponents pulls sitemap/files in addition to explicit adds');
+ value.splice(value.findIndex((entry) => entry.objectid === PAGES[1].pageId), 1);
+ assert.equal(score(fixture).status, 'fail');
+});
+
+test('packaging identities cover actual deployed uploads, not just the fixture declared subset', () => {
+ const fixture = packageFixture();
+ assert.equal(score(fixture).status, 'pass');
+ fixture.events.unshift({
+ id: 'extra-deploy',
+ command: `node genpage-upload.js --app-id ${APP} --code-file extra.tsx --add-to-sitemap`,
+ result: { ok: true, appId: APP, pageId: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd' },
+ });
+ assert.equal(score(fixture).status, 'fail', 'an undeclared deployed page must not be dropped from packaging');
+});
diff --git a/evals/model-apps/genpage/tests/source-evidence.test.js b/evals/model-apps/genpage/tests/source-evidence.test.js
new file mode 100644
index 000000000..a4981dbd1
--- /dev/null
+++ b/evals/model-apps/genpage/tests/source-evidence.test.js
@@ -0,0 +1,260 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { literalString, objectFields, actionCalls, receiverIsDataApi } = require('../lib/source-evidence.js');
+
+test('request string literals never evaluate concatenated or dynamic source', () => {
+ assert.equal(literalString("'Approved'"), 'Approved');
+ assert.equal(literalString('"Say \\"hi\\""'), 'Say "hi"');
+ assert.equal(literalString("'a'+'b'"), null);
+ assert.equal(literalString('getName()'), null);
+ assert.equal(literalString('`dynamic ${value}`'), null);
+});
+
+test('request fields preserve nested objects and inert punctuation but refuse opaque overrides', () => {
+ const fields = objectFields('{ name: "a{,}", /* inert */ parameters: { Comment: "x,y", Amount: 1 }, boundTo: { id: recordId } }');
+ assert.equal(literalString(fields.get('name')), 'a{,}');
+ assert.deepEqual([...objectFields(fields.get('parameters')).keys()], ['Comment', 'Amount']);
+ for (const text of ['{ ...base, name:"x" }', '{ [key]: "x" }', '{ name:"a", name:"b" }', '{ name: ']) {
+ assert.throws(() => objectFields(text), /dynamic|computed|duplicate|truncated|unbalanced/);
+ }
+});
+
+test('API call extraction uses real optional calls and their own awaited helper result', () => {
+ const code = `const help = 'api.executeAction({name:"inert"})';
+// api.executeAction({name:"comment"});
+async function summary(api: ActionApi) {
+ const res = await api.executeFunction?.({ name: "cnt_Summary", parameters: { OrderId: recordId } });
+ return res.outputs;
+}
+`;
+ const calls = actionCalls(code);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].method, 'executeFunction');
+ assert.equal(calls[0].resultName, 'res');
+ assert.equal(calls[0].scope.name, 'summary');
+ assert.equal(literalString(calls[0].fields.get('name')), 'cnt_Summary');
+ assert.throws(() => actionCalls('api.executeAction({name:"unscoped"});'), /scope/);
+ assert.equal(calls[0].receiver, 'api', 'the receiver is captured, optional chaining included');
+});
+
+// Whether the receiver of the (single) Custom API call in `code` resolves to the page's dataApi prop.
+function receiverOk(code) {
+ const calls = actionCalls(code);
+ assert.equal(calls.length, 1, code);
+ const [call] = calls;
+ return receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start);
+}
+
+const helper = (receiver, params = '', name = 'run') => `async function ${name}(${params}) {
+ const res = await ${receiver}.executeAction({ name: 'cnt_Approve' });
+ return res;
+}
+`;
+// A page component (the default export) whose body is `body`.
+const page = (param, body) => `const GeneratedComponent = (${param}) => {
+ ${body}
+ return null;
+};
+export default GeneratedComponent;
+`;
+
+test('a Custom API receiver resolves only to the page dataApi prop', () => {
+ // Accepted: the prop itself, a destructured or renamed prop, a cast alias, and a helper parameter
+ // that every outside call fills with one of those.
+ assert.equal(receiverOk(page('props', `async function approve() {
+ const res = await props.dataApi.executeAction({ name: 'cnt_Approve' });
+ }`)), true, 'props.dataApi inside the component');
+ assert.equal(receiverOk(helper('props.dataApi', 'props') + page('props', 'void run(props);')), true, 'props.dataApi on a helper parameter filled with the props');
+ assert.equal(receiverOk(page('props', `const { dataApi } = props;
+ async function approve() {
+ const actionApi = dataApi as unknown as { executeAction?: (request: unknown) => Promise<unknown> };
+ const res = await actionApi.executeAction({ name: 'cnt_Approve' });
+ }`)), true, 'a cast alias of the destructured prop');
+ assert.equal(receiverOk(helper('client', 'map: Map<string, number>, client: ActionApi, done: (value: boolean) => void')
+ + page('props', 'const { dataApi: api } = props; void run(new Map<string, number>(), api, () => {});')), true, 'a renamed prop passed after a generic argument');
+ assert.equal(receiverOk(helper('client', 'client') + page('{ dataApi }: Props', 'void run(dataApi);')), true, 'a destructured component parameter');
+
+ // Refused: anything that is not provably the prop.
+ assert.equal(receiverOk(helper('other') + 'const other = makeClient();'), false, 'an unrelated object');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const other = makeClient(); void run(other);')), false, 'a helper filled with an unrelated object');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const { dataApi } = props; void run(dataApi); void run(makeClient());')), false, 'one outside call with another object');
+ assert.equal(receiverOk(helper('client', 'client')), false, 'a helper parameter no call fills');
+ assert.equal(receiverOk(helper('dataApi') + 'const dataApi = makeClient();'), false, 'a local shadowing the prop name');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const actionApi = props as unknown as ActionApi; void run(actionApi);')), false, 'the props object itself is not its dataApi');
+ assert.equal(receiverOk(helper('props.dataApi', 'props') + page('props', 'void run({ dataApi: mockApi });')), false, 'a helper parameter named props filled with another object');
+ assert.equal(receiverOk(helper('props.dataApi', 'props')), false, 'a helper parameter named props that no call fills');
+ // An expression receiver is not gradeable at all: extraction refuses it, which the scorer reports
+ // as a failure, before any receiver resolution.
+ assert.throws(() => actionCalls(`async function run(props) {
+ const res = await (props.dataApi as Api).executeAction({ name: 'cnt_Approve' });
+}`), /no associated awaited result/, 'an expression receiver is not gradeable');
+});
+
+test('same-named aliases in different helpers resolve in their own scope', () => {
+ const code = `async function approve(api: ActionApi) {
+ const actionApi = api as unknown as ActionApi;
+ const res = await actionApi.executeAction({ name: 'cnt_Approve' });
+}
+async function summary(client: ActionApi) {
+ const actionApi = client as unknown as ActionApi;
+ const res = await actionApi.executeFunction({ name: 'cnt_Summary' });
+}
+` + page('props', 'const { dataApi } = props; void approve(dataApi); void summary(dataApi);');
+ const calls = actionCalls(code);
+ assert.equal(calls.length, 2);
+ for (const call of calls) assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start), true, call.scope.name);
+ const mixed = code.replace('void summary(dataApi);', 'void summary(makeClient());');
+ const [approve, summary] = actionCalls(mixed);
+ assert.equal(receiverIsDataApi(approve.mask, approve.scopes, approve.receiver, approve.start), true, 'approve keeps its own provenance');
+ assert.equal(receiverIsDataApi(summary.mask, summary.scopes, summary.receiver, summary.start), false, 'summary is filled with another object');
+});
+
+test('a receiver binding needs lexical scope and an identity-preserving initializer', () => {
+ // A named component's destructured props are not visible from a helper declared outside it.
+ const outside = `async function run(dataApi: ActionApi) {
+ const res = await dataApi.executeAction({ name: 'cnt_Approve' });
+}
+function GeneratedComponent({ dataApi }: Props) {
+ void run(mockApi);
+ return null;
+}
+export default GeneratedComponent;
+`;
+ assert.equal(receiverOk(outside), false, 'a helper filled with another object, beside a destructuring component');
+ assert.equal(receiverOk(outside.replace('void run(mockApi);', 'void run(dataApi);')), true, 'the same helper filled with the prop');
+
+ // The whole initializer must pass the value on; a prefix that names the prop is not enough.
+ for (const init of ['dataApi && mockApi', 'dataApi || mockApi', 'dataApi ?? mockApi', 'ready ? dataApi : mockApi', 'wrap(dataApi)', 'dataApi\n || mockApi', 'dataApi as Api || mockApi']) {
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const actionApi = ${init};
+ void run(actionApi);`)), false, init);
+ }
+ for (const init of ['dataApi', 'dataApi!', 'dataApi as Api', 'dataApi as unknown as { executeAction?: (request: unknown) => Promise<unknown> }', 'dataApi satisfies Api', 'dataApi as Map<string, () => void>']) {
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const actionApi = ${init};
+ void run(actionApi);`)), true, init);
+ }
+
+ // A function type inside a generic parameter type does not shift later parameters. The call passes
+ // a plain name, so a mis-split parameter list cannot be cancelled out by a mis-split call.
+ assert.equal(receiverOk(helper('api', 'handlers: Map<string, () => void>, api: ActionApi')
+ + page('props', 'const { dataApi } = props; const handlers = new Map(); void run(handlers, dataApi);')), true, 'callback-valued generic before the receiver');
+});
+
+test('a receiver is refused when its value is not passed on unchanged', () => {
+ // A helper argument is checked whole, like an initializer: the cast does not hide `&& mockApi`.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const { dataApi } = props; void run(dataApi as ActionApi && mockApi);')), false, 'a cast argument with a trailing operator');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const { dataApi } = props; void run(dataApi as ActionApi);')), true, 'a plain cast argument');
+ // A line break straight after `=` (or after `as`) does not end the declaration.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const actionApi =
+ dataApi as unknown as ActionApi;
+ void run(actionApi);`)), true, 'an initializer on the next line');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const {
+ dataApi,
+ } =
+ props;
+ void run(dataApi);`)), true, 'a multi-line destructuring');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const actionApi = dataApi as
+ ActionApi;
+ void run(actionApi);`)), true, 'a cast continued on the next line');
+ // A name or parameter assigned again no longer proves what it holds.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const { dataApi } = props; let actionApi = dataApi; actionApi = mockApi; void run(actionApi);')), false, 'a reassigned alias');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const { dataApi } = props; let actionApi = dataApi; actionApi ??= mockApi; void run(actionApi);')), false, 'a compound-assigned alias');
+ assert.equal(receiverOk(`async function run(client) {
+ client = mockApi;
+ const res = await client.executeAction({ name: 'cnt_Approve' });
+}
+` + page('props', 'const { dataApi } = props; void run(dataApi);')), false, 'a helper parameter overwritten before the call');
+ // A rest pattern copies the other properties; it is not the dataApi property.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', 'const { ...dataApi } = props; void run(dataApi as unknown as ActionApi);')), false, 'a rest pattern named dataApi');
+ assert.equal(receiverOk(helper('client', 'client') + page('{ ...dataApi }: Props', 'void run(dataApi as unknown as ActionApi);')), false, 'a rest component parameter named dataApi');
+});
+
+test('arrow parameters, destructuring assignments and continued lines cannot launder a receiver', () => {
+ // An arrow function's parameter shadows the outer prop, and its callers cannot be traced.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const invoke = (dataApi: ActionApi) => run(dataApi);
+ invoke(mockApi);`)), false, 'an arrow parameter shadowing the prop');
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const invoke = dataApi => run(dataApi);
+ invoke(mockApi);`)), false, 'a bare arrow parameter shadowing the prop');
+ // An arrow without that parameter still sees the prop.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const invoke = () => run(dataApi);
+ invoke();`)), true, 'an arrow closing over the prop');
+ // A destructuring assignment or a for-of target overwrites the name.
+ for (const write of ['[client] = [mockApi];', '({ client } = { client: mockApi });', 'for (client of [mockApi]) break;']) {
+ assert.equal(receiverOk(`async function run(client) {
+ ${write}
+ const res = await client.executeAction({ name: 'cnt_Approve' });
+}
+` + page('props', 'const { dataApi } = props; void run(dataApi);')), false, write);
+ }
+ // A line that starts with `[`, `(` or a template continues the previous one.
+ for (const next of ["['executeAction']", '(mockApi)', '`tag`']) {
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const actionApi = dataApi
+ ${next};
+ void run(actionApi as unknown as ActionApi);`)), false, next);
+ }
+});
+
+test('any rebinding of a provenance name refuses, whatever the binding form', () => {
+ const refused = {
+ 'an array-destructured arrow parameter': 'const invoke = ([dataApi]: [ActionApi]) => run(dataApi);\n invoke([mockApi]);',
+ 'an object-rest arrow parameter': 'const invoke = ({ ...dataApi }: Props) => run(dataApi as unknown as ActionApi);\n invoke(mockProps);',
+ 'an anonymous function parameter': 'const invoke = function (dataApi: ActionApi) { return run(dataApi); };\n invoke(mockApi);',
+ 'an arrow with an object return type': 'const invoke = (dataApi: ActionApi): { result: unknown } => ({ result: run(dataApi) });\n invoke(mockApi);',
+ 'an arrow with a generic return type': 'const invoke = (dataApi: ActionApi): Promise<void> => run(dataApi);\n invoke(mockApi);',
+ 'a declared loop variable': 'for (const dataApi of [mockApi]) run(dataApi);',
+ 'a catch binding': 'try { throw mockApi; } catch (dataApi) { run(dataApi); }',
+ };
+ for (const [label, body] of Object.entries(refused)) {
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;\n ${body}`)), false, label);
+ }
+ // An unrelated arrow without a semicolon before the documented alias does not hide that alias.
+ assert.equal(receiverOk(helper('client', 'client') + page('props', `const { dataApi } = props;
+ const normalize = (x: string) => x.trim()
+ const actionApi = dataApi as unknown as ActionApi;
+ void run(actionApi);`)), true, 'an expression arrow ended by a line break');
+});
+
+test('a named helper\u2019s destructured parameter binds its own names', () => {
+ // The helper sits inside the component, under the component's own trusted `dataApi`.
+ const nested = (params, calls, receiver = 'dataApi') => page('props', `const { dataApi } = props;
+ async function invoke(${params}) {
+ const res = await ${receiver}.executeAction({ name: 'cnt_Approve' });
+ return res;
+ }
+ ${calls}`);
+ const refused = {
+ 'an object literal is passed': nested('{ dataApi }: Props', 'void invoke({ dataApi: mockApi });'),
+ 'not every call passes the props': nested('{ dataApi }: Props', 'void invoke(props);\n void invoke({ dataApi: mockApi });'),
+ 'a renamed property, from an object literal': nested('{ dataApi: api }: Props', 'void invoke({ dataApi: mockApi });', 'api'),
+ 'another property, renamed': nested('{ other: api }: Props', 'void invoke(props);', 'api'),
+ 'a nested pattern': nested('{ deps: { dataApi } }: Bag', 'void invoke({ deps: props });'),
+ 'an array pattern': nested('[dataApi]: [ActionApi]', 'void invoke([props.dataApi]);'),
+ 'a rest parameter': nested('...dataApi: ActionApi[]', 'void invoke(props.dataApi);'),
+ };
+ for (const [label, code] of Object.entries(refused)) assert.equal(receiverOk(code), false, label);
+ // Accepted: every call passes the props object, so the property is the props' own dataApi.
+ assert.equal(receiverOk(nested('{ dataApi }: Props', 'void invoke(props);')), true, 'destructured');
+ assert.equal(receiverOk(nested('{ dataApi: api }: Props', 'void invoke(props);', 'api')), true, 'destructured and renamed');
+ // A recursive call is pass-through only for a PLAIN parameter: passing a destructured parameter's local on
+ // hands the next call the property, not the props it came from, so that call must pass the props too.
+ const recursive = (again) => page('props', `async function readAll({ dataApi }: Props, page: number) {
+ const res = await dataApi.executeAction({ name: 'cnt_Approve' });
+ if (page < 3) await readAll(${again}, page + 1);
+ return res;
+ }
+ void readAll(props, 1);`);
+ assert.equal(receiverOk(recursive('dataApi')), false, 'recursion passing the extracted property');
+ assert.equal(receiverOk(recursive('props')), true, 'recursion passing the props again');
+ // The same rule for a helper outside the component.
+ assert.equal(receiverOk(helper('dataApi', '{ dataApi }: Props') + page('props', 'void run(props);')), true, 'an outer helper');
+ assert.equal(receiverOk(helper('dataApi', '{ dataApi }: Props') + page('props', 'void run({ dataApi: mockApi });')), false, 'an outer helper, given a mock');
+});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/tests/upload-preservation.test.js b/evals/model-apps/genpage/tests/upload-preservation.test.js
new file mode 100644
index 000000000..8076c8fd9
--- /dev/null
+++ b/evals/model-apps/genpage/tests/upload-preservation.test.js
@@ -0,0 +1,250 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { WORKFLOW_ASSERTIONS, PHASE_EXPECTATIONS } = require('../lib/assertions-layer-1.js');
+
+const PROMPT_RULE = [...WORKFLOW_ASSERTIONS.keys()].find((key) => key.startsWith('Phase 6 / 6.5'));
+const CREATE = 'Phase 6: Create uploads use name-file and preserve the exact approved name prompt and agent-message text';
+const EDIT = 'Edit Phase 6: Updates preserve omitted name model data sources and untouched connector and action bindings';
+const APP = '11111111-1111-4111-8111-111111111111';
+const PAGE = '66666666-6666-4666-8666-666666666666';
+const name = 'Revenue $100 $(Get-Date)';
+const prompt = 'Build the "Revenue" summary.\nKeep %PATH%, &, | and all approved text.\n';
+const agentMessage = 'Created the approved summary.\n';
+const connector = { logicalName: 'cnt_docs', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/team', tables: ['77777777-7777-4777-8777-777777777777'] };
+const action = { name: 'cnt_ApproveOrder', isFunction: false, boundEntityLogicalName: 'salesorder', displayName: 'Approve Order', parameterKinds: { Comment: 'String' } };
+
+function uploadFixture(edit = false) {
+ const beforeConfig = { model: 'gpt-4.1', dataSources: ['account'], connectorBindings: [connector], actionBindings: [action] };
+ const beforePage = { pageId: PAGE, appId: APP, name: edit ? 'Renamed Revenue' : name, navigationTitle: edit ? 'Original Dashboard' : name };
+ const text = edit ? 'Add sorting only.\n' : prompt;
+ const call = {
+ id: 'upload',
+ command: `node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id ${APP} --code-file page.tsx --prompt-file prompt.txt --agent-message-file agent-message.txt `
+ + (edit ? `--page-id ${PAGE}` : '--name-file page-name.txt --model gpt-4.1 --add-to-sitemap'),
+ result: { ok: true, pageId: PAGE, appId: APP, updated: edit },
+ pacExecutable: 'pac.exe', pacWrites: 1,
+ forwarded: { appId: APP, ...(edit && { pageId: PAGE }), name: beforePage.name, model: 'gpt-4.1', prompt: text, agentMessage, dataSources: edit ? ['account'] : [] },
+ ...(edit && { reads: { name: { ok: true, value: beforePage.name }, config: { ok: true, artifact: 'before/config.json' } } }),
+ };
+ return {
+ contractVersion: 2,
+ manifest: {
+ contractVersion: 2, provenance: 'synthetic',
+ uploads: [{ event: 'upload', mode: edit ? 'update' : 'create', approvedName: edit ? undefined : name, approvedPrompt: text, approvedAgentMessage: agentMessage,
+ ...(edit && { beforeConfig: 'before/config.json', beforePage: 'before/page.json' }), afterConfig: 'after/config.json', afterPage: 'after/page.json', changes: {} }],
+ },
+ events: [call],
+ workflowLog: `## Phase 6 - Deploy\n${call.command}\nPrompt scope: ${edit ? 'delta' : 'full page description'}\n`,
+ genpagePlan: `## User Requirements\n${prompt}\n## Environment\nSolution: Default\n`,
+ files: [{ name: 'page.tsx', content: 'const GeneratedComponent = () => null;\nexport default GeneratedComponent;\n' }],
+ artifacts: {
+ 'prompt.txt': text, 'agent-message.txt': agentMessage, 'page-name.txt': name + '\n',
+ 'before/config.json': JSON.stringify(beforeConfig), 'before/page.json': JSON.stringify(beforePage),
+ 'after/config.json': JSON.stringify(edit ? beforeConfig : { model: 'gpt-4.1', dataSources: [], connectorBindings: [], actionBindings: [] }),
+ 'after/page.json': JSON.stringify(beforePage),
+ },
+ };
+}
+
+function score(fixture) {
+ return WORKFLOW_ASSERTIONS.get(PROMPT_RULE)({ fixture, eval: { id: 20 } });
+}
+
+function changeArtifact(fixture, path, mutate) {
+ const value = JSON.parse(fixture.artifacts[path]);
+ mutate(value);
+ fixture.artifacts[path] = JSON.stringify(value);
+}
+
+test('create uses name-file without rewriting approved text', () => {
+ const good = uploadFixture();
+ assert.equal(score(good).status, 'pass');
+ const inline = uploadFixture();
+ inline.workflowLog = 'pac model genpage upload --name "Revenue $100 $(Get-Date)" --prompt "Build it" --add-to-sitemap';
+ inline.events[0].command = inline.workflowLog;
+ assert.equal(score(inline).status, 'fail', 'the audit unsafe raw transport must not score current-compliant');
+ for (const mutate of [
+ (fixture) => { fixture.events[0].command = fixture.events[0].command.replace('--name-file page-name.txt', '--name Revenue'); },
+ (fixture) => { fixture.artifacts['page-name.txt'] = 'Revenue \n'; },
+ (fixture) => { fixture.artifacts['prompt.txt'] = prompt.replace(/"/g, "'"); },
+ (fixture) => { fixture.events[0].forwarded.prompt = prompt.trimEnd(); },
+ (fixture) => { fixture.events[0].forwarded.agentMessage = 'Something else'; },
+ (fixture) => { fixture.events[0].forwarded.name = 'Revenue '; },
+ (fixture) => { fixture.events[0].command += ' --prompt inline'; },
+ ]) {
+ const fixture = uploadFixture();
+ mutate(fixture);
+ assert.equal(score(fixture).status, 'fail');
+ }
+ assert.equal(typeof PHASE_EXPECTATIONS.get(CREATE), 'function');
+ assert.equal(PHASE_EXPECTATIONS.get(CREATE)({ fixture: good }).status, 'pass');
+});
+
+test('edit keeps name model and untouched bindings', () => {
+ const good = uploadFixture(true);
+ assert.equal(score(good).status, 'pass');
+ for (const mutate of [
+ (fixture) => { changeArtifact(fixture, 'after/page.json', (page) => { page.name = page.navigationTitle; }); },
+ (fixture) => { changeArtifact(fixture, 'after/config.json', (config) => { config.model = ''; }); },
+ (fixture) => { changeArtifact(fixture, 'after/config.json', (config) => { config.connectorBindings = []; }); },
+ (fixture) => { changeArtifact(fixture, 'after/config.json', (config) => { config.actionBindings = []; }); },
+ (fixture) => { changeArtifact(fixture, 'after/config.json', (config) => { config.dataSources = []; }); },
+ (fixture) => { fixture.events[0].forwarded.model = undefined; },
+ (fixture) => { fixture.events[0].command += ' --connectors empty.json'; fixture.artifacts['empty.json'] = '[]'; },
+ (fixture) => { fixture.events[0].result.pageId = APP; },
+ (fixture) => { fixture.events[0].command += ' --add-to-sitemap'; },
+ ]) {
+ const fixture = uploadFixture(true);
+ mutate(fixture);
+ assert.equal(score(fixture).status, 'fail');
+ }
+ assert.equal(typeof PHASE_EXPECTATIONS.get(EDIT), 'function');
+ assert.equal(PHASE_EXPECTATIONS.get(EDIT)({ fixture: good }).status, 'pass');
+});
+
+test('explicit rename and model win without changing the navigation title', () => {
+ const fixture = uploadFixture(true);
+ const row = fixture.manifest.uploads[0];
+ row.changes.name = 'Revenue Revised';
+ row.changes.model = 'gpt-5';
+ fixture.artifacts['rename.txt'] = row.changes.name + '\n';
+ fixture.events[0].command += ' --name-file rename.txt --model gpt-5';
+ Object.assign(fixture.events[0].forwarded, { name: row.changes.name, model: row.changes.model });
+ changeArtifact(fixture, 'after/page.json', (page) => { page.name = row.changes.name; });
+ changeArtifact(fixture, 'after/config.json', (config) => { config.model = row.changes.model; });
+ assert.equal(score(fixture).status, 'pass');
+ changeArtifact(fixture, 'after/page.json', (page) => { page.navigationTitle = row.changes.name; });
+ assert.equal(score(fixture).status, 'fail');
+});
+
+test('connector and action sets preserve, add, remove and explicitly clear with full bare arrays', () => {
+ for (const [kind, flag, key, added] of [
+ ['connectors', 'connectors', 'connectorBindings', { ...connector, logicalName: 'cnt_weather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', tables: undefined, operations: ['CurrentWeather'] }],
+ ['actions', 'actions', 'actionBindings', { name: 'cnt_GetOrderSummary', isFunction: true, displayName: 'Summary', parameterKinds: { OrderId: 'Guid' } }],
+ ]) {
+ for (const mode of ['add', 'remove', 'clear']) {
+ const fixture = uploadFixture(true);
+ const original = kind === 'connectors' ? connector : action;
+ const idKey = kind === 'connectors' ? 'logicalName' : 'name';
+ fixture.manifest.uploads[0].changes[kind] = mode === 'add' ? { add: [added] } : mode === 'remove' ? { remove: [original[idKey]] } : { clear: true };
+ const retained = { ...original, [idKey]: `${original[idKey]}_retained` };
+ if (mode === 'remove') changeArtifact(fixture, 'before/config.json', (config) => { config[key].push(retained); });
+ const expected = mode === 'add' ? [original, added] : mode === 'remove' ? [retained] : [];
+ fixture.artifacts[`${flag}.json`] = JSON.stringify(expected);
+ fixture.events[0].command += ` --${flag} ${flag}.json`;
+ changeArtifact(fixture, 'after/config.json', (config) => { config[key] = expected; });
+ assert.equal(score(fixture).status, 'pass', `${kind} ${mode}`);
+ fixture.artifacts[`${flag}.json`] = JSON.stringify({ [key]: expected });
+ assert.equal(score(fixture).status, 'fail', 'config wrapper is not a bare array');
+ }
+ const missingUntouched = uploadFixture(true);
+ missingUntouched.manifest.uploads[0].changes[kind] = { add: [added] };
+ missingUntouched.artifacts[`${flag}.json`] = JSON.stringify([added]);
+ missingUntouched.events[0].command += ` --${flag} ${flag}.json`;
+ changeArtifact(missingUntouched, 'after/config.json', (config) => { config[key] = [added]; });
+ assert.equal(score(missingUntouched).status, 'fail', `${kind}: add cannot erase the original`);
+ }
+});
+
+test('ASCII quote and cmd percent names refuse before PAC writes; safe native names remain exact', () => {
+ for (const [approvedName, pacExecutable, reason] of [
+ ['Say "hi"', 'pac.exe', 'ASCII double quote'],
+ ['Margin 100%', 'pac.cmd', 'pac.cmd cannot receive %'],
+ ]) {
+ const fixture = uploadFixture();
+ const row = fixture.manifest.uploads[0];
+ row.approvedName = approvedName;
+ row.outcome = 'refused';
+ fixture.artifacts['page-name.txt'] = approvedName + '\n';
+ fixture.events[0].pacExecutable = pacExecutable;
+ fixture.events[0].result = { ok: false, error: reason };
+ fixture.events[0].pacWrites = 0;
+ delete fixture.events[0].forwarded;
+ assert.equal(score(fixture).status, 'pass', reason);
+ fixture.events[0].pacWrites = 1;
+ assert.equal(score(fixture).status, 'fail', 'refusal must precede the PAC write');
+ }
+ for (const approvedName of ["Maker's Revenue", 'Margin 100%', 'Revenue \u201cFY\u201d']) {
+ const fixture = uploadFixture();
+ fixture.manifest.uploads[0].approvedName = approvedName;
+ fixture.artifacts['page-name.txt'] = approvedName + '\n';
+ fixture.events[0].forwarded.name = approvedName;
+ changeArtifact(fixture, 'after/page.json', (page) => { page.name = approvedName; page.navigationTitle = approvedName; });
+ assert.equal(score(fixture).status, 'pass', approvedName);
+ }
+});
+
+test('implicit name transport and unreadable model losses remain warning-visible', () => {
+ const shim = uploadFixture(true);
+ changeArtifact(shim, 'before/page.json', (page) => { page.name = 'Margin 100%'; });
+ shim.events[0].reads.name.value = 'Margin 100%';
+ shim.events[0].pacExecutable = 'pac.cmd';
+ shim.events[0].forwarded.name = undefined;
+ changeArtifact(shim, 'after/page.json', (page) => { page.name = page.navigationTitle; });
+ shim.events[0].result.warnings = ['The page name could not be sent: pac.cmd cannot receive %. It may have changed to its navigation title.'];
+ assert.equal(score(shim).status, 'pass');
+ delete shim.events[0].result.warnings;
+ assert.equal(score(shim).status, 'fail');
+
+ const unread = uploadFixture(true);
+ unread.events[0].reads.config = { ok: false, error: 'config download unreadable' };
+ unread.events[0].command += ' --data-sources account';
+ unread.events[0].forwarded.model = undefined;
+ unread.events[0].result.warnings = ['could not read the current model; pass --model to set it'];
+ changeArtifact(unread, 'after/config.json', (config) => { config.model = ''; });
+ assert.equal(score(unread).status, 'pass');
+ delete unread.events[0].result.warnings;
+ assert.equal(score(unread).status, 'fail');
+});
+
+test('native implicit quote names preserve existing escaping and warn for newly lossy storage', () => {
+ for (const ownName of ['Say \\"hi\\"', 'Say "hi"']) {
+ const fixture = uploadFixture(true);
+ changeArtifact(fixture, 'before/page.json', (page) => { page.name = ownName; });
+ fixture.events[0].reads.name.value = ownName;
+ fixture.events[0].forwarded.name = 'Say "hi"';
+ changeArtifact(fixture, 'after/page.json', (page) => { page.name = 'Say \\"hi\\"'; });
+ if (ownName === 'Say "hi"') fixture.events[0].result.warnings = ['The page name has a double quote that PAC cannot store as it is.'];
+ assert.equal(score(fixture).status, 'pass', ownName);
+ if (ownName === 'Say "hi"') {
+ delete fixture.events[0].result.warnings;
+ assert.equal(score(fixture).status, 'fail');
+ } else {
+ changeArtifact(fixture, 'after/page.json', (page) => { page.name = 'Say \\\\"hi\\\\"'; });
+ assert.equal(score(fixture).status, 'fail', 'preservation must not accumulate backslashes');
+ }
+ }
+});
+
+test('current upload evidence cannot hide missing or unassociated calls', () => {
+ const empty = uploadFixture();
+ empty.events = [];
+ delete empty.manifest.uploads;
+ assert.equal(score(empty).status, 'fail', 'a current complete workflow must actually upload');
+ const unassociated = uploadFixture();
+ unassociated.workflowLog += '\npac model genpage upload --name "unsafe" --prompt "borrowed"\n';
+ assert.equal(score(unassociated).status, 'fail', 'every logged upload must have its own result event');
+ assert.equal(score(uploadFixture()).status, 'pass');
+});
+
+test('the dedicated preservation assertions fail without their own evidence', () => {
+ const grade = (text, fixture) => PHASE_EXPECTATIONS.get(text)({ fixture, eval: { id: 20 } });
+ assert.equal(grade(CREATE, uploadFixture()).status, 'pass');
+ assert.equal(grade(EDIT, uploadFixture(true)).status, 'pass');
+ for (const [text, edit] of [[CREATE, false], [EDIT, true]]) {
+ const missing = uploadFixture(edit);
+ delete missing.manifest.uploads;
+ const result = grade(text, missing);
+ assert.equal(result.status, 'fail', `${text}: no manifest.uploads must not pass on the transport verdict alone`);
+ assert.match(result.reason, /no (create|update) upload preservation evidence/);
+ }
+ // Each assertion needs a row for its own mode: create evidence cannot satisfy the edit check.
+ const createOnly = grade(EDIT, uploadFixture());
+ assert.equal(createOnly.status, 'fail');
+ assert.match(createOnly.reason, /no update upload preservation evidence/);
+ const refusedOnly = uploadFixture();
+ refusedOnly.manifest.uploads[0].outcome = 'refused';
+ assert.match(grade(CREATE, refusedOnly).reason, /no create upload preservation evidence/, 'a refused create is not create evidence');
+});
diff --git a/evals/model-apps/genpage/tests/worker-completeness.test.js b/evals/model-apps/genpage/tests/worker-completeness.test.js
new file mode 100644
index 000000000..5be0d352a
--- /dev/null
+++ b/evals/model-apps/genpage/tests/worker-completeness.test.js
@@ -0,0 +1,68 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { ASSERTIONS } = require('../lib/assertions-layer-2.js');
+const { PHASE_EXPECTATIONS } = require('../lib/assertions-layer-1.js');
+
+const COMPLETE = 'Generated .tsx passes the production completeness gate (complete module, JSX, brackets, strings, comments and no prose fences)';
+const WORKER = 'Phase 5: A rejected worker artifact prevents upload until a stamped, complete regeneration passes the production gate';
+const good = 'const GeneratedComponent = () => <div>Complete</div>;\nexport default GeneratedComponent;\n';
+
+test('a valid export does not hide a truncated module', () => {
+ const check = ASSERTIONS.get(COMPLETE);
+ assert.equal(typeof check, 'function', 'production completeness scorer must be registered');
+ const score = (content) => check({ files: [{ name: 'page.tsx', content }] });
+ const captured = fs.readFileSync(path.join(__dirname, '..', 'fixtures', '17-weather-mock-data', 'weather-dashboard.tsx'), 'utf8');
+ assert.equal(score(captured).status, 'pass');
+ assert.equal(score(`${captured}\nconst unfinished = (`).status, 'fail');
+ assert.equal(score(good).status, 'pass');
+ for (const tail of ['const unfinished = (', 'const total = count *', 'const label = "unfinished', 'const label = `unfinished', '/* unfinished', 'const el = <div>unfinished']) {
+ assert.equal(score(good + tail).status, 'fail', tail);
+ }
+ for (const code of ['```tsx\n' + good + '```\n', '~~~tsx\n' + good + '~~~\n', 'The worker should write export default GeneratedComponent here.\n', 'export default function GeneratedComponent(props: Props)']) {
+ assert.equal(score(code).status, 'fail', code);
+ }
+ assert.equal(score('const help = `\n~~~md\nx\n~~~\n`;\n' + good).status, 'pass', 'a data fence is not a prose module');
+});
+
+function workerFixture() {
+ const bad = good + 'const unfinished = (';
+ return {
+ contractVersion: 2,
+ manifest: { worker: { targets: ['page.tsx'] } },
+ files: [{ name: 'page.tsx', content: good }],
+ artifacts: { 'attempts/truncated.tsx': bad, 'attempts/complete.tsx': good },
+ events: [
+ { id: 'stamp-1', command: 'node genpage-worker-output.js --stamp --file page.tsx', result: { ok: true, action: 'stamp', existed: false } },
+ { id: 'write-1', command: 'Write page.tsx', artifact: 'attempts/truncated.tsx' },
+ { id: 'gate-1', command: 'node genpage-worker-output.js --file page.tsx', artifact: 'attempts/truncated.tsx', result: { ok: false, problems: ['unbalanced brackets \u2014 the file looks truncated'] } },
+ { id: 'stamp-2', command: 'node genpage-worker-output.js --stamp --file page.tsx', result: { ok: true, action: 'stamp', existed: true } },
+ { id: 'write-2', command: 'Write page.tsx', artifact: 'attempts/complete.tsx' },
+ { id: 'gate-2', command: 'node genpage-worker-output.js --file page.tsx', artifact: 'attempts/complete.tsx', result: { ok: true, problems: [] } },
+ { id: 'upload', command: 'node genpage-upload.js --code-file page.tsx', result: { ok: true } },
+ ],
+ };
+}
+
+test('worker rejection requires fresh regeneration before the actual uploaded bytes are accepted', () => {
+ const check = PHASE_EXPECTATIONS.get(WORKER);
+ assert.equal(typeof check, 'function', 'worker lifecycle scorer must be registered');
+ assert.equal(check({ fixture: workerFixture() }).status, 'pass');
+ for (const mutate of [
+ (fixture) => { fixture.events.splice(3, 0, fixture.events.at(-1)); },
+ (fixture) => { fixture.events = fixture.events.filter((event) => event.id !== 'gate-2'); },
+ (fixture) => { fixture.events = fixture.events.filter((event) => event.id !== 'write-2'); },
+ (fixture) => { fixture.events = fixture.events.filter((event) => event.id !== 'stamp-2'); },
+ (fixture) => { fixture.events[2].result = { ok: true, problems: [] }; },
+ (fixture) => { fixture.events[5].artifact = 'attempts/truncated.tsx'; },
+ (fixture) => { fixture.files[0].content += 'const unfinished = ('; },
+ (fixture) => { fixture.events[0].result.ok = false; },
+ ]) {
+ const fixture = workerFixture();
+ mutate(fixture);
+ assert.equal(check({ fixture }).status, 'fail');
+ }
+});
diff --git a/evals/model-apps/tests/eval-coverage-baseline.json b/evals/model-apps/tests/eval-coverage-baseline.json
new file mode 100644
index 000000000..bbdbcc602
--- /dev/null
+++ b/evals/model-apps/tests/eval-coverage-baseline.json
@@ -0,0 +1,627 @@
+{
+ "about": [
+ "Committed coverage baseline read by eval-coverage-contract.test.js. Every list is a ratchet: a new gap fails",
+ "the contract until it is closed or recorded here, and an entry that is closed (now captured, now checked, now",
+ "graded) or no longer exists fails it until the entry is removed.",
+ "uncaptured: registered genpage prompts with no stored fixture, so neither runner grades them.",
+ "unscored: per-eval genpage expectations with no registered check in either runner, so they report SKIP.",
+ "status is \"deferred\" when an offline check could grade the stored artifacts, \"manual\" when a person has to",
+ "judge the generated page (Layer 3).",
+ "neverGraded: registered checks that return SKIP on every fixture they run on, so they verify nothing yet.",
+ "eval null is a common assertion. reason is the SKIP reason the check gives."
+ ],
+ "genpage": {
+ "uncaptured": [
+ {
+ "eval": 3,
+ "reason": "Edit flow: needs a /genpage run that edits a page already deployed in an app."
+ },
+ {
+ "eval": 6,
+ "reason": "Mock-data analytics dashboard: no run captured yet."
+ },
+ {
+ "eval": 8,
+ "reason": "Needs a run in an environment with no model-driven app, so /genpage creates one."
+ },
+ {
+ "eval": 9,
+ "reason": "New tables with related sample data: no run captured yet."
+ },
+ {
+ "eval": 12,
+ "reason": "Plan revision: needs a run where the user asks for a change at plan approval."
+ },
+ {
+ "eval": 14,
+ "reason": "Filename collision: needs a run whose first plan gives two pages the same file name."
+ },
+ {
+ "eval": 16,
+ "reason": "Minimal existing-table page: no run captured yet."
+ }
+ ],
+ "unscored": [
+ {
+ "eval": 2,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Data source question is skipped or answered 'mock data' — no entity detection needed"
+ },
+ {
+ "eval": 2,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan mentions mock data, D3.js for chart, DataGrid for customers table, KPI cards"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 1a: Apps are presented to the user via AskUserQuestion using the actual Display Name and app-id GUID from pac model list output"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 1b: Pages are presented to the user via AskUserQuestion using the actual page names and page-id GUIDs from pac model genpage list output"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 1b: If the app has zero genpages, the user is told there are no pages to edit and the flow stops"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 1c: Selection is restated to the user before proceeding to download"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 3: config.json is read; since dataSources contains 'contact', RuntimeTypes.ts is generated"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 4: edit-planner reads page.tsx, config.json, and prompt.txt from the <page-id>/ folder"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 5: Orchestrator reads genpage-edit-plan.md, rules.md, RuntimeTypes.ts, and page.tsx"
+ },
+ {
+ "eval": 3,
+ "status": "deferred",
+ "text": "Edit Phase 5: Search implementation uses Fluent UI V9 SearchBox or Input; sort uses column header handlers"
+ },
+ {
+ "eval": 3,
+ "status": "manual",
+ "text": "Edit Phase 5: Existing functionality is preserved per the edit plan's Preservation Constraints"
+ },
+ {
+ "eval": 4,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): pac model list-tables --search 'incident,contact' is run; both entities confirmed as existing"
+ },
+ {
+ "eval": 4,
+ "status": "deferred",
+ "text": "Phase 2: Entity-builder is SKIPPED"
+ },
+ {
+ "eval": 4,
+ "status": "deferred",
+ "text": "Phase 4: pac model genpage generate-types --data-sources 'incident,contact' is run"
+ },
+ {
+ "eval": 4,
+ "status": "deferred",
+ "text": "Phase 5 (Page Builder): Wizard sample (2-wizard-multi-step.tsx) is read"
+ },
+ {
+ "eval": 4,
+ "status": "manual",
+ "text": "Phase 5 (Page Builder): Generated code includes step state management (current step tracking) and Next/Back navigation"
+ },
+ {
+ "eval": 4,
+ "status": "manual",
+ "text": "Phase 5 (Page Builder): Step 3 (review) shows a summary of entered data before submission"
+ },
+ {
+ "eval": 4,
+ "status": "deferred",
+ "text": "Phase 6: Upload includes --data-sources 'incident,contact'"
+ },
+ {
+ "eval": 5,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): task entity confirmed as existing; plan describes kanban with 3 columns mapped to task statecode/statuscode values"
+ },
+ {
+ "eval": 5,
+ "status": "deferred",
+ "text": "Phase 4: RuntimeTypes.ts is read — status field enum values are identified for column mapping"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): pac model list-tables --search confirms cr_candidate and cr_jobrequisition do NOT exist (exact logical-name match, not fuzzy)"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan includes entity definitions with columns, types, and a lookup relationship (cr_candidate → cr_jobrequisition)"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Because entities will be created, the planner asks the solution selection question via AskUserQuestion and records the choice in ## Environment as 'Solution: <uniqueName>' and 'Publisher Prefix: <prefix>'"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Reads Solution + Publisher Prefix from the plan's ## Environment"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): cr_jobrequisition (independent) is provisioned before cr_candidate (has lookup) to satisfy dependency ordering"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): provision-entities.js handles entity creation and column definitions atomically with internal propagation management"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Lookup relationship (cr_candidate → cr_jobrequisition) is provisioned via input JSON; provision-entities.js handles propagation internally"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): User is asked about sample data via AskUserQuestion"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js input JSON; parent references use $parent/match convention for dependency resolution"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Actual logical names are reported back (may be normalized by Dataverse); a transaction log at <working-dir>/genpage-entity-creation-log.md captures each successful operation"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 4: pac model genpage generate-types is run with the created entity names"
+ },
+ {
+ "eval": 7,
+ "status": "deferred",
+ "text": "Phase 6: Upload includes --data-sources with both created entity names"
+ },
+ {
+ "eval": 8,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): pac model list returns zero apps"
+ },
+ {
+ "eval": 8,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): User is asked via AskUserQuestion whether to create a new app or cancel"
+ },
+ {
+ "eval": 8,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan records 'create new app' decision"
+ },
+ {
+ "eval": 8,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Because a new app will be created, the planner asks the solution selection question and records the choice in ## Environment"
+ },
+ {
+ "eval": 8,
+ "status": "deferred",
+ "text": "Phase 3: The new app-id returned from pac model create is stored for Phase 6"
+ },
+ {
+ "eval": 8,
+ "status": "deferred",
+ "text": "Phase 6: Upload uses the newly created app-id"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): cr_project and cr_milestone confirmed as NOT existing"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan includes a lookup relationship (cr_milestone → cr_project)"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Solution selection question is asked because new entities will be created"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): cr_project and cr_milestone entities are provisioned with lookup relationship (cr_milestone → cr_project) via provision-entities.js; dependency ordering is handled automatically"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Sample data is created because the user explicitly requested it in the prompt"
+ },
+ {
+ "eval": 9,
+ "status": "manual",
+ "text": "Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js; realistic values (not lorem ipsum)"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Sample records respect relationships (milestones reference projects via $parent/match convention)"
+ },
+ {
+ "eval": 9,
+ "status": "deferred",
+ "text": "Phase 6: Deployment includes --data-sources with both entity names"
+ },
+ {
+ "eval": 10,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): cr_widget is identified as NOT existing (exact logical-name match, not fuzzy)"
+ },
+ {
+ "eval": 10,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan records cr_widget under Entity Creation Required"
+ },
+ {
+ "eval": 10,
+ "status": "deferred",
+ "text": "Phase 2a: Orchestrator runs scripts/check-auth.js BEFORE invoking entity-builder; parses the returned JSON"
+ },
+ {
+ "eval": 10,
+ "status": "deferred",
+ "text": "Phase 2a: If blocker:'whoami_403', orchestrator surfaces the message including the specific `az login --username <pacUser>` command and halts"
+ },
+ {
+ "eval": 10,
+ "status": "deferred",
+ "text": "Phase 2a: If ok:true but identitiesMatch:false, orchestrator proceeds but surfaces a one-line warning"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan includes 3 pages in the Pages table with distinct file names and purposes"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Per-Page Specifications section has an entry for each of the 3 pages"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 5a: Orchestrator validates the plan — at least one page, unique filenames, each page has a matching Per-Page Specifications subsection"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 4: pac model genpage generate-types is run ONCE with --data-sources 'contact,appointment'; a single RuntimeTypes.ts is generated"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 5c: Each builder receives a distinct target filename — no two builders target the same file"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 5c: Each builder reads the same genpage-plan.md but extracts only its own page specification"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 5c: Each builder reads the same RuntimeTypes.ts for column verification"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 5c: Cross-page navigation (e.g., candidate list → candidate detail) uses quoted `\"PAGEREF_<filename>\"` placeholders, never invented GUIDs"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 6: All 3 pages are deployed via separate pac model genpage upload commands, each with the correct --code-file"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 6.5: If any .tsx contains PAGEREF_ tokens, orchestrator builds a filename→page-id map sorted by length desc, replaces quoted `\"PAGEREF_<name>\"` tokens with the matching GUID (word-boundary safe), and re-uploads only affected files with the full update flag set"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 6.5: Re-upload uses a DELTA --prompt (e.g. 'Resolve cross-page navigation placeholders to real page GUIDs') — NOT a copy of the original page description from Phase 6"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 6.5: Unresolved PAGEREF tokens (typos, missing siblings) cause an explicit error to the user — never silently shipped"
+ },
+ {
+ "eval": 11,
+ "status": "deferred",
+ "text": "Phase 8: Summary table lists all 3 pages with their files, entities, and deployment status"
+ },
+ {
+ "eval": 12,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Initial plan is presented via EnterPlanMode"
+ },
+ {
+ "eval": 12,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): User requests a revision (ExitPlanMode with changes-requested response)"
+ },
+ {
+ "eval": 12,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Planner revises the plan based on user feedback and re-enters plan mode"
+ },
+ {
+ "eval": 12,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Revised plan reflects the user's requested changes (search box added)"
+ },
+ {
+ "eval": 12,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): User approves the revised plan on the second presentation"
+ },
+ {
+ "eval": 12,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): genpage-plan.md reflects the approved (revised) version, not the initial version"
+ },
+ {
+ "eval": 12,
+ "status": "manual",
+ "text": "Phase 5 (Page Builder): Generated code implements the revised plan (includes BOTH filter toolbar AND search box)"
+ },
+ {
+ "eval": 13,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English"
+ },
+ {
+ "eval": 13,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan includes a Localization section listing detected languages"
+ },
+ {
+ "eval": 13,
+ "status": "deferred",
+ "text": "Phase 5 (Page Builder): Generated .tsx fetches usersettings via dataApi.retrieveRow and uses formatDate/formatNumber/formatCurrency helpers"
+ },
+ {
+ "eval": 13,
+ "status": "deferred",
+ "text": "Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats"
+ },
+ {
+ "eval": 14,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan initially contains a Pages table with 2 pages"
+ },
+ {
+ "eval": 14,
+ "status": "deferred",
+ "text": "Phase 5a: Orchestrator reads the Pages table and detects duplicate filenames"
+ },
+ {
+ "eval": 14,
+ "status": "deferred",
+ "text": "Phase 5a: Orchestrator rewrites genpage-plan.md with unique filenames (e.g., account-list.tsx, account-edit.tsx) before dispatching builders"
+ },
+ {
+ "eval": 14,
+ "status": "deferred",
+ "text": "Phase 5b: Two page-builders are invoked in parallel with distinct target filenames"
+ },
+ {
+ "eval": 14,
+ "status": "deferred",
+ "text": "Phase 5b: No builder overwrites another builder's output (both .tsx files exist after Phase 5)"
+ },
+ {
+ "eval": 14,
+ "status": "deferred",
+ "text": "Phase 6: Both pages are deployed with their distinct filenames"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): cr_ticket is identified as NOT existing"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan includes choice column definitions for priority and status under Choice Columns, with numeric option values starting at 100000000"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Plan includes a datetime column for due date"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Solution selection question is asked (because new entity will be created) and recorded in ## Environment"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 2a: scripts/check-auth.js returns ok:true before entity-builder is invoked"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; picklist options include {value,label} pairs"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Priority picklist has 4 options starting at 100000000 (Low=100000000, Medium=100000001, High=100000002, Critical=100000003)"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Status picklist has 4 options starting at 100000000"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 2b (Entity Builder): Transaction log (genpage-entity-creation-log.md) records each create with its returned metadataId"
+ },
+ {
+ "eval": 15,
+ "status": "deferred",
+ "text": "Phase 4: pac model genpage generate-types picks up the enum registrations"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): genpage-plan.md is written and conforms to references/plan-schema.md"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): genpage-plan.md contains ALL required sections with exact headings: # Genpage Plan, ## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): ## Pages table has at least one row with columns Page, File, Purpose, Entities"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): ## Per-Page Specifications has one ### <Page Name> subsection for each row in ## Pages"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): File names in ## Pages are unique"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): Because the account entity exists, ## Entity Creation Required contains the literal string 'No entity creation required — all entities already exist.'"
+ },
+ {
+ "eval": 16,
+ "status": "deferred",
+ "text": "Phase 1 (Planner): ## Existing Entities contains the entity logical name used for RuntimeTypes generation (account)"
+ },
+ {
+ "eval": 19,
+ "status": "deferred",
+ "text": "Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names"
+ },
+ {
+ "eval": 19,
+ "status": "deferred",
+ "text": "Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)"
+ }
+ ],
+ "neverGraded": [
+ {
+ "runner": "layer-1",
+ "eval": 1,
+ "text": "Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names",
+ "reason": "column-name verification needs schema cross-check"
+ },
+ {
+ "runner": "layer-2",
+ "eval": null,
+ "text": "For Dataverse pages with fetching, separate setState calls inside async callbacks are batched into a single setData(...) call (Rule 14)",
+ "reason": "Rule 14 batched-setState requires AST analysis"
+ },
+ {
+ "runner": "layer-2",
+ "eval": 1,
+ "text": "Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names",
+ "reason": "column-name verification requires RuntimeTypes.ts fixture"
+ },
+ {
+ "runner": "layer-2",
+ "eval": 4,
+ "text": "Phase 5 (Page Builder): All form fields have aria-labels or aria-labelledby for accessibility",
+ "reason": "aria-label coverage requires AST analysis"
+ },
+ {
+ "runner": "layer-2",
+ "eval": 5,
+ "text": "Phase 5 (Page Builder): All components and utilities are separate top-level functions (no nested function definitions)",
+ "reason": "nested function detection requires AST analysis"
+ },
+ {
+ "runner": "layer-2",
+ "eval": 7,
+ "text": "Phase 5 (Page Builder): Generated code uses ONLY verified column names from RuntimeTypes.ts",
+ "reason": "column-name verification requires RuntimeTypes.ts fixture"
+ },
+ {
+ "runner": "layer-1",
+ "eval": 10,
+ "text": "Phase 2a: If the script returns blocker:'az_not_logged_in', orchestrator surfaces the message ('Run `az login`...') to the user and halts (entity-builder is NOT invoked)",
+ "reason": "az_not_logged_in blocker not in scenario"
+ },
+ {
+ "runner": "layer-1",
+ "eval": 10,
+ "text": "Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true",
+ "reason": "entity-builder not invoked"
+ },
+ {
+ "runner": "layer-2",
+ "eval": 13,
+ "text": "Phase 5 (Page Builder): All user-visible text goes through a translate() helper — no hardcoded display strings in JSX",
+ "reason": "translate() coverage requires AST analysis"
+ },
+ {
+ "runner": "layer-2",
+ "eval": 15,
+ "text": "Phase 5 (Page Builder): Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)",
+ "reason": "choice enum verification requires RuntimeTypes.ts fixture"
+ }
+ ]
+ },
+ "appBuilder": {
+ "neverGraded": []
+ }
+}
diff --git a/evals/model-apps/tests/eval-coverage-contract.test.js b/evals/model-apps/tests/eval-coverage-contract.test.js
new file mode 100644
index 000000000..0fab1da31
--- /dev/null
+++ b/evals/model-apps/tests/eval-coverage-contract.test.js
@@ -0,0 +1,463 @@
+'use strict';
+
+// Cross-runner eval coverage contract.
+//
+// Every eval runner reports an assertion it has no check for as SKIP, and a SKIP never fails a run.
+// So a new expectation in evals.json, a prompt nobody captured, or a check that skips on every
+// fixture all leave CI green while verifying nothing. This contract turns each of those into an
+// explicit, committed decision: eval-coverage-baseline.json records today's gaps, and every list in
+// it is a ratchet. A new gap fails here until it is closed or recorded; a closed gap (a prompt now
+// captured, an expectation now checked, a check that now grades) fails until its entry is removed.
+//
+// It also pins what the guides state (prompt, fixture and tier counts, the prompts with no fixture,
+// the app-builder fixture table) to the registries, and the entity-log file name the genpage loader
+// reads to the one the /genpage skill writes.
+//
+// It grades through the runners' own exports (gradeFixture, getExpectationCheck and the routing
+// predicates), so it sees exactly what the runners report rather than a copy of their routing.
+//
+// Each rule is a pure function returning a list of problems; the last tests feed each one a broken
+// input to prove it can fail.
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const EVALS_ROOT = path.join(__dirname, '..');
+const REPO_ROOT = path.join(EVALS_ROOT, '..', '..');
+const GENPAGE = path.join(EVALS_ROOT, 'genpage');
+const APP_BUILDER = path.join(EVALS_ROOT, 'app-builder');
+const PLUGIN = path.join(REPO_ROOT, 'plugins', 'model-apps');
+
+const layer1 = require('../genpage/run-layer-1.js');
+const layer2 = require('../genpage/run-layer-2.js');
+const appBuilder = require('../app-builder/run-app-builder.js');
+const { WORKFLOW_ASSERTIONS } = require('../genpage/lib/assertions-layer-1.js');
+const { ASSERTIONS: CODE_ASSERTIONS } = require('../genpage/lib/assertions-layer-2.js');
+const { ASSERTIONS: STAGE_ASSERTIONS } = require('../app-builder/lib/assertions.js');
+const genpageLoader = require('../genpage/lib/fixture-loader.js');
+const appBuilderLoader = require('../app-builder/lib/fixture-loader.js');
+
+const readJson = (file) => JSON.parse(fs.readFileSync(file, 'utf8'));
+const readText = (file) => fs.readFileSync(file, 'utf8');
+
+const genpageData = readJson(path.join(GENPAGE, 'evals.json'));
+const appBuilderData = readJson(path.join(APP_BUILDER, 'evals.json'));
+const baseline = readJson(path.join(__dirname, 'eval-coverage-baseline.json'));
+const genpageFixtures = genpageLoader.loadFixtures(path.join(GENPAGE, 'fixtures'));
+const appBuilderFixtures = appBuilderLoader.loadFixtures(path.join(APP_BUILDER, 'fixtures'));
+
+const STATUSES = new Set(['deferred', 'manual']);
+const pairKey = (...parts) => parts.map((p) => (p === null ? '' : String(p))).join('\u0000');
+const hasGenpageCheck = (text) => Boolean(layer1.getExpectationCheck(text) || layer2.getExpectationCheck(text));
+const sortedNumbers = (values) => [...values].sort((a, b) => a - b);
+const report = (problems) => `\n - ${problems.join('\n - ')}`;
+
+// ---------------------------------------------------------------------------------------------
+// Rules
+// ---------------------------------------------------------------------------------------------
+
+// Every registered prompt has a fixture or a recorded reason why not; every fixture has a prompt.
+function uncapturedProblems({ evals, fixtureIds, uncaptured }) {
+ const problems = [];
+ const evalIds = new Set(evals.map((e) => e.id));
+ for (const id of fixtureIds) {
+ if (!evalIds.has(id)) problems.push(`a fixture is filed under eval ${id}, which evals.json does not define`);
+ }
+ const listed = new Set();
+ for (const entry of uncaptured) {
+ if (listed.has(entry.eval)) problems.push(`uncaptured lists eval ${entry.eval} twice`);
+ listed.add(entry.eval);
+ if (!evalIds.has(entry.eval)) problems.push(`uncaptured lists eval ${entry.eval}, which evals.json no longer defines — remove it`);
+ else if (fixtureIds.has(entry.eval)) problems.push(`eval ${entry.eval} now has a fixture — remove it from uncaptured`);
+ if (typeof entry.reason !== 'string' || !entry.reason.trim()) problems.push(`uncaptured eval ${entry.eval} needs a reason`);
+ }
+ for (const id of evalIds) {
+ if (!fixtureIds.has(id) && !listed.has(id)) {
+ problems.push(`eval ${id} has no fixture, so no runner grades it — capture one, or list it in uncaptured with a reason`);
+ }
+ }
+ return problems;
+}
+
+// A per-eval expectation neither runner routes is dropped without even a SKIP line.
+function unroutedProblems(evals, { isPhaseExpectation, isPhase5Expectation }) {
+ return evals.flatMap((ev) => ev.expectations
+ .filter((text) => !isPhaseExpectation(text) && !isPhase5Expectation(text))
+ .map((text) => `eval ${ev.id}: neither runner routes "${text}", so it is dropped without even a SKIP — start it with its "Phase N" or "Edit Phase N"`));
+}
+
+// A common assertion with no check is a SKIP on every fixture of the corpus.
+function unregisteredCommonProblems(data, { workflow, code }) {
+ return [
+ ...data.common_workflow_assertions.filter((text) => !workflow.has(text))
+ .map((text) => `common workflow assertion has no check in WORKFLOW_ASSERTIONS: "${text}"`),
+ ...data.common_code_assertions.filter((text) => !code.has(text))
+ .map((text) => `common code assertion has no check in ASSERTIONS: "${text}"`),
+ ];
+}
+
+// Every per-eval expectation is checked, or recorded as deferred or manual.
+function unscoredProblems({ evals, hasCheck, unscored }) {
+ const problems = [];
+ const expectations = new Map();
+ for (const ev of evals) for (const text of ev.expectations) expectations.set(pairKey(ev.id, text), { id: ev.id, text });
+ const listed = new Set();
+ for (const entry of unscored) {
+ const key = pairKey(entry.eval, entry.text);
+ const label = `eval ${entry.eval} "${entry.text}"`;
+ if (listed.has(key)) problems.push(`unscored lists ${label} twice`);
+ listed.add(key);
+ if (!STATUSES.has(entry.status)) problems.push(`unscored ${label}: status must be "deferred" or "manual", got ${JSON.stringify(entry.status)}`);
+ if (!expectations.has(key)) problems.push(`unscored ${label} is no longer in evals.json — remove it`);
+ else if (hasCheck(entry.text)) problems.push(`${label} now has a check — remove it from unscored`);
+ }
+ for (const [key, { id, text }] of expectations) {
+ if (!hasCheck(text) && !listed.has(key)) {
+ problems.push(`eval ${id}: no check is registered for "${text}", so it only ever reports SKIP — register one, or list it in unscored as deferred or manual`);
+ }
+ }
+ return problems;
+}
+
+// Every registered check grades at least one fixture, or is recorded with the reason it cannot yet.
+// `observed` maps pairKey(runner, eval|null, text) to { runner, eval, text, statuses, reasons }.
+function neverGradedProblems({ observed, neverGraded }) {
+ const problems = [];
+ const onlySkips = (seen) => seen.statuses.size === 1 && seen.statuses.has('skip');
+ const describe = (e) => `${e.runner} ${e.eval === null ? 'common assertion' : `eval ${e.eval}`} "${e.text}"`;
+ const listed = new Set();
+ for (const entry of neverGraded) {
+ const key = pairKey(entry.runner, entry.eval, entry.text);
+ if (listed.has(key)) problems.push(`neverGraded lists ${describe(entry)} twice`);
+ listed.add(key);
+ if (typeof entry.reason !== 'string' || !entry.reason.trim()) problems.push(`neverGraded ${describe(entry)} needs a reason`);
+ const seen = observed.get(key);
+ if (!seen) problems.push(`neverGraded ${describe(entry)} no longer runs on any fixture — remove it`);
+ else if (!onlySkips(seen)) problems.push(`${describe(entry)} now grades a fixture — remove it from neverGraded`);
+ }
+ for (const [key, seen] of observed) {
+ if (onlySkips(seen) && !listed.has(key)) {
+ problems.push(`${describe(seen)} returns SKIP on every fixture it runs on (${[...seen.reasons].join('; ')}), so it verifies nothing — make it grade a fixture, or list it in neverGraded with that reason`);
+ }
+ }
+ return problems;
+}
+
+// The loader reads the entity log under the name the skill writes, and evals.json asks for that name.
+function entityLogNameProblems({ docs, loaderName, legacyName, evalTexts }) {
+ const problems = [];
+ const LOG_NAME = /[A-Za-z0-9_-]*entity-creation-log\.md/g;
+ const named = new Set(docs.flatMap(({ text }) => [...text.matchAll(LOG_NAME)].map((m) => m[0])));
+ if (named.size !== 1 || !named.has(loaderName)) {
+ problems.push(`the /genpage skill names the entity log ${JSON.stringify([...named])}, but the eval loader reads "${loaderName}"`);
+ }
+ if (legacyName === loaderName) problems.push('the legacy entity-log alias must differ from the current name');
+ for (const text of evalTexts) {
+ for (const m of text.matchAll(LOG_NAME)) {
+ if (m[0] !== loaderName) problems.push(`evals.json asks for "${m[0]}" instead of "${loaderName}": "${text}"`);
+ }
+ }
+ return problems;
+}
+
+function parseIdList(text) {
+ return text.split(',').map((s) => s.trim()).filter(Boolean).flatMap((part) => {
+ const range = /^(\d+)\s*[–-]\s*(\d+)$/.exec(part);
+ if (!range) return [Number(part)];
+ const out = [];
+ for (let n = Number(range[1]); n <= Number(range[2]); n += 1) out.push(n);
+ return out;
+ });
+}
+
+// What the genpage corpus actually holds, computed from evals.json and the fixture loader.
+function genpageCorpusFacts(data, fixtures) {
+ const fixtureIds = new Set(fixtures.map((f) => f.id));
+ const tierOf = new Map(data.evals.map((e) => [e.id, e.tier]));
+ const tiers = {};
+ for (const tier of ['smoke', 'full', 'stress']) {
+ tiers[tier] = {
+ ids: sortedNumbers(data.evals.filter((e) => e.tier === tier).map((e) => e.id)),
+ fixtures: fixtures.filter((f) => tierOf.get(f.id) === tier).length,
+ };
+ }
+ return {
+ workflowCount: data.common_workflow_assertions.length,
+ codeCount: data.common_code_assertions.length,
+ promptCount: data.evals.length,
+ fixtureDirs: fixtures.length,
+ tsxFiles: fixtures.reduce((n, f) => n + f.files.length, 0),
+ representedIds: fixtureIds.size,
+ missingIds: sortedNumbers(data.evals.filter((e) => !fixtureIds.has(e.id)).map((e) => e.id)),
+ tiers,
+ };
+}
+
+// The figures genpage/EVAL_GUIDE.md states. A sentence that cannot be found is itself a problem:
+// rewording one must update this contract, never silently drop the check.
+function genpageGuideProblems(guide, facts) {
+ const problems = [];
+ const expect = (label, actual, wanted) => {
+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) problems.push(`EVAL_GUIDE.md ${label}: says ${JSON.stringify(actual)}, actual ${JSON.stringify(wanted)}`);
+ };
+ const find = (label, re) => {
+ const m = re.exec(guide);
+ if (!m) problems.push(`EVAL_GUIDE.md: could not find ${label} — update the guide or this contract`);
+ return m;
+ };
+ let m = find('the common_workflow_assertions count', /`common_workflow_assertions`:\s*\*\*(\d+)\*\*/);
+ if (m) expect('common_workflow_assertions count', Number(m[1]), facts.workflowCount);
+ m = find('the common_code_assertions count', /`common_code_assertions`:\s*\*\*(\d+)\*\*/);
+ if (m) expect('common_code_assertions count', Number(m[1]), facts.codeCount);
+ m = find('the prompt definition count', /`evals`:\s*\*\*(\d+)\*\*\s+prompt definitions/);
+ if (m) expect('prompt definition count', Number(m[1]), facts.promptCount);
+ m = find('the corpus sentence', /\*\*(\d+) fixture directories \/ (\d+) top-level TSX files\*\*,\s+representing (\d+) prompt IDs\.\s+IDs \*\*([\d,\s]+)\*\* have no fixture/);
+ if (m) {
+ expect('fixture directory count', Number(m[1]), facts.fixtureDirs);
+ expect('top-level TSX count', Number(m[2]), facts.tsxFiles);
+ expect('represented prompt IDs', Number(m[3]), facts.representedIds);
+ expect('prompt IDs with no fixture', parseIdList(m[4]), facts.missingIds);
+ }
+ for (const tier of ['smoke', 'full', 'stress']) {
+ const row = find(`the ${tier} row of the tier table`, new RegExp(`^\\|\\s*\`${tier}\`\\s*\\|\\s*(\\d+)\\s*\\|[^|\\r\\n]*\\|\\s*([^|\\r\\n]+?)\\s*\\|\\s*$`, 'm'));
+ if (row) {
+ expect(`${tier} tier count`, Number(row[1]), facts.tiers[tier].ids.length);
+ expect(`${tier} tier eval IDs`, sortedNumbers(parseIdList(row[2])), facts.tiers[tier].ids);
+ }
+ const filter = find(`the --tier ${tier} example`, new RegExp(`run-layer-1\\.js --tier ${tier}\\s+#\\s*(\\d+) stored fixtures?[^,\\r\\n]*,\\s*(\\d+) prompt definitions?`));
+ if (filter) {
+ expect(`--tier ${tier} stored fixtures`, Number(filter[1]), facts.tiers[tier].fixtures);
+ expect(`--tier ${tier} prompt definitions`, Number(filter[2]), facts.tiers[tier].ids.length);
+ }
+ }
+ return problems;
+}
+
+function genpageReadmeProblems(readme, facts) {
+ const problems = [];
+ const counts = /\*\*(\d+) fixtures, (\d+) top-level TSX files and (\d+) represented\s+prompt IDs\*\*/.exec(readme);
+ if (!counts) problems.push('fixtures/README.md: could not find the fixture count sentence — update the README or this contract');
+ else {
+ const said = counts.slice(1, 4).map(Number);
+ const actual = [facts.fixtureDirs, facts.tsxFiles, facts.representedIds];
+ if (JSON.stringify(said) !== JSON.stringify(actual)) problems.push(`fixtures/README.md counts: says ${JSON.stringify(said)}, actual ${JSON.stringify(actual)}`);
+ }
+ const missing = /Registered prompts with no fixture:\s*\*\*([\d,\s]+)\*\*/.exec(readme);
+ if (!missing) problems.push('fixtures/README.md: could not find the prompts with no fixture — update the README or this contract');
+ else if (JSON.stringify(parseIdList(missing[1])) !== JSON.stringify(facts.missingIds)) {
+ problems.push(`fixtures/README.md prompts with no fixture: says ${missing[1].trim()}, actual ${facts.missingIds.join(', ')}`);
+ }
+ return problems;
+}
+
+// Every app-builder fixture has exactly one row in the guide's fixture table, and nothing else does.
+function appBuilderGuideProblems(guide, dirNames) {
+ const rows = [...guide.matchAll(/^\|\s*(\d+)\s*\|\s*`([^`]+)`\s*\|/gm)].map((m) => m[2]);
+ const problems = [];
+ for (const dir of dirNames) {
+ const n = rows.filter((r) => r === dir).length;
+ if (n !== 1) problems.push(`app-builder EVAL_GUIDE.md fixture table lists \`${dir}\` ${n} times, expected once`);
+ }
+ for (const row of rows) if (!dirNames.includes(row)) problems.push(`app-builder EVAL_GUIDE.md fixture table lists \`${row}\`, which is not a fixture`);
+ return problems;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Observations: what the runners actually report, per (runner, eval, text)
+// ---------------------------------------------------------------------------------------------
+
+function observe(observed, runner, evalId, text, result) {
+ const key = pairKey(runner, evalId, text);
+ if (!observed.has(key)) observed.set(key, { runner, eval: evalId, text, statuses: new Set(), reasons: new Set() });
+ const seen = observed.get(key);
+ seen.statuses.add(result.status);
+ if (result.status === 'skip') seen.reasons.add(result.reason);
+}
+
+// Registered checks only: an unregistered text is unscoredProblems' or unregisteredCommonProblems' concern.
+function observeGenpage() {
+ const observed = new Map();
+ const evalById = new Map(genpageData.evals.map((e) => [e.id, e]));
+ const runners = [
+ ['layer-1', layer1, WORKFLOW_ASSERTIONS],
+ ['layer-2', layer2, CODE_ASSERTIONS],
+ ];
+ for (const fix of genpageFixtures) {
+ for (const [name, runner, common] of runners) {
+ for (const { kind, text, result } of runner.gradeFixture(fix, evalById.get(fix.id), genpageData)) {
+ if (kind === 'common' && common.has(text)) observe(observed, name, null, text, result);
+ if (kind === 'expectation' && runner.getExpectationCheck(text)) observe(observed, name, fix.id, text, result);
+ }
+ }
+ }
+ return observed;
+}
+
+async function observeAppBuilder() {
+ const observed = new Map();
+ const evalById = new Map(appBuilderData.evals.map((e) => [e.id, e]));
+ for (const fix of appBuilderFixtures) {
+ const { results } = await appBuilder.gradeFixture(fix, evalById.get(fix.id), appBuilderData);
+ for (const { kind, text, result } of results) {
+ if (kind === 'gate' || !STAGE_ASSERTIONS.has(text)) continue;
+ observe(observed, 'app-builder', kind === 'common' ? null : fix.id, text, result);
+ }
+ }
+ return observed;
+}
+
+function genpageSkillDocs() {
+ const dirs = [path.join(PLUGIN, 'skills', 'genpage'), path.join(PLUGIN, 'agents')];
+ const docs = [];
+ const walk = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (entry.name.endsWith('.md') && (!full.includes(`${path.sep}agents${path.sep}`) || entry.name.startsWith('genpage-'))) {
+ docs.push({ file: path.relative(REPO_ROOT, full), text: readText(full) });
+ }
+ }
+ };
+ for (const dir of dirs) walk(dir);
+ return docs;
+}
+
+// ---------------------------------------------------------------------------------------------
+// The contract
+// ---------------------------------------------------------------------------------------------
+
+test('every genpage prompt has a fixture or a recorded reason, and every fixture a prompt', () => {
+ const problems = uncapturedProblems({
+ evals: genpageData.evals,
+ fixtureIds: new Set(genpageFixtures.map((f) => f.id)),
+ uncaptured: baseline.genpage.uncaptured,
+ });
+ const historical = Object.keys(readJson(path.join(GENPAGE, 'fixtures', 'contracts.json')));
+ const dirs = new Set(genpageFixtures.map((f) => f.dirName));
+ for (const dir of historical) if (!dirs.has(dir)) problems.push(`fixtures/contracts.json labels "${dir}", which is not a fixture`);
+ assert.deepEqual(problems, [], report(problems));
+});
+
+test('every genpage expectation is routed, and every common assertion has a check', () => {
+ const problems = [
+ ...unroutedProblems(genpageData.evals, { isPhaseExpectation: layer1.isPhaseExpectation, isPhase5Expectation: layer2.isPhase5Expectation }),
+ ...unregisteredCommonProblems(genpageData, { workflow: WORKFLOW_ASSERTIONS, code: CODE_ASSERTIONS }),
+ ];
+ assert.deepEqual(problems, [], report(problems));
+});
+
+test('every genpage expectation is checked, or recorded as deferred or manual', () => {
+ const problems = unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: baseline.genpage.unscored });
+ assert.deepEqual(problems, [], report(problems));
+});
+
+test('every registered check grades a fixture, or is recorded with the reason it cannot yet', async () => {
+ const problems = [
+ ...neverGradedProblems({ observed: observeGenpage(), neverGraded: baseline.genpage.neverGraded }),
+ ...neverGradedProblems({ observed: await observeAppBuilder(), neverGraded: baseline.appBuilder.neverGraded }),
+ ];
+ assert.deepEqual(problems, [], report(problems));
+});
+
+test('the eval loader reads the entity log under the name the /genpage skill writes', () => {
+ const docs = genpageSkillDocs();
+ assert.ok(docs.length > 0, 'found the /genpage skill and agent docs');
+ const problems = entityLogNameProblems({
+ docs,
+ loaderName: genpageLoader.ENTITY_CREATION_LOG,
+ legacyName: genpageLoader.LEGACY_ENTITY_CREATION_LOG,
+ evalTexts: [...genpageData.common_workflow_assertions, ...genpageData.common_code_assertions, ...genpageData.evals.flatMap((e) => e.expectations)],
+ });
+ assert.deepEqual(problems, [], report(problems));
+});
+
+test('the eval guides state the corpus as it is', () => {
+ const facts = genpageCorpusFacts(genpageData, genpageFixtures);
+ const problems = [
+ ...genpageGuideProblems(readText(path.join(GENPAGE, 'EVAL_GUIDE.md')), facts),
+ ...genpageReadmeProblems(readText(path.join(GENPAGE, 'fixtures', 'README.md')), facts),
+ ...appBuilderGuideProblems(readText(path.join(APP_BUILDER, 'EVAL_GUIDE.md')), appBuilderFixtures.map((f) => f.dirName)),
+ ];
+ assert.deepEqual(problems, [], report(problems));
+});
+
+// ---------------------------------------------------------------------------------------------
+// Negative controls: each rule reports the drift it exists to catch
+// ---------------------------------------------------------------------------------------------
+
+test('negative controls: prompt, routing and registration drift is reported', () => {
+ const fixtureIds = new Set(genpageFixtures.map((f) => f.id));
+ const uncaptured = baseline.genpage.uncaptured;
+ const [first] = uncaptured;
+ assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds, uncaptured: uncaptured.slice(1) }).join('\n'), new RegExp(`eval ${first.eval} has no fixture`));
+ assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds: new Set([...fixtureIds, first.eval]), uncaptured }).join('\n'), /now has a fixture/);
+ assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds, uncaptured: [...uncaptured, { eval: 9999, reason: 'x' }] }).join('\n'), /no longer defines/);
+ assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds, uncaptured: [{ ...first, reason: ' ' }, ...uncaptured.slice(1)] }).join('\n'), /needs a reason/);
+ assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds: new Set([...fixtureIds, 9998]), uncaptured }).join('\n'), /eval 9998, which evals.json does not define/);
+
+ const evals = structuredClone(genpageData.evals);
+ evals[0].expectations.push('Verify: a requirement written without its phase');
+ assert.match(unroutedProblems(evals, { isPhaseExpectation: layer1.isPhaseExpectation, isPhase5Expectation: layer2.isPhase5Expectation }).join('\n'), /neither runner routes "Verify: a requirement/);
+
+ const data = structuredClone(genpageData);
+ data.common_workflow_assertions.push('An unregistered common workflow assertion');
+ data.common_code_assertions.push('An unregistered common code assertion');
+ const common = unregisteredCommonProblems(data, { workflow: WORKFLOW_ASSERTIONS, code: CODE_ASSERTIONS });
+ assert.equal(common.length, 2, report(common));
+});
+
+test('negative controls: expectation and grading drift is reported', () => {
+ const unscored = baseline.genpage.unscored;
+ const evals = structuredClone(genpageData.evals);
+ evals[0].expectations.push('Phase 1 (Planner): a new requirement nobody checks');
+ assert.match(unscoredProblems({ evals, hasCheck: hasGenpageCheck, unscored }).join('\n'), /no check is registered for "Phase 1 \(Planner\): a new requirement/);
+ const [first] = unscored;
+ assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: (t) => t === first.text || hasGenpageCheck(t), unscored }).join('\n'), /now has a check/);
+ assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [{ ...first, status: 'later' }, ...unscored.slice(1)] }).join('\n'), /status must be/);
+ assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [...unscored, { eval: first.eval, status: 'deferred', text: 'Phase 1: gone' }] }).join('\n'), /no longer in evals.json/);
+ assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [...unscored, first] }).join('\n'), /twice/);
+
+ const observed = observeGenpage();
+ const neverGraded = baseline.genpage.neverGraded;
+ assert.ok(neverGraded.length > 0, 'the controls below need a recorded entry');
+ const entry = neverGraded[0];
+ const key = pairKey(entry.runner, entry.eval, entry.text);
+ const graded = new Map(observed);
+ graded.set(key, { ...observed.get(key), statuses: new Set(['skip', 'pass']) });
+ assert.match(neverGradedProblems({ observed: graded, neverGraded }).join('\n'), /now grades a fixture/);
+ const gone = new Map(observed);
+ gone.delete(key);
+ assert.match(neverGradedProblems({ observed: gone, neverGraded }).join('\n'), /no longer runs on any fixture/);
+ const skipping = new Map(observed);
+ skipping.set(pairKey('layer-2', 1, 'Phase 5: a new placeholder'), { runner: 'layer-2', eval: 1, text: 'Phase 5: a new placeholder', statuses: new Set(['skip']), reasons: new Set(['needs AST analysis']) });
+ assert.match(neverGradedProblems({ observed: skipping, neverGraded }).join('\n'), /returns SKIP on every fixture it runs on \(needs AST analysis\)/);
+ assert.match(neverGradedProblems({ observed, neverGraded: [{ ...entry, reason: '' }, ...neverGraded.slice(1)] }).join('\n'), /needs a reason/);
+});
+
+test('negative controls: entity-log and guide drift is reported', () => {
+ const current = genpageLoader.ENTITY_CREATION_LOG;
+ const legacy = genpageLoader.LEGACY_ENTITY_CREATION_LOG;
+ const docs = [{ file: 'SKILL.md', text: `writes ${current}` }];
+ assert.deepEqual(entityLogNameProblems({ docs, loaderName: current, legacyName: legacy, evalTexts: [`reads ${current}`] }), []);
+ assert.match(entityLogNameProblems({ docs: [{ file: 'SKILL.md', text: 'writes renamed-entity-creation-log.md' }], loaderName: current, legacyName: legacy, evalTexts: [] }).join('\n'), /eval loader reads/);
+ assert.match(entityLogNameProblems({ docs, loaderName: current, legacyName: legacy, evalTexts: [`reads ${legacy}`] }).join('\n'), /evals.json asks for "entity-creation-log.md"/);
+ assert.match(entityLogNameProblems({ docs, loaderName: current, legacyName: current, evalTexts: [] }).join('\n'), /must differ/);
+
+ const facts = genpageCorpusFacts(genpageData, genpageFixtures);
+ const guide = readText(path.join(GENPAGE, 'EVAL_GUIDE.md'));
+ assert.match(genpageGuideProblems(guide.replace(/(`evals`:\s*\*\*)\d+/, '$1999'), facts).join('\n'), /prompt definition count: says 999/);
+ assert.match(genpageGuideProblems(guide.replace(/^\|\s*`stress`.*$/m, ''), facts).join('\n'), /could not find the stress row/);
+ assert.match(genpageGuideProblems(guide, { ...facts, missingIds: [...facts.missingIds, 999] }).join('\n'), /prompt IDs with no fixture/);
+ assert.match(genpageGuideProblems(guide, { ...facts, tiers: { ...facts.tiers, full: { ...facts.tiers.full, fixtures: facts.tiers.full.fixtures + 1 } } }).join('\n'), /--tier full stored fixtures/);
+ const readme = readText(path.join(GENPAGE, 'fixtures', 'README.md'));
+ assert.match(genpageReadmeProblems(readme, { ...facts, tsxFiles: facts.tsxFiles + 1 }).join('\n'), /counts: says/);
+ assert.match(genpageReadmeProblems(readme, { ...facts, missingIds: [] }).join('\n'), /prompts with no fixture: says/);
+
+ const appGuide = readText(path.join(APP_BUILDER, 'EVAL_GUIDE.md'));
+ const dirs = appBuilderFixtures.map((f) => f.dirName);
+ assert.match(appBuilderGuideProblems(appGuide, [...dirs, '99-unlisted']).join('\n'), /lists `99-unlisted` 0 times/);
+ assert.match(appBuilderGuideProblems(appGuide, dirs.slice(1)).join('\n'), new RegExp(`lists \`${dirs[0]}\`, which is not a fixture`));
+ assert.deepEqual(parseIdList('4, 5, 18–21, 7-8'), [4, 5, 18, 19, 20, 21, 7, 8]);
+});
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 6cc2d6845..5324a7ba1 100644
--- a/plugins/model-apps/.claude-plugin/plugin.json
+++ b/plugins/model-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.11.0",
+ "version": "2.12.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 6cc2d6845..5324a7ba1 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.11.0",
+ "version": "2.12.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index cfdf61d4e..d5d43d9c6 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -234,6 +234,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
default; `--apply` writes, `--sample-data` / `--publish` opt-in (`--publish` gates the final *bulk*
publish; edit/finalize paths — reconciling an existing form/view, form events, quick-views,
existing-app sitemap, page finalize — still publish their one artifact so the change takes effect).
+ The bulk publish is ONE `PublishXml` envelope (`publishArtifacts`) for every table and the app, and
+ with `--publish` the default-view enrichment defers its own publish to it. A build that halts before
+ it hands what is still owed to the CLI, which keeps each attempt's debt across transient retries until
+ a publish phase pays it, and settles the rest per target once no retry follows (`settleOwedPublishes`)
+ — so a halted build leaves those views live, as it did before the batching. A default-view push
+ refused by a concurrent edit fails the enrichment step, as any refused push does.
**The modern ("new look") shell is opt-in via `app.newLook`.** It is a per-app SETTING
(`NewLookAlwaysOn`, written through the SDK's `saveSettingValue` scoped to app + solution), NOT an
app-module column — `navigationtype` is Single/Multi *session* and unrelated, which is the reason
@@ -242,11 +248,13 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
a silent success.
**`app.aiDescription` (the routing description) is written only when the spec sets it** — at create,
and on an existing app when it differs from the fetched draft, riding that run's app push. The
- platform may author this text itself, so an omitted field is never written or blanked. A 412 on the
- appmodule row over an UNPUBLISHED header change (componentstate 1, proven by a draft read) halts with
+ platform may author this text itself, so an omitted field is never written or blanked. A
+ never-published app refuses the write (`APP_DRAFT_HEADER_NOT_WRITABLE`), which halts with
`app-header-unpublished` — publish, then re-run — after resetting the workspace copy, which a plain
- re-fetch would otherwise refuse to replace (`LOCAL_EDITS_WOULD_BE_LOST`). A 412 on the sitemap is a
- concurrent edit even then (the push writes the header first, so its own write left that layer). Any
+ re-fetch would otherwise refuse to replace (`LOCAL_EDITS_WOULD_BE_LOST`). An app with an UNPUBLISHED
+ header change takes it: the vendored SDK conditions the header write on the appmodule's row token, so
+ the push saves and keeps that change (live-verified). A 412 is a concurrent edit, on the appmodule
+ row as on the sitemap, and is never re-explained as "publish first". Any
other failed push that carried the change resets the copy too — except a concurrent edit
(`VERSION_CONFLICT` / a code-less 412), where the unrecorded copy is what stops a blind re-run — and
without the pages phase the change is applied only after the live-page gate, so a gate halt leaves
@@ -402,7 +410,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
**icon** web resource is referenced by the table itself, so Dataverse refuses to delete it until the table
is gone (form JS, referenced by its already-deleted form, is safe either way). Teardown also removes the
build's **generated default app icon** (`<appUnique>_icon`, created in-solution when the spec sets no
- `app.icon`) so it doesn't leak as an orphan. **An app is TWO rows** — an `appmodule` AND a `sitemaps`
+ `app.icon`) so it doesn't leak as an orphan. It keeps the **page manifest** while the generative-pages
+ step fails (a failed manifest or page read fails that step too), so a re-run still finds the pages the
+ app authored. **An app is TWO rows** — an `appmodule` AND a `sitemaps`
row, with no lookup between them and no server-side cascade; the only link is
`sitemap.sitemapnameunique === appmodule.uniquename`. Deleting only the appmodule strands the sitemap
forever and, because `sitemapnameunique` is unique-constrained, permanently **burns that unique name**:
@@ -711,7 +721,7 @@ scripts/
launch-playwright-mcp.js ← Playwright MCP server launcher (fullscreen; uses lib/detect-browser.js)
playwright-mcp-fullscreen.config.json ← Fullscreen browser config for the launcher
regenerate-verified-icons.js ← Regenerates references/verified-icons.txt from npm
- check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match (pac overlaps the az probes)
+ check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match (pac overlaps the az probes); a CLI too slow to answer is `az_timeout`/`pac_timeout`
check-version.js ← Skill-start update notice: compares the plugin clone with its origin/main (git runs in the plugin, never the user's repo)
resolve-interaction-mode.js ← Reports whether a human can answer in this run (unattended defaults)
lint-app-spec.js ← Validate + lint an App Spec without touching an environment
@@ -735,7 +745,7 @@ scripts/
run-tests.js ← one-command plugin + SDK regression runner
smoke-eval.js ← scripted live smoke eval (build → assert → teardown)
generate-page-manifest.js ← Phase 0.5: writes working-dir package.json + genpage.d.ts
- genpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line; an update must name the app the page is placed in)
+ genpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line; an update must name the app the page is placed in, and keeps the page's name, model and bindings unless given)
genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval named
check-page-files.js ← /genpage: pre-dispatch gate — the page file names of the plan's one ## Pages table are safe write targets (lib/page-file-targets.js)
genpage-worker-output.js ← /genpage: accept a parallel worker's page only if complete (default export, balanced, no elided code)
@@ -745,6 +755,7 @@ scripts/
provision-input.js ← Input validation for entity provisioning
dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401; responses decoded as UTF-8 once; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`), plus the CLI arg contract (parseArgs/validateFlags)
process-runner.js ← how every script starts az/pac/npm/npx/git: the executable is resolved to an absolute path on PATH, never the project folder, and started without a shell (a Windows batch shim runs through cmd.exe with its arguments checked)
+ cli-failure.js ← how a CLI child failed (timeout / missing / failed) and the Azure CLI budget (60 s, `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`), so a slow `az` is never reported as missing or signed out
nearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators)
supported-dependencies.js ← Single source of truth for runtime + dev deps versions
feature-flags.js ← Default-OFF feature flag probe + Custom API script backstop
@@ -754,7 +765,7 @@ scripts/
artifact-intent.js ← pure App Spec → canonical SDK intent compiler (new form topology; no SDK calls)
form-occupancy.js ← pure row occupancy (own cells + columns reserved by row-spanning cells above), shared by build and verify
form-order.js ← the Main Form Set order: which Main form a table opens with, and which forms the build orders (shared by the spec gate, build and verify)
- form-container-match.js ← how an authored tab/section is matched to a deployed one (shared by build and verify)
+ form-container-match.js ← how an authored tab/section is matched to a deployed one, and the moves that put them in the layout's order (shared by build and verify)
ai-app-settings.js ← single source of truth for the per-app AI feature contract
interaction-mode.js ← whether a human is reachable in this run (shared by both skills)
page-plan.js ← pure App Spec → plan-document projection used by write-page-plan.js
@@ -769,7 +780,7 @@ scripts/
role-privileges.js ← pure: declared persona privileges + subset comparison against a deployed role
(also the oracle for `roleGrants[]`, which is additive rather than converged)
odata.js ← OData literal escaping helpers
- genpage-cli.js ← pac model genpage upload/list/download wrapper
+ genpage-cli.js ← pac model genpage upload/list/download wrapper, plus a page's own name read from its row (pac stores `"` as `\"`; `unescapePacName`)
hydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)
verify-spec.js ← spec-vs-deployed reconciliation core
build-journal.js ← durable JSONL build journal (resume diagnostics)
@@ -962,7 +973,11 @@ elided?" rule the page gate and the Layer 2 eval share (a `FIXME` comment, a `TO
a colon, a comment opening with `...`, "omitted for brevity", or a bare `...` line; the same words
as UI copy — "Loading…", a `'TODO'` status value — are not elision). A template's `${…}` body is
code and is read by the same lexer (`lexInto`), JSX and comments included, never by a lighter
-scanner. Whether a `/` or `<` starts a regex or JSX is judged by the code before it: never by a
+scanner. It is **one pass** over the file with an explicit stack of code and template frames, so
+its time is linear in the file's length however deeply templates nest — a lexer that re-scanned
+each `${…}` body per level of nesting took over a second on a 2.5 KB page. Keep it one pass; the
+`performance:` tests and the 50,000-deep nesting test in `genpage-lexer-hardening.test.js` guard it.
+Whether a `/` or `<` starts a regex or JSX is judged by the code before it: never by a
comment's last word; a keyword read back as a property name (`counts.new / total`) or a postfix
`!` / `++` ends an operand; and a `)` ends one too, unless it closes an `if` / `for` / `while`
head, after which a statement starts. Each of those rules was once broken, and each break refused
@@ -1183,8 +1198,12 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/pow
telemetry-emitting hook or script.
- The SDK's Jest suite needs **Node 20** (its `canvas` native module is built for the Node-20 ABI).
Set `NODE20_BIN` to a Node-20 bin dir; without it the SDK suite is skipped (plugin suite still runs).
-- genpage evals: `node --test evals/model-apps/genpage/tests/*.test.js`, plus the Layer 1/2 runners
- (`node evals/model-apps/genpage/run-layer-{1,2}.js --tier smoke`). See `## Eval Suite` below.
+- Evals: `node --test evals/model-apps/tests/*.test.js evals/model-apps/app-builder/tests/*.test.js
+ evals/model-apps/genpage/tests/*.test.js` (the first directory holds the cross-runner coverage
+ contract), plus the runners (`node evals/model-apps/genpage/run-layer-{1,2}.js --tier smoke`,
+ `node evals/model-apps/app-builder/run-app-builder.js`). See `## Eval Suite` below. CI's
+ `test-model-apps-evals` job runs the eval tests AND all three runners (genpage Layer 1/2, app-builder)
+ over every committed fixture — offline, no org — so a fixture that falls out of step fails the PR.
**The vendored SDK lives in a separate repo.** The Dataverse mechanics are in
`power-platform-ux` (Azure DevOps `msazure/OneAgile`), package `packages/cds-maker-sdk`. This plugin
@@ -1347,12 +1366,17 @@ layers are automated (TAP v13 runners); Layer 3 is manual.
we evaluate, the 3 layers, tiers (smoke/full/stress), fixture types
(synthetic vs real captures), runner output, capture flow, cadence,
diagnosing failures, adding evals and assertions.
-- **Eval definitions:** `evals/model-apps/genpage/evals.json` — 18 evals
- with prompts, answers, and expectations.
+- **Eval definitions:** `evals/model-apps/genpage/evals.json` — prompts,
+ answers, and expectations.
- **Fixtures:** `evals/model-apps/genpage/fixtures/<eval-id>-<slug>/` —
one folder per captured or synthetic run. Each contains the `.tsx`,
`workflow-log.md`, `genpage-plan.md`, and (when applicable)
- `entity-creation-log.md` and `RuntimeTypes.ts`.
+ `genpage-entity-creation-log.md` (older captures: `entity-creation-log.md`)
+ and `RuntimeTypes.ts`.
+- **Coverage contract:** `evals/model-apps/tests/eval-coverage-contract.test.js`
+ fails when a prompt has no fixture, an expectation has no check, or a check
+ skips on every fixture, unless `eval-coverage-baseline.json` beside it records
+ the gap and why; it also pins the guides' counts to the registries.
Run on every PR that touches the skill, agents, rules, or evals:
@@ -1375,7 +1399,9 @@ snapshots — using the plugin's own pure primitives. No live env required.
Per-stage oracles: `author` (validate + lint), `plan` (`planFor`), `data`
(`schema-facts.js` normalized tables/columns/relationships), `ui` (view/chart/form
-intent facts), `app` (sitemap facts + nav graph), `verify` (`verifySpec` reconcile).
+intent facts), `app` (sitemap facts + nav graph), `security`, `verify` (`verifySpec`
+reconcile, fail-closed), `process`, `generate-pages`, `teardown`, `round-trip` and
+`changed-only` — see the guide's stage → oracle table for what each grades.
```bash
# From repo root:
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 54feca528..3c7ad94e1 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,7 +5,80 @@ All notable changes to the **model-apps** plugin.
Entries are deliberately short: what changed and why it matters to you. The reasoning,
evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.
-## [Unreleased] — 2.11.0
+## [Unreleased] — 2.12.0
+
+Fixes from a retest of 2.11.0: an existing form converges to its layout's order and `--verify` checks
+more of it, a generative page keeps its name and model on update, and several readers refuse output
+they cannot read instead of guessing. A `--publish` build publishes in fewer requests, with the refreshed
+vendored SDK.
+
+### Added
+
+- **`pages[].model`** — the model id a generative page was generated with. A download writes it and
+ the build sends it with every upload.
+- **`POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`** — how long an Azure CLI call may take (default 60 s).
+
+### Changed
+
+- **Faster `--publish` builds.** The final publish sends every table and the app in one request,
+ and the enriched default views wait for it instead of publishing each table on the way: on a
+ three-table app, 8 publishes became 3 and the build took 152 s instead of 172 s. A build that stops
+ before its end still publishes the default views it had enriched, once no automatic retry follows.
+ A failed publish of them is now a warning naming the re-run, like any other, rather than a stop
+ before the forms are built; a default view someone edits while the build writes it now stops the
+ build, as any concurrent edit does, instead of being skipped.
+- **The vendored SDK is refreshed.** A build that changes an app's routing description no longer
+ stops with `app-header-unpublished` when the app holds an unpublished change to its name or
+ descriptions: it saves alongside that change. Only a never-published app must be published first,
+ and a concurrent edit is reported as one. On an org whose base language is not English, a new app
+ gets its System Administrator role, and the inactive default view is enriched too.
+
+### Fixed
+
+- **A field moved into a narrower section fits it.** Moved without a `colspan`, a two-column field
+ kept its width in a one-column section, and the build wrote a layout `--verify` then failed. It
+ keeps its width only where it fits, and is narrowed — and reported — where it does not.
+- **Tabs and sections are put in the layout's order** on an existing form, with the fewest moves. A
+ build used to create and move them but never reorder them, and a new tab placed between existing
+ ones took over the next one, which then came back as a duplicate.
+- **`--verify` checks more of a form**: tab expanded and visible state, form-column widths, section
+ visibility and label display, fields' `hidden` and `readOnly` (an auto layout's too, failing a
+ flagged field the form no longer carries), and the order of tabs and sections. A form that differed
+ in any of these passed. It also reads a field's state, span and section from the field itself, never
+ from a quick view bound to the same lookup. Lint warns when an auto layout flags a field it does not
+ place, since the build never applies that flag.
+- **A generative page keeps its name and model on update.** An update without a name renamed the
+ page to its navigation title, and one without `--model` stored the model empty. `genpage-upload`
+ now reads both from the deployed page and sends them again (a name a `pac.cmd` shim cannot receive
+ is left out, with a warning), and a download → rebuild keeps the model. A name with a straight
+ double quote is refused — pac stores each one as `\"`, in the navigation title too — and
+ `/app-builder` lints one in `pages[].name`. A download no longer copies pac's backslashes into
+ `pages[].name`, where each rebuild added another.
+- **Generative-page navigation parsing** is linear — a 2.5 KB page of nested template literals took
+ 1.4 s, and a long comment inside one navigation call seconds more — and no longer rewrites a name
+ that only resembles a navigation call, misses an optional call (`?.`), misreads a property override
+ or a Unicode line terminator, or reads a word in a comment as a property.
+- **Adding pages to a solution checks every id first.** A malformed page id was refused only after
+ the app had been added; nothing is added now until the app and page ids are valid, and a repeated
+ id is sent once.
+- **Connector discovery refuses output it cannot read** — a warning, a changed format — instead of
+ reporting no connections, rejects malformed identifiers, and no longer reads a table's dashed
+ separator as a connection. The connector agent never creates a connection after a failed discovery.
+- **A slow Azure CLI or PAC is reported as slow.** A token request that ran out of time was reported
+ as `az` missing or signed out; it is now `az_timeout`, with the time it was given and a longer budget
+ to try — never more than the 15-minute maximum. A `pac org who` slower than its fixed 60 s is
+ `pac_timeout`, to retry, not `pac_not_logged_in`.
+- **Lint no longer warns about a view, chart or form name used on two tables** — only a repeat on
+ one table collides.
+- **A re-run of a failed teardown finds the generative pages it left.** When teardown could not delete
+ a page, or could not read which pages the app authored, it still deleted the page manifest — the
+ only record of them — so a re-run reported success and the pages stayed behind. The manifest and the
+ solution are now kept until the pages step succeeds.
+- **`capture-fixture.js` no longer passes an eval it could not verify.** A runner that exited with an
+ error but no failing assertion, or reported no assertions at all, was summarized as clean; each is
+ now listed as a failure, with the runner's exit code.
+
+## [2.11.0]
AI features are written with each setting's own values, rebuilding an existing app no longer
rewrites its navigation, a table opens with the form the spec makes its default, and the vendored
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index 9b8a7af79..7ce0791a5 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -29,6 +29,11 @@ claude --plugin-dir /path/to/power-platform-skills/plugins/model-apps
After installing `az`, run `az login` with the same identity as your active `pac auth list` profile. Without `az`, the `/genpage` skill still works for pages over existing entities or mock data — it only fails when entity creation is needed.
+Each Azure CLI call (a token, `az account show`) may take up to **60 seconds** — a busy machine can
+take most of that just to start `az`. A call that runs out of time is reported as a timeout (the
+pre-flight's `az_timeout`), never as a missing or signed-out CLI. To allow longer, set
+`POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS` in milliseconds (1000–900000), for example `120000`.
+
## Feature flags (experimental & in-progress)
Some capabilities ship **OFF by default** while their cross-repo dependencies roll
diff --git a/plugins/model-apps/agents/genpage-connector-builder.md b/plugins/model-apps/agents/genpage-connector-builder.md
index a079a3b92..7dfebfee6 100644
--- a/plugins/model-apps/agents/genpage-connector-builder.md
+++ b/plugins/model-apps/agents/genpage-connector-builder.md
@@ -120,6 +120,11 @@ is actually bound to that connection (its `connectionId` matches) — prefer tho
Offer ready-to-bind choices first in a `needs_input` request, showing the
connectionreference logical name, connector id, and connection display name.
+If the script fails (`ok: false`), discovery did not happen — it refuses PAC output
+it cannot read rather than report it as "no connections". Do **not** treat that as
+"no suitable connection exists" below, and never create a connection on it: return
+`needs_input` with the script's error.
+
After selecting any existing connection — before branching into tabular versus
REST/action discovery — derive `connectorName` from the final path segment of
its full `connectorId`. PAC metadata commands use `connectorName`; binding files
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index c129e3271..196844771 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -257,7 +257,7 @@ apart deliberately.
test here and by a `@jest-environment node` regression upstream.
### Edit flow (download → edit → rebuild) — ✅ verified live
-- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages (code, prompt and data sources; a page's connector and Custom API bindings stay on the deployed page but are not carried in the spec, so they survive a same-environment rebuild only), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.
+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages (code, prompt, data sources and model; a page's connector and Custom API bindings stay on the deployed page but are not carried in the spec, so they survive a same-environment rebuild only), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.
- Live regression on the edit path found + fixed **4 bugs**, then re-verified clean.
- `verify-model-app.js` — read-only reconcile of spec vs deployed (exits non-zero on anything missing). Sitemap checks are **element-scoped**: an area/subarea icon is matched on its own `<Area>`/`<SubArea>` element, and a **dashboard subarea** is verified by resolving the dashboard id (systemform type 0 — by a downloaded spec's pinned `dashboardId` first, else by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass — and that entry must carry the dashboard launcher `Url`, without which the app shows a placeholder icon for it. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).
diff --git a/plugins/model-apps/hooks/run-skill-posttool-validation.js b/plugins/model-apps/hooks/run-skill-posttool-validation.js
index dbcb59190..9dcd4487a 100644
--- a/plugins/model-apps/hooks/run-skill-posttool-validation.js
+++ b/plugins/model-apps/hooks/run-skill-posttool-validation.js
@@ -68,7 +68,11 @@ readUtf8Stream(process.stdin).then((inputData) => {
if (result.stderr) process.stderr.write(result.stderr);
debug(`[model-apps hook] Validator exited with code ${result.status ?? 0}\n`);
- process.exit(result.status ?? 0);
+ // Set the code rather than calling process.exit(): a write to a pipe is asynchronous on
+ // macOS, and exiting at once drops whatever the 64 KiB pipe buffer has not taken yet, so a
+ // long validator report arrived cut off. Nothing else is pending, so the process ends as
+ // soon as both streams have flushed.
+ process.exitCode = result.status ?? 0;
} catch (err) {
// Never block on a hook-side bug — the skill already ran.
process.stderr.write(`[model-apps hook] Unexpected error: ${err.message}\n`);
diff --git a/plugins/model-apps/hooks/validate-icon-imports.js b/plugins/model-apps/hooks/validate-icon-imports.js
index 1c3c1b990..85062ab7b 100644
--- a/plugins/model-apps/hooks/validate-icon-imports.js
+++ b/plugins/model-apps/hooks/validate-icon-imports.js
@@ -30,7 +30,7 @@
const fs = require('fs');
const path = require('path');
-const { blankNonCodePreservingTemplateExpressions, commentRanges } = require('../scripts/lib/source-literals.js');
+const { blankNonCodePreservingTemplateExpressions, commentRanges, isLineTerminator } = require('../scripts/lib/source-literals.js');
const PLUGIN_ROOT = path.resolve(__dirname, '..');
const VERIFIED_ICONS_PATH = path.join(PLUGIN_ROOT, 'references', 'verified-icons.txt');
@@ -109,7 +109,7 @@ function loadVerifiedIcons() {
try {
const raw = fs.readFileSync(VERIFIED_ICONS_PATH, 'utf8');
const set = new Set();
- for (const line of raw.split(/\r?\n/)) {
+ for (const line of raw.split(/[\r\n\u2028\u2029]+/)) {
const name = line.trim();
if (!name || name.startsWith('#')) continue; // skip header/comment/blank lines
set.add(name);
@@ -180,7 +180,7 @@ function extractIconImports(content) {
function stripCommentsForImports(content) {
return content
.replace(/\/\*[\s\S]*?\*\//g, ' ')
- .replace(/(?<!:)\/\/[^\n]*/g, '');
+ .replace(/(?<!:)\/\/[^\r\n\u2028\u2029]*/g, '');
}
// `content` with each comment the lexer finds turned into spaces, newlines kept, so every offset is
@@ -188,7 +188,7 @@ function stripCommentsForImports(content) {
function blankComments(content) {
const out = content.split('');
for (const { start, end } of commentRanges(content)) {
- for (let k = start; k < end; k += 1) if (out[k] !== '\n') out[k] = ' ';
+ for (let k = start; k < end; k += 1) if (!isLineTerminator(out[k])) out[k] = ' ';
}
return out.join('');
}
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index f85171018..4ab00a5d1 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -752,7 +752,7 @@ at the same order, as every new form is — were served with the `isdefault` for
| section | `label`, `showLabel`, `visible` | Section heading, whether it renders, whether the section shows. |
| section | `columns` | `1`–`4` grid columns. |
| section | `fields[]` | Column logical names, or `{ "name": …, … }` entries. |
-| field entry | `colspan`, `rowspan` | Whole numbers ≥ 1. A cell wider than its section is clamped to it — the clamp reaches the deployed cell, not just the row packing. `rowspan` is valid only on the **last** field of a section (see below). |
+| field entry | `colspan`, `rowspan` | Whole numbers ≥ 1. A cell wider than its section is clamped to it — the clamp reaches the deployed cell, not just the row packing. A field **moved** into another section without a declared `colspan` keeps its deployed width if it fits there, and is narrowed to that section's width (and reported) if not — declare `colspan` to choose. `rowspan` is valid only on the **last** field of a section (see below). |
A tab declares **either** `sections` **or** `columns`, never both. `columns` on a **tab** is the list
of form-columns; `columns` on a **section** is its 1–4 grid width — a number on a tab is rejected
@@ -814,20 +814,24 @@ recorded in the build result (`skipped.layout`), and `--verify` reports the dive
explicit layout.
**Editing an existing form.** An explicit layout is converged onto the deployed form rather than
-flattened into its first section: missing tabs, form-columns and sections are **created**, a
-section's `columns`/`label`/`showLabel`/`visible` are **updated in place**, a named section that
-sits in another tab or form-column is **moved** to where the layout places it, and a field sitting
-in the wrong section is **moved** (never duplicated — the cell keeps its id and any control state a
-maker edited). Containers are matched by `name`, then `label`, then position, so a form built by an
-earlier `auto` layout — or by hand in Maker — converges instead of gaining a duplicate tab. Nothing
-is renamed, because form scripts and business rules can reference a section by name.
+flattened into its first section: missing tabs, form-columns and sections are **created** where the
+layout places them, a tab's `label`/`expanded`/`visible`, a form-column's `width` and a section's
+`columns`/`label`/`showLabel`/`visible` are **updated in place**, a named section that sits in another
+tab or form-column is **moved** to where the layout places it, the tabs — and the sections of each
+form-column — are **put in the layout's order**, and a field sitting in the wrong section is **moved**
+(never duplicated — the cell keeps its id and any control state a maker edited). Containers are
+matched by `name`, then `label`, then position, so a form built by an earlier `auto` layout — or by
+hand in Maker — converges instead of gaining a duplicate tab. Nothing is renamed, because form scripts
+and business rules can reference a section by name. Every move is reported; only the layout's own
+containers are ordered — a tab or section it does not mention (a maker's own, the notes timeline)
+keeps its place among them.
Three rules keep that matching from claiming the wrong container. An index an earlier tab or section
already matched is **not reused**, because an unlabeled container compiles to a default label
(`General` for a tab, `Details` for a section) and several of them would otherwise all match the
-first one. A section whose name another section in the layout declares is matched only **by that
+first one. A tab or section whose name another one in the layout declares is matched only **by that
name**, so it can be moved to its own place instead of being taken over by a neighbour with the same
-label. And sections the **engine** owns — a sub-grid host, the notes/timeline section — are
+label or position. And sections the **engine** owns — a sub-grid host, the notes/timeline section — are
matched only by `name`: a label or a position is not evidence about what a container *is*, and
matching one positionally would relabel a sub-grid and place fields in the row holding its grid.
Their name is the engine's own, so a section **you** declare never takes one even by name: a section
@@ -855,8 +859,8 @@ remove in Maker.
⚠ **Field order.** A field the form lacks is appended to the end of its section; a field it already
has stays where it is. So reordering a section's `fields` list on an existing form changes nothing
-(`--verify` does not check order either). Position a field explicitly with `fieldOptions[x].after`,
-below.
+(`--verify` does not check field order either — it does check the order of tabs and of sections).
+Position a field explicitly with `fieldOptions[x].after`, below.
⚠ Declaring explicit `tabs` also switches **pruning** on: a field the deployed form carries and the
layout does not list is removed (never the primary field). Set `"prune": false` to restyle or
@@ -898,6 +902,12 @@ in the form designer. The corollary is that `readOnly: false` / `hidden: false`
back off — they are rejected at author time rather than accepted and ignored. To un-set one, clear it
in the designer, or drop the field and let the next build re-add it.
+**Under an `auto` layout the flags apply to the fields the layout places** — the primary column, the
+table's declared columns and its parent lookups. A `readOnly`/`hidden` on any other field (a stock
+column of an existing table, say) is never written, and lint warns about it; list that field in an
+explicit layout instead (`prune: false` keeps the rest of the form). `--verify` proves every flag the
+build writes, and fails a flagged field the deployed form no longer carries.
+
- **`prune`** *(optional, default `true`, explicit layouts only)* — an explicit `tabs` layout is
normally the complete desired state, so a rebuild removes any deployed field it does not list. Set
`prune: false` to keep those fields, which lets you restyle or reorder a **subset** of a form
@@ -1006,6 +1016,11 @@ custom control), but the spec validator emits a warning.
create (authored by different people/tools), and an unrelated edit (e.g. a form change) must still
build. The pages phase matches by `pageId`/`key`, never by name, so distinct-id same-name pages
build correctly; rename one in Maker to disambiguate the navigation.
+- **A straight double quote (`"`) in a page `name`** draws a lint warning: pac stores each one as `\"`
+ on the page's own record, and the backslashes stay there. The navigation shows the page subarea's
+ `title`, which the build writes as given. A download writes the name without pac's backslashes, so a
+ rebuild does not add more. Use typographic quotes (“ ”) or an apostrophe — pac stores those, and
+ every other character, exactly.
- **`pageInput`**: `{ "data": { … } }` — the input this page expects when navigated to.
- **Durable page manifest.** The build writes a `<app-unique-name>_pagemanifest` web resource
carrying `{ schemaVersion, pages: [{ key, name, pageId, purpose, dataSources, navigatesTo, pageInput }], design }`.
@@ -1034,13 +1049,16 @@ custom control), but the spec validator emits a warning.
highest identity authority (outranks the manifest), confirmed against EXISTENCE — so a downloaded
app (including Maker-added pages) rebuilds against the correct existing page without duplication.
- **What a page round-trip carries — and what it does not.** A download brings back each page's
- code, prompt, `dataSources` and identity. A page's **connector and Custom API bindings** and the id
- of the **model** that generated it have no App Spec field, so they are not in the spec. The build
- uploads without them, and pac leaves a page's existing bindings in place when they are omitted: a
- rebuild in the **same environment** keeps the bindings working, but that is preservation, not
- reconstruction — the same spec rebuilt in **another environment** deploys the page without them
- (bind them there with `/genpage`). The model id is stored empty whenever a rebuild re-uploads the
- page.
+ code, prompt, `dataSources`, the id of the **model** that generated it (`pages[].model`) and its
+ identity; the build re-sends the model with every upload, because pac stores whatever an upload says
+ and an upload without one stored it empty. A page's **connector and Custom API bindings** have no App
+ Spec field, so they are not in the spec. The build uploads without them, and pac leaves a page's
+ existing bindings in place when they are omitted: a rebuild in the **same environment** keeps the
+ bindings working, but that is preservation, not reconstruction — the same spec rebuilt in **another
+ environment** deploys the page without them (bind them there with `/genpage`).
+- **`model` (optional).** The model id a page was generated with, e.g. `"gpt-4.1"` — letters, digits and
+ `. _ : / @ + -`, at most 100 characters. A download writes it (an id outside that shape is left out, with
+ a warning); an authored spec may omit it, and then a rebuild of an existing page stores it empty.
- **Safety HALTs (pages phase).** The build halts on identity/safety violations rather than
proceeding with potentially wrong state:
- `pages-identity-conflict` — spec `pageId` and manifest disagree on a key, or a duplicate id is
diff --git a/plugins/model-apps/references/troubleshooting.md b/plugins/model-apps/references/troubleshooting.md
index b658d4057..054c92d7d 100644
--- a/plugins/model-apps/references/troubleshooting.md
+++ b/plugins/model-apps/references/troubleshooting.md
@@ -48,7 +48,8 @@ Both skills can create one:
- Verify app-id: run `pac model list` to get the correct GUID
- Ensure the page's display name is provided for new pages — written to a file and passed with `--name-file`, so a shell never reads it
-- A page display name with a straight double quote (`"`) is stored with a backslash before each one (`\"Q3\"`). The name reaches pac intact, and the extra backslash is added inside pac. Until pac is fixed, use typographic quotes (`“Q3”`) in page names
+- A page display name with a straight double quote (`"`) is refused before anything is uploaded: pac stores each one with a backslash before it (`\"Q3\"`), in the page and in the navigation title it writes. Use typographic quotes (`“Q3”`) or an apostrophe, which are stored exactly
+- An update result with a `warnings` entry about the page's name or model: the script could not read the deployed value — or, for a name, could not send it through a `pac.cmd` shim, which cannot receive `%` or `"` — so pac may have renamed the page to its navigation title or stored an empty model. Re-run the update with `--name-file` or `--model`
- `--prompt-file …/prompt.txt is a symbolic link or junction, not a file written in place` (or `is a hard link`,
for any input file): something other than the skill left a link at that name, and writing it may have changed
the file it points to. Check that file, delete the link, and re-run; the skill then writes a plain file there
diff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.js
index adfc36fe2..063709c40 100644
--- a/plugins/model-apps/scripts/add-page-to-solution.js
+++ b/plugins/model-apps/scripts/add-page-to-solution.js
@@ -27,6 +27,7 @@ const {
emitResult,
} = require('./lib/dataverse-auth');
const { odataLit } = require('./lib/odata');
+const { FORM_GUID_RE } = require('./lib/app-spec');
const APPMODULE_COMPONENT_TYPE = 80;
const UXAGENTPROJECT_LOGICAL_NAME = 'uxagentproject';
const CONNECTION_REFERENCE_LOGICAL_NAME = 'connectionreference';
@@ -90,15 +91,36 @@ async function main() {
const added = [];
// Parsed BEFORE the first mutation so lookup failures refuse the whole run rather
- // than leaving a half-packaged solution (app + pages added, refs missing).
- const refs = (flags['connection-refs'] || '')
+ // than leaving a half-packaged solution (app + pages added, refs missing). A repeated
+ // entry (in any letter case) is dropped: adding the same component twice is a wasted write.
+ const unique = (list) => {
+ const seen = new Set();
+ return list.filter((v) => {
+ const key = v.toLowerCase();
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ };
+ const refs = unique((flags['connection-refs'] || '')
.split(',')
.map((s) => s.trim())
- .filter(Boolean);
- const pageIds = (flags['page-ids'] || '')
+ .filter(Boolean));
+ const pageIds = unique((flags['page-ids'] || '')
.split(',')
.map((s) => s.trim())
- .filter(Boolean);
+ .filter(Boolean));
+ // Every id must be a GUID before anything is read or written. A malformed page id used to reach
+ // Dataverse only at its own AddSolutionComponent — after the app had been added — so the run failed
+ // with the solution holding the app but not its page.
+ const malformed = [
+ ...(FORM_GUID_RE.test(appId) ? [] : [`app id '${appId}'`]),
+ ...pageIds.filter((id) => !FORM_GUID_RE.test(id)).map((id) => `page id '${id}'`),
+ ];
+ if (malformed.length) {
+ emitResult(false, new Error(`Not a GUID: ${malformed.join(', ')}. Nothing was added to ${solutionUniqueName}.`));
+ return;
+ }
try {
// ObjectTypeCode for custom tables is allocated per environment. Resolve both
// types before the first AddSolutionComponent so a metadata failure leaves the
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index cd3d04cbb..538efd1b6 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -16,7 +16,7 @@ const path = require('node:path');
const { randomUUID } = require('node:crypto');
const { sha256 } = require('./lib/hash.js');
const { validateAppSpec, migrateAppSpec, normalizePageSource, normalizeLanguageCode } = require('./lib/app-spec.js');
-const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId } = require('./lib/sdk-build.js');
+const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId, settleOwedPublishes } = require('./lib/sdk-build.js');
const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');
// #455: resolves the authoring LCID over the transport hatch, BEFORE constructing the SDK that
// bakes it into the App/Form/Dashboard adapters.
@@ -573,6 +573,10 @@ async function buildModelApp(spec, opts, deps) {
// Injectable apply seam: production defaults to runSdkBuild; tests inject a stub to drive verify
// without a live SDK.
const runBuild = deps.runBuild || runSdkBuild;
+ // What failed attempts still owe for the default views they enriched (sdk-build.js, 4b), by artifact.
+ // Every attempt re-runs every phase, but a later one can halt before the enrichment an earlier one did,
+ // so each debt is kept until a publish phase pays it (`owedPaid`), and the final halt settles the rest.
+ const owedAcrossAttempts = new Map();
let r;
for (let attempt = 1; ; attempt++) {
counts.ok = counts.skip = counts.error = 0; // summary reflects the final (successful) attempt
@@ -609,6 +613,8 @@ async function buildModelApp(spec, opts, deps) {
});
break;
} catch (err) {
+ if (err && err.owedPaid) owedAcrossAttempts.clear();
+ for (const target of (err && Array.isArray(err.owedPublishes) ? err.owedPublishes : [])) owedAcrossAttempts.set(`${target[0]}:${target[1]}`, target);
if (attempt <= maxRetries && isTransientHalt(err)) {
const delay = opts.retryDelayMs != null ? opts.retryDelayMs : backoffMs(attempt);
if (journal) journal.record({ phase: err && err.phase, status: 'retry', label: `transient error (attempt ${attempt}/${maxRetries}) — retrying in ${delay}ms`, detail: String((err && err.message) || err) });
@@ -617,7 +623,13 @@ async function buildModelApp(spec, opts, deps) {
continue;
}
// A non-transient (or retries-exhausted) halt — journal where/why it stopped, then propagate.
- // Resume by re-running the same command (idempotent) or with --from <phase>.
+ // Resume by re-running the same command (idempotent): a partial range (--from and the like) is
+ // refused on --apply.
+ //
+ // First publish the default views this build's attempts had enriched and no publish phase paid: no
+ // retry follows now (see settleOwedPublishes, sdk-build.js). Best-effort, so the halt below is still
+ // what this run reports.
+ await settleOwedPublishes(deps.provisionSdk || deps.sdk, [...owedAcrossAttempts.values()], deps.warn);
if (journal) journal.close({ status: 'halt', phase: err && err.phase, code: err && err.code, recoverable: !!(err && err.recoverable), message: String((err && err.message) || err), ...counts });
throw err;
}
diff --git a/plugins/model-apps/scripts/capture-fixture.js b/plugins/model-apps/scripts/capture-fixture.js
index d88a97806..9c39c678f 100644
--- a/plugins/model-apps/scripts/capture-fixture.js
+++ b/plugins/model-apps/scripts/capture-fixture.js
@@ -228,6 +228,26 @@ function extractFailures(stdout) {
.map((l) => l.trim());
}
+// One layer's verdict for the summary. The documented review rule is "both `failures` arrays empty → the fixture is
+// good to commit", so a runner that produced NO verdict has to put something into `failures` itself. Two cases used to
+// leave it empty and read as a clean capture:
+// - the runner exited nonzero without reporting a failing assertion — a crash, or its own refusal (exit 2 when the
+// eval id matches no fixture). Its counts, if any, are not a result. Its exit code was read and then dropped.
+// - the runner exited 0 but reported no assertions, so nothing was verified.
+// The process itself still exits 0: the files were captured, and a capture of a run with real failures is still a
+// capture — the summary is how the caller judges it.
+function layerSummary(run) {
+ const counts = parseTapSummary(run.stdout);
+ const failures = extractFailures(run.stdout);
+ if (run.exitCode !== 0 && failures.length === 0) {
+ const detail = String(run.stderr || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean).slice(-3).join(' | ');
+ failures.push(`runner exited ${run.exitCode === null ? 'without an exit code' : run.exitCode} without reporting a failing assertion — its result is not verified${detail ? `: ${detail.slice(0, 300)}` : ''}`);
+ } else if (run.exitCode === 0 && counts.tests === 0) {
+ failures.push('runner reported no assertions for this eval — nothing was verified');
+ }
+ return { ...counts, exitCode: run.exitCode, failures };
+}
+
function main() {
let args;
try {
@@ -282,16 +302,8 @@ function main() {
};
if (!args.skipVerify) {
- const layer1 = runRunner(LAYER1_SCRIPT, args.eval);
- const layer2 = runRunner(LAYER2_SCRIPT, args.eval);
- summary.layer1 = {
- ...parseTapSummary(layer1.stdout),
- failures: extractFailures(layer1.stdout),
- };
- summary.layer2 = {
- ...parseTapSummary(layer2.stdout),
- failures: extractFailures(layer2.stdout),
- };
+ summary.layer1 = layerSummary(runRunner(LAYER1_SCRIPT, args.eval));
+ summary.layer2 = layerSummary(runRunner(LAYER2_SCRIPT, args.eval));
}
console.log(JSON.stringify(summary, null, 2));
diff --git a/plugins/model-apps/scripts/check-auth.js b/plugins/model-apps/scripts/check-auth.js
index e1b675fae..260c85300 100644
--- a/plugins/model-apps/scripts/check-auth.js
+++ b/plugins/model-apps/scripts/check-auth.js
@@ -14,7 +14,7 @@
// Output (stdout JSON, exit 0 even on auth failure — failures are in the fields):
// {
// "ok": true|false,
-// "blocker": null | "az_missing" | "az_not_logged_in" | "pac_not_logged_in"
+// "blocker": null | "az_missing" | "az_not_logged_in" | "az_timeout" | "pac_not_logged_in" | "pac_timeout"
// | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error",
// "message": "human-readable next step",
// "warnings": ["..."],
@@ -33,7 +33,12 @@
// Exit code 0 always (so callers can parse stdout). Use `ok` field to gate.
const { execFileAsync } = require('./lib/process-runner.js');
-const { dataverseRequest, getAuthTokenAsync, parseArgs, validateFlags } = require('./lib/dataverse-auth');
+const { dataverseRequest, getAuthTokenAsync, parseArgs, validateFlags, tokenFailureKind, tokenFailureMessage } = require('./lib/dataverse-auth');
+const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./lib/cli-failure.js');
+
+// `pac org who` cold-starts the PAC CLI's .NET runtime (~7 s measured on Windows), and longer on a busy
+// machine; a probe that runs out of time is reported as that, never as "not logged in".
+const PAC_PROBE_TIMEOUT_MS = 60000;
// Read the env URL from either `--env <url>` (the flag the build/verify/teardown scripts use) or
// the first positional arg, so a caller can copy the `--env` form here without silently passing
@@ -55,27 +60,28 @@ function parseEnvUrl(argv) {
return positional || null;
}
-// Trimmed stdout, or null on any failure. The child runs in the background so the event loop stays
-// free to drain other CLI stdout and service their timeout timers while Azure CLI and PAC cold-start.
-function runQuietAsync(cmd, args) {
+// `{ out, failure }`: the trimmed stdout, or null with the failure's kind — 'timeout' | 'missing' |
+// 'failed' (cli-failure.js). The child runs in the background so the event loop stays free to drain
+// other CLI stdout and service their timeout timers while Azure CLI and PAC cold-start.
+function runQuietAsync(cmd, args, timeoutMs) {
let child = null;
let settled = false;
const promise = new Promise((resolve) => {
try {
child = execFileAsync(cmd, args, {
encoding: 'utf8',
- timeout: 15000,
+ timeout: timeoutMs,
windowsHide: true,
}, (error, stdout) => {
settled = true;
- resolve(error ? null : String(stdout || '').trim());
+ resolve(error ? { out: null, failure: cliFailureKind(error) } : { out: String(stdout || '').trim(), failure: null });
});
// execFile always opens a stdin pipe; close it (the effect of stdio 'ignore'), so a CLI that
// checks stdin can never wait on it.
if (child && child.stdin) child.stdin.end();
- } catch {
+ } catch (e) {
settled = true;
- resolve(null);
+ resolve({ out: null, failure: cliFailureKind(e) });
}
});
return {
@@ -135,13 +141,25 @@ async function main() {
// call ~3-5 s. Run one after another (az --version, az account show, pac, then az again for the
// WhoAmI token), the preflight cost ~19 s at the start of every /genpage and /app-builder run.
// pac needs nothing from az, so it is started FIRST and runs while the az probes run.
- const pacOrgProbe = runQuietAsync('pac', ['org', 'who']);
+ const pacOrgProbe = runQuietAsync('pac', ['org', 'who'], PAC_PROBE_TIMEOUT_MS);
+ const azBudget = azTimeoutMs();
+ // A slow Azure CLI is reported as slow — neither "not installed" nor "not logged in" is true of it,
+ // and sending the user to reinstall or `az login` fixes nothing.
+ const azTimedOut = (command, partial = {}) => {
+ pacOrgProbe.cancel();
+ return emit(buildResult(Object.assign({ blocker: 'az_timeout', message: azTimeoutAdvice(command, azBudget) }, partial)));
+ };
// 1) az login. `az account show` answers "installed?" and "logged in?" together on the happy path,
- // so `az --version` runs only to tell those two failures apart.
- const azUser = await runQuietAsync('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv']).promise;
+ // so `az --version` runs only to tell those two failures apart — and not at all when the runner
+ // already found no `az` on PATH.
+ const account = await runQuietAsync('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv'], azBudget).promise;
+ const azUser = account.out;
if (!azUser) {
- if (await runQuietAsync('az', ['--version']).promise == null) {
+ if (account.failure === 'timeout') return azTimedOut('az account show');
+ const version = account.failure === 'missing' ? account : await runQuietAsync('az', ['--version'], azBudget).promise;
+ if (version.failure === 'timeout') return azTimedOut('az --version');
+ if (version.out == null) {
// This branch returns before the pac probe is awaited. Kill the child explicitly so a
// non-detached PAC process cannot outlive the preflight after its parent exits.
pacOrgProbe.cancel();
@@ -165,13 +183,20 @@ async function main() {
// Acquire the WhoAmI token while pac is still running. getAuthToken memoizes per process, so the
// dataverseRequest below reuses it instead of paying another az cold start after pac returns. A
- // failure here is not reported: WhoAmI acquires again and reports it with the right blocker.
+ // failure here is not reported: WhoAmI acquires again and reports it with the right blocker — except
+ // a TIMEOUT, which WhoAmI's own attempt would only repeat, doubling the wait before saying so.
if (envUrl) {
- try { await getAuthTokenAsync(envUrl); } catch { /* reported by WhoAmI */ }
+ let warmed = null;
+ try { warmed = await getAuthTokenAsync(envUrl); } catch { /* reported by WhoAmI */ }
+ if (!warmed && tokenFailureKind(envUrl) === 'timeout') {
+ return azTimedOut('az account get-access-token', { azUser, envUrl, warnings, message: tokenFailureMessage(envUrl, '') });
+ }
}
// 2) pac user + env URL (best-effort — pac is NOT required for the Dataverse build path)
- const pacOrg = await pacOrgProbe.promise;
+ const pacProbe = await pacOrgProbe.promise;
+ const pacOrg = pacProbe.out;
+ const pacSlow = pacProbe.failure === 'timeout';
let pacUser = null;
if (pacOrg) {
const m = pacOrg.match(/Connected as\s+([^\s\r\n]+)/i);
@@ -182,6 +207,7 @@ async function main() {
}
}
if (!pacUser) {
+ const slowPac = `\`pac org who\` did not answer within ${PAC_PROBE_TIMEOUT_MS / 1000} s — the PAC CLI can be that slow to start on a busy machine, so its login is unknown, not missing`;
if (requirePac) {
// Genpage caller (--require-pac): pac is genuinely required to upload pages, so keep the hard block.
return emit(
@@ -189,17 +215,17 @@ async function main() {
azUser,
envUrl,
warnings,
- blocker: 'pac_not_logged_in',
- message: 'PAC CLI is not logged in. Run `pac auth create --environment <url>` to authenticate.',
+ blocker: pacSlow ? 'pac_timeout' : 'pac_not_logged_in',
+ message: pacSlow ? `${slowPac}. Retry.` : 'PAC CLI is not logged in. Run `pac auth create --environment <url>` to authenticate.',
})
);
}
// App-builder path: not a blocker — the build/verify/teardown flow uses the az token, not pac.
// Only the genpage `pages` phase shells out to `pac model genpage`. Warn so a genpage run isn't surprised.
- warnings.push(
- 'PAC CLI is not logged in. This is only required for the genpage `pages` phase (`pac model genpage ...`); ' +
- 'table/column/form/view/app builds authenticate with the az token. Run `pac auth create --environment <url>` if you need genpage.'
- );
+ warnings.push(pacSlow
+ ? `${slowPac}. This is only required for the genpage \`pages\` phase (\`pac model genpage ...\`); table/column/form/view/app builds authenticate with the az token.`
+ : 'PAC CLI is not logged in. This is only required for the genpage `pages` phase (`pac model genpage ...`); ' +
+ 'table/column/form/view/app builds authenticate with the az token. Run `pac auth create --environment <url>` if you need genpage.');
}
if (!envUrl) {
return emit(
@@ -221,6 +247,9 @@ async function main() {
try {
whoRes = await dataverseRequest(envUrl, 'GET', 'WhoAmI', null, { timeout: 30000 });
} catch (e) {
+ // The token for WhoAmI is read here when the env URL came from pac (nothing was warmed above); a
+ // read that ran out of time is the Azure CLI being slow, not WhoAmI failing.
+ const slow = tokenFailureKind(envUrl) === 'timeout';
return emit(
buildResult({
azUser,
@@ -228,8 +257,8 @@ async function main() {
envUrl,
identitiesMatch,
warnings,
- blocker: 'whoami_error',
- message: `WhoAmI probe failed: ${e.message}`,
+ blocker: slow ? 'az_timeout' : 'whoami_error',
+ message: slow ? e.message : `WhoAmI probe failed: ${e.message}`,
})
);
}
@@ -281,8 +310,12 @@ async function main() {
);
}
+ // A pac probe that ran out of time says THAT here too — its warning already does, and "not logged in" beside
+ // it contradicted it: a slow PAC CLI's login is unknown, not missing.
const readyMessage = !pacUser
- ? `Ready (az signed in as ${azUser}, env ${envUrl}). PAC is not logged in — only needed for the genpage pages phase.`
+ ? (pacSlow
+ ? `Ready (az signed in as ${azUser}, env ${envUrl}). PAC's login is unknown — \`pac org who\` did not answer in time; it is only needed for the genpage pages phase.`
+ : `Ready (az signed in as ${azUser}, env ${envUrl}). PAC is not logged in — only needed for the genpage pages phase.`)
: identitiesMatch
? `Ready (az + pac both signed in as ${azUser}, env ${envUrl}).`
: `Ready, but az ("${azUser}") and pac ("${pacUser}") use different identities. WhoAmI passed so this works for now — but if entity creation later returns 403, run \`az login --username ${pacUser}\` to align them.`;
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index a01bf6fde..5f37e9970 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -14,12 +14,12 @@ const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin } =
const { writeBaseline } = require('./lib/deployed-baseline.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { hydrateSpec, descriptionFromDataverse, withDescription } = require('./lib/hydrate-spec.js');
-const { makeGenpageCli } = require('./lib/genpage-cli.js');
+const { makeGenpageCli, unescapePacName } = require('./lib/genpage-cli.js');
const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require('./lib/page-manifest.js');
const { reverseResolveNavIds } = require('./lib/pageref-resolver.js');
const { fetchSitemap, sitemapGenPages } = require('./lib/sitemap-pages.js');
const { isRestrictedSolution } = require('./lib/system-solutions.js');
-const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey } = require('./lib/app-spec.js');
+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey, PAGE_MODEL_RE } = require('./lib/app-spec.js');
const { odataGuid } = require('./lib/ai-app-settings.js');
// webresourcetype (int) -> app-spec web-resource type.
@@ -811,7 +811,10 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo
// page's `dataSources` are unknown — and defaulting them to `[]` writes a spec that rebuilds the
// page with NO table bindings while its source still queries the table. Silent, and only visible
// once the rebuilt page returns nothing.
-function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable) {
+//
+// `unkeptModels` collects pages whose model id the App Spec cannot hold (`PAGE_MODEL_RE`): written into
+// the spec it would fail validation and block a rebuild, so it is left out and reported instead.
+function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptModels) {
const pages = [];
if (!fs.existsSync(pagesRoot)) return pages;
for (const entry of fs.readdirSync(pagesRoot)) {
@@ -856,10 +859,17 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable) {
} catch (e) {
prompt = (e && e.code === 'ENOENT') ? undefined : '';
}
+ // The model that generated the page, as config.json records it. It has to come back with the page:
+ // pac stores whatever `--model` an upload sends, so a rebuild that re-uploads without it wiped a
+ // deployed model id to "" (live-measured). Only an id the spec can hold is carried (see above).
+ const recordedModel = typeof config.model === 'string' ? config.model.trim() : '';
+ const model = PAGE_MODEL_RE.test(recordedModel) ? recordedModel : undefined;
+ if (recordedModel && !model && Array.isArray(unkeptModels)) unkeptModels.push({ pageId: entry, model: recordedModel });
pages.push({
pageId: entry,
name: (nameById && nameById.get(String(entry).toLowerCase())) || entry,
dataSources: Object.prototype.hasOwnProperty.call(config, 'dataSources') ? config.dataSources : [],
+ ...(model ? { model } : {}),
prompt,
codeFile: path.relative(outDir, tsx).replace(/\\/g, '/'),
});
@@ -1956,13 +1966,22 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
// Name resolver: env-wide name (real, stable) primary; sitemap title (XML-entity-decoded) as
// fallback when the env-wide list doesn't cover an id (shouldn't happen in practice — env-wide
- // lists all pages — but guards against an eventual stale or truncated listing).
+ // lists all pages — but guards against an eventual stale or truncated listing). Either one may hold
+ // pac's `\"` for a `"` (the row name always does; a title does when pac wrote it), and the spec's
+ // name is what a rebuild sends to pac — which would escape it again, adding a backslash every
+ // round trip. So the spec gets the name pac was given (`unescapePacName`).
const nameById = new Map(smPages.map((p) => {
const id = String(p.pageId).toLowerCase();
- return [id, envNameById.get(id) || p.title || p.pageId];
+ return [id, unescapePacName(envNameById.get(id) || p.title || p.pageId)];
}));
const unreadableConfigs = [];
- pages = parseDownloadedPages(pagesRoot, outDir, nameById, unreadableConfigs);
+ const unkeptModels = [];
+ pages = parseDownloadedPages(pagesRoot, outDir, nameById, unreadableConfigs, unkeptModels);
+ // Reported, not gated: a page whose model is left out rebuilds exactly as every page did before the
+ // spec carried models — the model is stored empty.
+ if (unkeptModels.length) {
+ process.stderr.write(`WARNING: ${unkeptModels.length} page model id(s) the App Spec cannot hold were left out, so a rebuild stores them empty: ${unkeptModels.map((u) => `${u.pageId} (${JSON.stringify(u.model)})`).join(', ')}\n`);
+ }
// A page whose config.json could not be read has UNKNOWN data sources, and the spec would claim
// it has none — rebuilding it with no table bindings while its source still queries the table.
// That is exactly the class of silent loss `--allow-lossy-download` exists to gate.
diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.js
index 4bab7a783..269195c71 100644
--- a/plugins/model-apps/scripts/genpage-upload.js
+++ b/plugins/model-apps/scripts/genpage-upload.js
@@ -31,7 +31,7 @@ const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
-const { makeGenpageCli, suppliedButBlank } = require('./lib/genpage-cli.js');
+const { makeGenpageCli, suppliedButBlank, unescapePacName } = require('./lib/genpage-cli.js');
const KNOWN = ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name', 'name-file',
'data-sources', 'clear-data-sources', 'prompt', 'prompt-file', 'agent-message', 'agent-message-file',
@@ -153,6 +153,18 @@ async function main(argv = process.argv.slice(2), deps = {}) {
});
}
}
+ // An ASCII double quote cannot be deployed in a page name: pac stores every `"` in it as `\"` — in the page
+ // row AND in the navigation title it writes, which the app then shows (live-measured: `Say "hi" now` became
+ // `Say \"hi\" now` in both). No other character is changed — backslashes, typographic quotes, apostrophes
+ // and non-ASCII text all arrive exactly — so the name is refused before anything is deployed, and the
+ // message names the characters that do survive.
+ if (typeof pageName.value === 'string' && pageName.value.includes('"')) {
+ return emit(false, {
+ error: `the page name ${JSON.stringify(pageName.value)} contains an ASCII double quote ("), which the page would `
+ + 'show as \\" — pac stores every " in a page name that way, in the navigation title too. Use typographic '
+ + 'quotes (“ ”) or an apostrophe instead; they are stored exactly.',
+ });
+ }
const addToSitemap = flags['add-to-sitemap'] === true || flags['add-to-sitemap'] === 'true';
// Same normalization as the switch above, and for the same reason: `parseArgs` yields the STRING
@@ -284,8 +296,16 @@ async function main(argv = process.argv.slice(2), deps = {}) {
// Same rule as an omitted cell span: absence is "no opinion", never "clear it". The current
// bindings are read back and re-sent, so a fix-redeploy is non-destructive by default; pass
// `--clear-data-sources` to actually unbind. A create has nothing to preserve.
+ //
+ // The page's MODEL follows the same rule: pac stores whatever `--model` an upload sends, and an update
+ // without one wiped the deployed model id to "" (live-measured). So an update that omits it re-sends the
+ // one config.json records — read from the same download.
let preservedDataSources;
- if (flags['page-id'] && !flags['data-sources'] && !clearDataSources) {
+ let preservedModel;
+ let modelUnread = null; // why the page's current model could not be read, when it could not
+ const preserveBindings = flags['page-id'] && !flags['data-sources'] && !clearDataSources;
+ const preserveModel = flags['page-id'] && !flags.model;
+ if (preserveBindings || preserveModel) {
const probe = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-ds-'));
// The failure is RECORDED and emitted after cleanup, never emitted from inside the try. The real
// `emitResult` calls `process.exit(1)`, so a `return emit(...)` in the catch never reaches the
@@ -312,23 +332,37 @@ async function main(argv = process.argv.slice(2), deps = {}) {
// path uses (`config.dataSources || []`), and how an unbound page legitimately looks. A key
// that is PRESENT but not an array is neither absent nor readable: it is malformed, and
// treating it as "no bindings" would unbind the page on the strength of a value we could not
- // interpret. Only a MISSING or UNREADABLE config is unknown, and that is refused below.
- if (cfg.dataSources !== undefined && !Array.isArray(cfg.dataSources)) {
- throw new Error(`config.json dataSources is ${typeof cfg.dataSources}, not an array`);
- }
- if (Array.isArray(cfg.dataSources)) {
- const bad = cfg.dataSources.find((value) => typeof value !== 'string' || !value.trim());
- if (bad !== undefined) {
- throw new Error('config.json dataSources must be an array of non-empty table logical names');
+ // interpret. Only a MISSING or UNREADABLE config is unknown, and that is refused below. Checked
+ // only when the bindings are what this download preserves — a caller who named them owns them.
+ if (preserveBindings) {
+ if (cfg.dataSources !== undefined && !Array.isArray(cfg.dataSources)) {
+ throw new Error(`config.json dataSources is ${typeof cfg.dataSources}, not an array`);
+ }
+ if (Array.isArray(cfg.dataSources)) {
+ const bad = cfg.dataSources.find((value) => typeof value !== 'string' || !value.trim());
+ if (bad !== undefined) {
+ throw new Error('config.json dataSources must be an array of non-empty table logical names');
+ }
}
+ preservedDataSources = Array.isArray(cfg.dataSources) ? cfg.dataSources : [];
+ }
+ // An absent or empty model is the page having none — nothing to re-send.
+ if (preserveModel) {
+ if (typeof cfg.model === 'string' && cfg.model.trim()) preservedModel = cfg.model.trim();
+ else if (cfg.model !== undefined && cfg.model !== null && cfg.model !== '') modelUnread = `config.json model is ${typeof cfg.model}, not a string`;
}
- preservedDataSources = Array.isArray(cfg.dataSources) ? cfg.dataSources : [];
} catch (e) {
- // Fail CLOSED: guessing "probably none" is exactly the silent unbinding this exists to stop.
- probeError = `cannot read the current data-source bindings for page ${flags['page-id']} (${e.message})`
- + ' — refusing to update, because pac would persist an EMPTY binding list and the page would'
- + ' keep querying a table it is no longer bound to. Pass --data-sources explicitly, or'
- + ' --clear-data-sources to unbind deliberately.';
+ // Fail CLOSED for the BINDINGS: guessing "probably none" is exactly the silent unbinding this exists
+ // to stop. The model is metadata — the page works without it — so not knowing it never blocks an
+ // update (a deliberate `--clear-data-sources` included); it is reported instead.
+ if (preserveBindings) {
+ probeError = `cannot read the current data-source bindings for page ${flags['page-id']} (${e.message})`
+ + ' — refusing to update, because pac would persist an EMPTY binding list and the page would'
+ + ' keep querying a table it is no longer bound to. Pass --data-sources explicitly, or'
+ + ' --clear-data-sources to unbind deliberately.';
+ } else {
+ modelUnread = e.message;
+ }
} finally {
// Best-effort: a cleanup failure must not replace the outcome of the operation, nor abort an
// update whose bindings were read successfully.
@@ -337,19 +371,54 @@ async function main(argv = process.argv.slice(2), deps = {}) {
if (probeError) return emit(false, { error: probeError });
}
+ // An UPDATE without a name keeps the page's CURRENT name. pac otherwise renames it to its navigation
+ // title — live-reproduced: a page renamed by an earlier upload went back to its original title when a
+ // later update omitted the name. The name lives only on the page's Dataverse row, so it is read from
+ // there and sent again, unescaped (`unescapePacName`): pac's escaping then stores exactly the value that
+ // was there. Only a `"` that pac did not write (no backslash before it — a name set some other way)
+ // cannot be kept as it is; the update goes ahead and says so. A name pac cannot be HANDED here — a
+ // `pac.cmd` shim cannot receive `%` or `"` — is not sent at all: the update proceeds as it did before
+ // names were kept, and says so. Metadata, like the model: not knowing or not being able to send the name
+ // never blocks the update, and is reported.
+ let preservedName;
+ let nameUnread = null;
+ let nameChanged = null;
+ let nameUnsent = null;
+ if (flags['page-id'] && pageName.value === undefined) {
+ if (typeof cli.pageName !== 'function') {
+ nameUnread = 'this pac wrapper cannot read a page name';
+ } else {
+ try {
+ const current = await cli.pageName(flags['page-id']);
+ if (typeof current === 'string' && current.trim()) {
+ const name = unescapePacName(current);
+ const refusal = typeof cli.argumentRefusal === 'function' ? cli.argumentRefusal(name) : null;
+ if (refusal) {
+ nameUnsent = { current, refusal };
+ } else {
+ preservedName = name;
+ if (/(?:^|[^\\])"/.test(current)) nameChanged = current;
+ }
+ }
+ } catch (e) {
+ nameUnread = (e && e.message) || String(e);
+ }
+ }
+ }
+
try {
const res = await cli.upload({
appId: flags['app-id'],
pageId: flags['page-id'] || undefined,
codeFile: flags['code-file'],
compiledCodeFile: flags['compiled-code-file'] || undefined,
- name: pageName.value || undefined,
+ name: pageName.value || preservedName || undefined,
prompt: prompt.value,
agentMessage: agentMessage.value,
// Passed through as the CSV the caller typed; upload() normalizes array-or-string. When the
// caller said nothing on an update, this carries the page's EXISTING bindings so they survive.
dataSources: flags['data-sources'] || preservedDataSources || undefined,
- model: flags.model || undefined,
+ model: flags.model || preservedModel || undefined,
connectors: flags.connectors || undefined,
actions: flags.actions || undefined,
addToSitemap,
@@ -369,11 +438,18 @@ async function main(argv = process.argv.slice(2), deps = {}) {
}
// `pageId` is the one value a caller needs in order to continue (sitemap wiring, a follow-up
// edit). Echo the identity back rather than making the caller re-parse pac output.
+ const warnings = [
+ ...(modelUnread ? [`could not read page ${flags['page-id']}'s current model (${modelUnread}), so this update stored it empty — pass --model to set it`] : []),
+ ...(nameUnread ? [`could not read page ${flags['page-id']}'s current name (${nameUnread}), so pac may have renamed it to its navigation title — pass --name-file to set it`] : []),
+ ...(nameChanged ? [`page ${flags['page-id']}'s name ${JSON.stringify(nameChanged)} has a double quote (") pac cannot store as it is, so the page now shows \\" there — pass --name-file with typographic quotes (“ ”) or an apostrophe to fix it`] : []),
+ ...(nameUnsent ? [`page ${flags['page-id']}'s name ${JSON.stringify(nameUnsent.current)} could not be sent to keep it (${nameUnsent.refusal}), so pac may have renamed the page to its navigation title — give it a name without % or a double quote, or install pac as a .NET tool, which receives any name`] : []),
+ ];
return emit(true, {
ok: true,
pageId,
appId: flags['app-id'],
updated: !!flags['page-id'],
+ ...(warnings.length ? { warnings } : {}),
});
} catch (e) {
return emit(false, { error: e && e.message ? e.message : String(e) });
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index 033848a9d..515b782c2 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -26,6 +26,9 @@ const FORM_TYPE_CODE = { Main: 2, QuickView: 6, QuickCreate: 7, Card: 11 };
// A canonical GUID (used to validate an author-pinned forms[].formId, which is interpolated UNQUOTED into
// an Edm.Guid OData filter). Anchored so it can neither over-match nor be an injection seam.
const FORM_GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+// A page's model id (`pages[].model`), e.g. `gpt-4.1` or `claude-3-5-sonnet@20240620`: a short token, because the
+// build hands it to pac as one command-line value. Shared with download, which carries only a model the spec can hold.
+const PAGE_MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,99}$/;
// Security-authoring enums (personas[]). These mirror the vendored SDK's security surface
// (cds-maker-sdk src/types/security.ts) EXACTLY — the app-spec validator is a lint-time echo of the
@@ -1308,6 +1311,18 @@ function authoredSectionNames(formSpec, { named = false } = {}) {
return names;
}
+// Every tab name an explicit layout declares, under the name the compiler gives it, lower-cased — the
+// tabs' counterpart of authoredSectionNames, for the same reason: a deployed tab another tab of the
+// layout claims by name is not handed to a different one by label or position. Without it, a tab
+// declared mid-layout took the next existing tab by POSITION, and that tab's own want — its name now
+// taken — created a second tab of the same name.
+function authoredTabNames(formSpec) {
+ const names = new Set();
+ const tabs = formSpec && Array.isArray(formSpec.tabs) ? formSpec.tabs : [];
+ tabs.forEach((t, ti) => { if (t && typeof t === 'object') names.add(String(t.name || generatedTabName(ti)).toLowerCase()); });
+ return names;
+}
+
// The plugin's own version, read from its manifest, for the `minimumPluginVersion` capability gate.
//
// Cached, and NULL when the manifest cannot be read. The caller decides what that means, and it is
@@ -2785,6 +2800,11 @@ function validateAppSpec(spec, opts = {}) {
if (p.pageId !== undefined && !PAGE_ID_GUID.test(String(p.pageId))) {
errors.push(`page '${p.key || p.name}': pageId must be a 36-char GUID`);
}
+ // The id of the model that generated the page — what `pac model genpage upload --model` records, and
+ // what a download writes back. A short token (e.g. `gpt-4.1`); it travels as a command-line value.
+ if (p.model !== undefined && (typeof p.model !== 'string' || !PAGE_MODEL_RE.test(p.model))) {
+ errors.push(`page '${p.key || p.name}': model must be a model id such as 'gpt-4.1' (letters, digits and . _ : / @ + -, at most 100 characters)`);
+ }
const src = normalizePageSource(p);
// Track whether a structural source error was emitted so the profile check below doesn't
// double-report (e.g. source:{kind:'tsx'} with no codeFile should get ONE error, not two).
@@ -3722,6 +3742,7 @@ module.exports = {
generatedSectionName,
formColumnsOf,
authoredSectionNames,
+ authoredTabNames,
validateAppSpec,
validateSampleDataRows,
normalizePageSource,
@@ -3739,6 +3760,7 @@ module.exports = {
webResourceNameFromRef,
FORM_TYPE_CODE,
FORM_GUID_RE,
+ PAGE_MODEL_RE,
ACCESS_LEVELS,
PRIVILEGE_SCOPES,
ROLE_GRANT_KEYS,
diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.js
index 4297eaf31..942d12c4c 100644
--- a/plugins/model-apps/scripts/lib/artifact-intent.js
+++ b/plugins/model-apps/scripts/lib/artifact-intent.js
@@ -11,7 +11,7 @@
// the SDK's generic mutation surface without hardcoding form-model logic everywhere.
const { entityByLogical } = require('./_graph.js');
-const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf, authoredSectionNames } = require('./app-spec.js');
+const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf, authoredSectionNames, authoredTabNames } = require('./app-spec.js');
const { SDK_COLUMN_TYPE } = require('./entity-provision.js');
// Arrange field cells into `columns` cells-per-row.
@@ -697,6 +697,8 @@ function compileFormIntent(spec, formSpec, opts) {
// The section names the author declared (see `authoredSectionNames`), so the engine's reconcile
// skips the same containers verify skips. An array, because the compiled def is plain data.
__authoredSectionNames: [...authoredSectionNames(formSpec)],
+ // …the tab names, for the same reason (see `authoredTabNames`)…
+ __authoredTabNames: [...authoredTabNames(formSpec)],
// …and the subset the author NAMED, which the engine's sweep reads to word its report.
__namedSectionNames: [...authoredSectionNames(formSpec, { named: true })],
// Ordering anchors: { <logical>: <anchorLogical> }. Consumed by the engine's reconcile, which
diff --git a/plugins/model-apps/scripts/lib/cli-failure.js b/plugins/model-apps/scripts/lib/cli-failure.js
new file mode 100644
index 000000000..10ba2c282
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/cli-failure.js
@@ -0,0 +1,58 @@
+'use strict';
+
+// How a CLI child process failed, and how long one Azure CLI call may take.
+//
+// The auth preflight and every Dataverse token read shell out to `az` (check-auth also to `pac`), and
+// each failure used to come back as the same thing: null. A slow Azure CLI therefore read as a missing
+// or signed-out one — a cached-token read was measured at 44.6 s on a busy machine, past the 30 s
+// budget, and check-auth reported `az_missing` ("not installed") while every script said "run az login".
+// Neither was the problem. A failure now has one of three kinds, and a timeout is reported as one.
+
+const AZ_TIMEOUT_ENV = 'POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS';
+const DEFAULT_AZ_TIMEOUT_MS = 60000;
+// The range an override may take: 1 s to 15 min. Shared by the parser and the advice below, so the
+// advice can never suggest a value the parser would reject — and so fall back to the 60 s default.
+const MIN_AZ_TIMEOUT_MS = 1000;
+const MAX_AZ_TIMEOUT_MS = 900000;
+
+// The budget for one Azure CLI call: 60 s, or POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS milliseconds (1 s to
+// 15 min). An unusable value keeps the default rather than failing the run — this is a tuning knob for
+// a slow machine, not an input a mistake in which should stop the work.
+function azTimeoutMs(env = process.env) {
+ const n = Number(env && env[AZ_TIMEOUT_ENV]);
+ return Number.isInteger(n) && n >= MIN_AZ_TIMEOUT_MS && n <= MAX_AZ_TIMEOUT_MS ? n : DEFAULT_AZ_TIMEOUT_MS;
+}
+
+// 'timeout' | 'missing' | 'failed' for an error from the process runner, or null for none. The shapes
+// Node gives each case (https://nodejs.org/api/child_process.html):
+// execFileSync / spawnSync past `timeout` code 'ETIMEDOUT'
+// execFile past `timeout` killed: true, signal: the kill signal, code: null
+// not on PATH code 'ENOENT' — the runner resolves the executable before
+// it spawns anything ("spawn az ENOENT: not found on PATH")
+// Any other code (a non-zero exit, output past maxBuffer — which also kills the child) is 'failed'.
+function cliFailureKind(error) {
+ if (!error) return null;
+ if (error.code === 'ETIMEDOUT') return 'timeout';
+ if (error.code === 'ENOENT') return 'missing';
+ if (typeof error.code === 'string') return 'failed';
+ if (error.killed === true && error.signal) return 'timeout';
+ if (/\bENOENT\b/.test(String(error.message || ''))) return 'missing';
+ return 'failed';
+}
+
+// What to tell the user when `command` ran out of time: that it was slow, and how to allow it longer. The
+// suggested budget is double the one that ran out (at least 2 min), CAPPED at the maximum the parser
+// accepts — a suggestion above it would be rejected and quietly put the budget back to 60 s. Once the
+// budget is already the maximum, more time is not the remedy, and the advice says so.
+function azTimeoutAdvice(command, ms = azTimeoutMs()) {
+ const ranOut = `\`${command}\` did not answer within ${Math.round(ms / 1000)} s.`;
+ if (ms >= MAX_AZ_TIMEOUT_MS) {
+ return `${ranOut} That is already the longest ${AZ_TIMEOUT_ENV} allows (${MAX_AZ_TIMEOUT_MS / 60000} min), so `
+ + `waiting longer will not help: run \`${command}\` yourself to see whether Azure CLI answers at all, then retry.`;
+ }
+ const longer = Math.min(Math.max(ms * 2, 120000), MAX_AZ_TIMEOUT_MS);
+ return `${ranOut} Azure CLI can take that long to start on a busy machine — retry, or allow it longer with `
+ + `${AZ_TIMEOUT_ENV}=${longer}.`;
+}
+
+module.exports = { AZ_TIMEOUT_ENV, DEFAULT_AZ_TIMEOUT_MS, MIN_AZ_TIMEOUT_MS, MAX_AZ_TIMEOUT_MS, azTimeoutMs, cliFailureKind, azTimeoutAdvice };
diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.js
index 16cd7ba63..47b8a0d77 100644
--- a/plugins/model-apps/scripts/lib/dataverse-auth.js
+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js
@@ -9,6 +9,7 @@
const { normalizeLanguageCode } = require('./app-spec.js');
const { nearestName } = require('./nearest-name.js');
const { execFileAsync, runSync } = require('./process-runner.js');
+const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./cli-failure.js');
// Dataverse environment hosts, one family per cloud (the same families power-pages accepts in
// scripts/lib/validation-helpers.js, plus the non-numbered `crm<ring>` labels such as crmtest):
@@ -59,6 +60,10 @@ function requireDataverseOrigin(value) {
* @returns {string|null}
*/
const authTokenMemo = new Map();
+// Why the last token read for an origin failed — 'timeout' | 'missing' | 'failed' (cli-failure.js) —
+// so the caller that then throws can say which, instead of "run az login" for a slow Azure CLI.
+const tokenFailures = new Map();
+const noteTokenFailure = (resource, error) => tokenFailures.set(resource, cliFailureKind(error) || 'failed');
function getAuthToken(envUrl, opts = {}) {
const resource = dataverseOrigin(envUrl);
@@ -71,18 +76,19 @@ function getAuthToken(envUrl, opts = {}) {
const out = exec(
'az',
['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'],
- { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'] }
+ { encoding: 'utf8', timeout: azTimeoutMs(), stdio: ['ignore', 'pipe', 'pipe'] }
);
const token = out.trim() || null;
// `az account get-access-token` is expensive on a cold Windows process, but an immediate
// re-call returns the same MSAL-cached token (see the ensureOk 401 note below). Reusing that
// non-null token within this Node process removes repeated CLI cold-starts without changing
// Dataverse semantics; a caller that just saw a 401 passes `{ fresh: true }` to replace it.
- if (token) authTokenMemo.set(resource, token);
- else authTokenMemo.delete(resource);
+ if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); }
+ else { authTokenMemo.delete(resource); noteTokenFailure(resource, null); }
return token;
- } catch {
+ } catch (e) {
if (opts.fresh) authTokenMemo.delete(resource);
+ noteTokenFailure(resource, e);
return null;
}
}
@@ -99,10 +105,11 @@ function getAuthTokenAsync(envUrl, opts = {}) {
exec(
'az',
['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'],
- { encoding: 'utf8', timeout: 30000, windowsHide: true },
+ { encoding: 'utf8', timeout: azTimeoutMs(), windowsHide: true },
(error, stdout) => {
if (error) {
if (opts.fresh) authTokenMemo.delete(resource);
+ noteTokenFailure(resource, error);
resolve(null);
return;
}
@@ -110,18 +117,39 @@ function getAuthTokenAsync(envUrl, opts = {}) {
// Shares the synchronous helper's memo deliberately: check-auth can pre-warm the token
// without blocking the event loop, and later synchronous Dataverse callers in the same
// process still avoid a second Azure CLI cold start.
- if (token) authTokenMemo.set(resource, token);
- else authTokenMemo.delete(resource);
+ if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); }
+ else { authTokenMemo.delete(resource); noteTokenFailure(resource, null); }
resolve(token);
}
);
- } catch {
+ } catch (e) {
if (opts.fresh) authTokenMemo.delete(resource);
+ noteTokenFailure(resource, e);
resolve(null);
}
});
}
+/**
+ * Why the last token read for `envUrl` failed: 'timeout' | 'missing' | 'failed', or null when it did
+ * not (or none was attempted in this process).
+ */
+function tokenFailureKind(envUrl) {
+ return tokenFailures.get(dataverseOrigin(envUrl)) || null;
+}
+
+/**
+ * The message to throw when no token could be had for `envUrl`: a slow or missing Azure CLI said as
+ * such, and anything else as `fallback` — the sign-in advice each caller already gives.
+ */
+function tokenFailureMessage(envUrl, fallback) {
+ const origin = dataverseOrigin(envUrl) || String(envUrl);
+ const kind = tokenFailureKind(envUrl);
+ if (kind === 'timeout') return `Could not get an Azure CLI token for ${origin}: ${azTimeoutAdvice('az account get-access-token')}`;
+ if (kind === 'missing') return `Could not get an Azure CLI token for ${origin}: Azure CLI (\`az\`) is not on PATH. Install it from https://aka.ms/azure-cli and run \`az login\`.`;
+ return fallback;
+}
+
/**
* Reads the Azure CLI identity that will supply the Dataverse token. Best-effort and never throws —
* it exists to make a failure explicable, so it must not become a failure of its own.
@@ -132,7 +160,7 @@ function azIdentity(deps = {}) {
const out = (deps.exec || runSync)(
'az',
['account', 'show', '--query', '{user:user.name,tenantId:tenantId}', '-o', 'json'],
- { encoding: 'utf8', timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'] }
+ { encoding: 'utf8', timeout: azTimeoutMs(), stdio: ['ignore', 'pipe', 'pipe'] }
);
const parsed = JSON.parse(out);
return parsed && parsed.user ? { user: parsed.user, tenantId: parsed.tenantId || '(unknown)' } : null;
@@ -194,10 +222,12 @@ async function preflightAuth(envUrl, deps = {}) {
let token = null;
try { token = getToken(origin); } catch { token = null; }
if (!token) {
+ // A slow or missing Azure CLI is said as such: it is not a sign-in problem, and `az login` fixes
+ // neither. Only a failure the CLI actually reported gets the sign-in advice.
return {
ok: false,
- error: `no Azure CLI access token could be obtained for ${origin}. This is a sign-in problem, not a `
- + `permissions one — run \`az login\` (add \`--tenant <id>\` if this org lives in another tenant), then retry.`,
+ error: tokenFailureMessage(origin, `no Azure CLI access token could be obtained for ${origin}. This is a sign-in problem, not a `
+ + `permissions one — run \`az login\` (add \`--tenant <id>\` if this org lives in another tenant), then retry.`),
};
}
@@ -344,7 +374,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})
// been rejected is exactly the thing that must not be retried.
let token = presetToken || acquireToken(cleanUrl, { fresh: false });
if (!token) {
- throw new Error(`Failed to get Azure CLI token for ${cleanUrl}. Run 'az login' first.`);
+ throw new Error(tokenFailureMessage(cleanUrl, `Failed to get Azure CLI token for ${cleanUrl}. Run 'az login' first.`));
}
const maxRetries = 2;
@@ -367,7 +397,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})
if (res.statusCode === 401 && attempt < maxRetries) {
token = acquireToken(cleanUrl, { fresh: true });
- if (!token) throw new Error("Token refresh failed. Run 'az login' again.");
+ if (!token) throw new Error(tokenFailureMessage(cleanUrl, "Token refresh failed. Run 'az login' again."));
continue;
}
@@ -722,6 +752,8 @@ module.exports = {
azIdentity,
getAuthToken,
getAuthTokenAsync,
+ tokenFailureKind,
+ tokenFailureMessage,
makeRequest,
dataverseRequest,
ensureOk,
diff --git a/plugins/model-apps/scripts/lib/form-container-match.js b/plugins/model-apps/scripts/lib/form-container-match.js
index 02c6afdf7..e1ad068f2 100644
--- a/plugins/model-apps/scripts/lib/form-container-match.js
+++ b/plugins/model-apps/scripts/lib/form-container-match.js
@@ -109,4 +109,62 @@ function claimedByAuthoredName(authoredNames) {
};
}
-module.exports = { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName };
+// ORDER — the layout's order of the containers it matched: the build moves them into it (tabs, and the
+// sections in each form-column) and verify requires it. Only the RELATIVE order of the matched containers
+// is the author's. A tab or section the layout does not mention — a maker's own, an engine host — has no
+// place in that order and is never moved for its own sake.
+//
+// `positions` are the current indices, in ONE array, of the containers the layout places there, listed in
+// the layout's order. Returns `{ moves, positions }`: the moves that put them in that order, each as the
+// SDK's moveElement takes it — `from`, the index in the array as it stands when that move runs, and `to`,
+// the index to insert at once the source is removed (moveElement removes first, then splices) — and each
+// container's index afterwards, in the order of the input.
+//
+// The longest run already in the layout's order stays put, and every other container moves in right
+// after the one the layout places before it (the first, right before the first one staying put). So the
+// fewest containers move, and a maker's own containers keep their place beside those that stay. A
+// container already where it would land is not moved: every move is a write, and a line in the report.
+function planOrderMoves(positions) {
+ const pos = positions.slice();
+ const n = pos.length;
+ // Longest strictly increasing run, by O(n²) dynamic programming: n is the number of tabs, or of
+ // sections in one form-column. Ties keep the run that ends first, so the plan is deterministic.
+ const runLength = new Array(n).fill(1);
+ const before = new Array(n).fill(-1);
+ let end = -1;
+ for (let i = 0; i < n; i += 1) {
+ for (let j = 0; j < i; j += 1) {
+ if (pos[j] < pos[i] && runLength[j] + 1 > runLength[i]) { runLength[i] = runLength[j] + 1; before[i] = j; }
+ }
+ if (end < 0 || runLength[i] > runLength[end]) end = i;
+ }
+ const stays = new Set();
+ for (let i = end; i >= 0; i = before[i]) stays.add(i);
+ const moves = [];
+ for (let w = 0; w < n; w += 1) {
+ if (stays.has(w)) continue;
+ const from = pos[w];
+ let to;
+ if (w > 0) {
+ const anchor = pos[w - 1];
+ to = from < anchor ? anchor : anchor + 1;
+ } else {
+ // The first container is out of the run, so the run starts later — and it goes before it.
+ const anchor = pos[Math.min(...stays)];
+ to = from < anchor ? anchor - 1 : anchor;
+ }
+ if (to === from) continue;
+ moves.push({ from, to });
+ for (let k = 0; k < n; k += 1) {
+ if (k === w) continue;
+ let p = pos[k];
+ if (p > from) p -= 1;
+ if (p >= to) p += 1;
+ pos[k] = p;
+ }
+ pos[w] = to;
+ }
+ return { moves, positions: pos };
+}
+
+module.exports = { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName, planOrderMoves };
diff --git a/plugins/model-apps/scripts/lib/genpage-cli.js b/plugins/model-apps/scripts/lib/genpage-cli.js
index d16b31359..ebee5e7e5 100644
--- a/plugins/model-apps/scripts/lib/genpage-cli.js
+++ b/plugins/model-apps/scripts/lib/genpage-cli.js
@@ -3,6 +3,7 @@
// to author/deploy generative pages. Page CONTENT only: uploads run WITHOUT --add-to-sitemap because
// the SDK owns the sitemap (it writes the GenPage subareas). Real impl spawns pac; tests inject `run`.
const { invocation, spawnProcess } = require('./process-runner.js');
+const { dataverseRequest } = require('./dataverse-auth.js');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
@@ -93,6 +94,15 @@ function runPac(args) {
// means the token continues. Returning null is the safe outcome: the caller treats a zero exit with
// no parsable id as an UNCERTAIN create and reconciles by env-wide id diff.
const GUID_RE = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/;
+// A value that IS a GUID and nothing else — what may go into a Dataverse key segment, `uxagentprojects(<id>)`.
+const GUID_ONLY_RE = new RegExp(`^${GUID_RE.source}$`);
+// pac stores every ASCII `"` in a page name as `\"` — in the page's row and in a navigation title it writes (live-measured:
+// `Say "hi" now` became `Say \"hi\" now` in both) — and changes nothing else. This is the inverse: the name pac was given.
+// Sent back as the name, it makes pac store the same value again; a name read back and re-sent as it is would gain a
+// backslash on every upload.
+function unescapePacName(name) {
+ return String(name).replace(/\\"/g, '"');
+}
// The end of a GUID token, for a RegExp built with the 'u' flag. Shared by both parsers below.
const GUID_END = '(?![\\p{L}\\p{N}\\p{M}_-])';
function parsePageId(out) {
@@ -541,6 +551,31 @@ function makeGenpageCli(env, deps = {}) {
if (r.status !== 0) throw new Error(`pac genpage download failed: ${pacDiagnostic(r)}`);
return true;
},
+ // The page's current display name, from its Dataverse row (`uxagentproject.name`). An update without
+ // `--name` renames the page to its navigation title, so a caller that wants to keep the name must read
+ // it and send it. pac's app-scoped listing shows the navigation title instead, and its env-wide listing
+ // prints the name trimmed, in a fixed-width table — so the row itself is read, through Dataverse (the
+ // az token). The row cannot be written there: a PATCH of `name` answers 204 and changes nothing
+ // (live-measured), so pac's `--name` is the only way to set it.
+ async pageName(pageId) {
+ if (!GUID_ONLY_RE.test(String(pageId || ''))) throw new Error(`'${pageId}' is not a page id`);
+ const request = deps.request || dataverseRequest;
+ const res = await request(env, 'GET', `uxagentprojects(${pageId})?$select=name`);
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`reading page ${pageId}'s name returned HTTP ${res && res.status}`);
+ return res.data && typeof res.data.name === 'string' ? res.data.name : null;
+ },
+ // Why pac, as installed here, cannot be handed `value` as an argument — null when it can. A `pac.cmd` shim
+ // (Windows) cannot receive a double quote or `%` unchanged, and the runner refuses such a value rather than
+ // let cmd.exe rewrite it. Checked without starting anything, so a caller can decide BEFORE an upload
+ // whether a value it chose on the user's behalf — a page's current name — can be sent at all.
+ argumentRefusal(value) {
+ try {
+ buildPacInvocation(['--name', value], deps.pacInvocation);
+ return null;
+ } catch (e) {
+ return e && e.code === 'EARGUMENT' ? e.message : null;
+ }
+ },
};
}
@@ -551,4 +586,4 @@ function makeGenpageCli(env, deps = {}) {
function suppliedButBlank(value) {
return value !== undefined && value !== null && !String(value).trim();
}
-module.exports = { makeGenpageCli, suppliedButBlank, parsePageId, parseList, parseListCount, classifyListOutput, buildPacInvocation, runPac };
+module.exports = { makeGenpageCli, suppliedButBlank, unescapePacName, parsePageId, parseList, parseListCount, classifyListOutput, buildPacInvocation, runPac };
diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.js
index 8036ba77d..98b5066c5 100644
--- a/plugins/model-apps/scripts/lib/hydrate-spec.js
+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js
@@ -272,6 +272,7 @@ async function hydrateSpec(read) {
...(p.pageId ? { pageId: p.pageId } : {}),
...(p.purpose !== undefined ? { purpose: p.purpose } : {}),
...(p.dataSources && p.dataSources.length ? { dataSources: p.dataSources } : {}),
+ ...(p.model ? { model: p.model } : {}),
...(p.navigatesTo ? { navigatesTo: p.navigatesTo } : {}),
...(p.pageInput !== undefined ? { pageInput: p.pageInput } : {}),
...directEntryOf(p),
@@ -283,6 +284,7 @@ async function hydrateSpec(read) {
: {
name: p.name,
...(p.dataSources && p.dataSources.length ? { dataSources: p.dataSources } : {}),
+ ...(p.model ? { model: p.model } : {}),
...(p.prompt !== undefined ? { prompt: p.prompt } : {}),
codeFile: p.codeFile,
})),
diff --git a/plugins/model-apps/scripts/lib/pageref-resolver.js b/plugins/model-apps/scripts/lib/pageref-resolver.js
index f90b64427..550f28699 100644
--- a/plugins/model-apps/scripts/lib/pageref-resolver.js
+++ b/plugins/model-apps/scripts/lib/pageref-resolver.js
@@ -29,46 +29,122 @@ const { blankNonCodePreservingTemplateExpressions } = require('./source-literals
// as a comment opener, blanked everything after it, and dropped every later call — so a literal
// "PAGEREF_detail" shipped unresolved while verification passed.
-// `navigateTo(` immediately followed by an object literal `{`. `\s*` tolerates the multi-line form in
-// references/rules.md. The method-name prefix (Xrm.Navigation./xrm.Navigation.) is irrelevant to the
-// match, so any call spelled `navigateTo({ … })` is covered.
-const NAV_CALL = /navigateTo\s*\(\s*\{/g;
+// A navigation call can be bare, a member call, optional (`navigateTo?.({ … })`), or spell the
+// identifier through JavaScript Unicode escapes (`navigate\u0054o`). A regex cannot distinguish
+// that identifier from a longer one such as `notnavigateTo`, `x\u0041navigateTo`, or a name using
+// ZWNJ/ZWJ continuation characters, so call-site discovery tokenizes identifiers before checking
+// for the object-literal argument.
const CANON = /^"PAGEREF_([A-Za-z0-9_-]+)"$/; // canonical: double-quoted, both sides
const PAGEREF_ANY = /PAGEREF_([A-Za-z0-9_-]+)/; // a PAGEREF token in ANY form (used to detect malformed)
// Content must not span across unescaped quote chars — prevents matching a "foo"+"bar" concat
// as a single literal when the full expression is somehow presented as a raw string.
const QUOTED = /^(["'`])((?:[^"'`\\]|\\[\s\S])*)\1$/;
-// Scan the object-literal argument of a navigateTo(...) call from the '{' at `open` to its matching
-// '}', string-aware so a brace inside a string does not end the object. Returns { text, end } or null
-// on an unbalanced/broken literal (the caller treats a broken call as having no nav target).
-function objectArgAt(code, open) {
- let depth = 0;
- let inStr = null;
- for (let i = open; i < code.length; i += 1) {
- const c = code[i];
- if (inStr) { if (c === '\\') { i += 1; continue; } if (c === inStr) inStr = null; continue; }
- // inStr handles quoted values — the mask keeps their delimiters and blanks their bodies — so a
- // quote or brace in a value never counts toward the object boundary.
- if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }
- if (c === '{') depth += 1;
- else if (c === '}') { depth -= 1; if (depth === 0) return { text: code.slice(open, i + 1), end: i + 1 }; }
+function isIdentifierStart(ch) {
+ return ch === '$' || ch === '_' || /\p{ID_Start}/u.test(ch || '');
+}
+
+function isIdentifierContinue(ch) {
+ return ch === '$' || ch === '_' || ch === '\u200c' || ch === '\u200d' || /\p{ID_Continue}/u.test(ch || '');
+}
+
+function readUnicodeEscape(src, i) {
+ if (src[i] !== '\\' || src[i + 1] !== 'u') return null;
+ if (src[i + 2] === '{') {
+ const end = src.indexOf('}', i + 3);
+ if (end === -1) return null;
+ const hex = src.slice(i + 3, end);
+ if (!/^[0-9A-Fa-f]{1,6}$/.test(hex)) return null;
+ const cp = Number.parseInt(hex, 16);
+ if (cp > 0x10ffff) return null;
+ return { ch: String.fromCodePoint(cp), end: end + 1 };
+ }
+ const hex = src.slice(i + 2, i + 6);
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return null;
+ return { ch: String.fromCharCode(Number.parseInt(hex, 16)), end: i + 6 };
+}
+
+function readCodePoint(src, i) {
+ const cp = src.codePointAt(i);
+ if (cp === undefined) return null;
+ return { ch: String.fromCodePoint(cp), end: i + (cp > 0xffff ? 2 : 1) };
+}
+
+function readIdentifier(src, i) {
+ if (src[i] === '#') {
+ const privateName = readIdentifier(src, i + 1);
+ return privateName ? { name: `#${privateName.name}`, end: privateName.end } : null;
+ }
+ const firstEscape = readUnicodeEscape(src, i);
+ const first = firstEscape || readCodePoint(src, i);
+ if (!first || !isIdentifierStart(first.ch)) return null;
+ let name = first.ch;
+ let end = first.end;
+ while (end < src.length) {
+ const esc = readUnicodeEscape(src, end);
+ const next = esc || readCodePoint(src, end);
+ if (!next || !isIdentifierContinue(next.ch)) break;
+ name += next.ch;
+ end = next.end;
}
- return null;
+ return { name, end };
+}
+
+function skipSpace(mask, i) {
+ while (i < mask.length && /\s/.test(mask[i])) i += 1;
+ return i;
+}
+
+function matchingBraces(mask) {
+ const matches = new Map();
+ const stack = [];
+ for (let i = 0; i < mask.length; i += 1) {
+ if (mask[i] === '{') stack.push(i);
+ else if (mask[i] === '}' && stack.length) {
+ const open = stack.pop();
+ matches.set(open, i);
+ }
+ }
+ return matches;
+}
+
+function navigationObjectOpenAt(mask, nameEnd) {
+ let i = skipSpace(mask, nameEnd);
+ if (mask[i] === '?' && mask[i + 1] === '.') i = skipSpace(mask, i + 2);
+ if (mask[i] !== '(') return -1;
+ i = skipSpace(mask, i + 1);
+ return mask[i] === '{' ? i : -1;
+}
+
+function navigateCallObjectOpens(mask) {
+ const opens = [];
+ for (let i = 0; i < mask.length; i += 1) {
+ const id = readIdentifier(mask, i);
+ if (!id) continue;
+ if (id.name === 'navigateTo') {
+ const open = navigationObjectOpenAt(mask, id.end);
+ if (open !== -1) opens.push(open);
+ }
+ i = Math.max(i, id.end - 1);
+ }
+ return opens;
+}
+
+// Read the object-literal argument of a navigateTo(...) call from the precomputed brace table. The
+// mask has already blanked comments and literal bodies, so unmatched malformed calls are an O(1)
+// miss instead of every candidate scanning to EOF.
+function objectArgAt(code, open, braceMatches) {
+ const close = braceMatches.get(open);
+ return close === undefined ? null : { text: code.slice(open, close + 1), end: close + 1 };
}
-// Read the VALUE of a TOP-LEVEL `key:` in an object-literal text (depth 1 only — never a key inside a
-// nested data:{}/pageInput:{}). `objText` begins with '{'. Returns { raw, valueStart, valueEnd } (span
-// relative to objText) or null when the key is absent at the top level. A quoted value captures the
-// whole string literal (escape-aware); an unquoted value (or a quoted string followed by '+', which
-// indicates a concat expression) runs to the next top-level ',' or the closing '}'. The char-before
-// check rejects a false hit inside a longer identifier (e.g. `myPageId`).
+// Read the VALUE of the last effective TOP-LEVEL `key` in an object-literal text. Object
+// literals are last-write-wins at runtime, including methods, accessors and shorthand properties:
+// { pageId: "PAGEREF_detail", get pageId() { return "runtime"; } }
+// { pageType: "generative", pageType() { return "entityrecord"; } }
+// Later computed keys and spreads can also overwrite either property, so a literal before them is
+// classified dynamic; a literal after them wins again by normal object order.
function topLevelValue(objText, key, sourceObjText = objText) {
- let depth = 0;
- let inStr = null;
- // `key` is always a code-controlled literal ('pageType' or 'pageId'), never user-supplied,
- // so no regex-escape is needed before interpolating into the pattern.
- const keyRe = new RegExp('^' + key + '\\s*:');
const scanStringEnd = (from) => {
const q = objText[from];
for (let k = from + 1; k < objText.length; k += 1) {
@@ -77,92 +153,162 @@ function topLevelValue(objText, key, sourceObjText = objText) {
}
return null;
};
- const followsPropertyBoundary = (from) => {
- // Object keys begin immediately after `{` or `,` once whitespace is skipped. The mask blanks
- // comments to same-length whitespace, so this deliberately walks the mask rather than the source:
- // { /* note */ "pageId": "..." } -> previous non-space is `{`
- // c ? "pageId" : "..." -> previous non-space is `?`, not a key boundary
- // An identifier character before the match (`myPageId`) therefore still fails.
- let p = from - 1;
- while (p >= 0 && /\s/.test(objText[p])) p -= 1;
- return p < 0 || objText[p] === '{' || objText[p] === ',';
+ const decodeQuotedKey = (from, to) => {
+ const quote = sourceObjText[from];
+ if (quote !== '"' && quote !== "'" || sourceObjText[to - 1] !== quote) return null;
+ let value = '';
+ for (let i = from + 1; i < to - 1; i += 1) {
+ const c = sourceObjText[i];
+ if (c !== '\\') { value += c; continue; }
+ i += 1;
+ if (i >= to - 1) return null;
+ const e = sourceObjText[i];
+ if (e === '\r' && sourceObjText[i + 1] === '\n') { i += 1; continue; }
+ if (e === '\n' || e === '\r' || e === '\u2028' || e === '\u2029') continue;
+ if (e === 'u') {
+ if (sourceObjText[i + 1] === '{') {
+ const close = sourceObjText.indexOf('}', i + 2);
+ if (close === -1 || close >= to - 1) return null;
+ const hex = sourceObjText.slice(i + 2, close);
+ if (!/^[0-9A-Fa-f]{1,6}$/.test(hex)) return null;
+ const cp = Number.parseInt(hex, 16);
+ if (cp > 0x10ffff) return null;
+ value += String.fromCodePoint(cp);
+ i = close;
+ continue;
+ }
+ const hex = sourceObjText.slice(i + 1, i + 5);
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return null;
+ value += String.fromCharCode(Number.parseInt(hex, 16));
+ i += 4;
+ continue;
+ }
+ if (e === 'x') {
+ const hex = sourceObjText.slice(i + 1, i + 3);
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return null;
+ value += String.fromCharCode(Number.parseInt(hex, 16));
+ i += 2;
+ continue;
+ }
+ if (e === '0') { value += '\0'; continue; }
+ const simple = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', "'": "'", '"': '"', '\\': '\\' };
+ value += Object.prototype.hasOwnProperty.call(simple, e) ? simple[e] : e;
+ }
+ return value;
};
const readValue = (colonEnd) => {
- let j = colonEnd;
- while (j < objText.length && /\s/.test(objText[j])) j += 1;
+ let j = skipSpace(objText, colonEnd);
const q = objText[j];
if (q === '"' || q === "'" || q === '`') {
- // Quoted value: scan to the matching closing quote, respecting escape sequences.
const end = scanStringEnd(j) || objText.length;
- // If the quoted string is followed (after optional whitespace) by '+', it is a concat
- // expression — fall through to unquoted scanning to capture the full span, so the
- // tightened QUOTED regex correctly classifies it as `dynamic` rather than `literal`.
- let kk = end;
- while (kk < objText.length && /\s/.test(objText[kk])) kk++;
+ let kk = skipSpace(objText, end);
if (!(kk < objText.length && objText[kk] === '+')) {
return { raw: objText.slice(j, end), valueStart: j, valueEnd: end };
}
- // Falls through to the unquoted scanning below.
}
- // Unquoted value (variable, function call, concat expression, etc.): scan to the next
- // top-level ',' or '}'.
- let d2 = 0;
+ let depth = 0;
+ let inStr = null;
let k = j;
for (; k < objText.length; k += 1) {
const cc = objText[k];
- if (cc === '{' || cc === '[' || cc === '(') d2 += 1;
- else if (cc === '}' || cc === ']' || cc === ')') { if (d2 === 0) break; d2 -= 1; }
- else if (cc === ',' && d2 === 0) break;
+ if (inStr) {
+ if (cc === '\\') { k += 1; continue; }
+ if (cc === inStr) inStr = null;
+ continue;
+ }
+ if (cc === '"' || cc === "'" || cc === '`') { inStr = cc; continue; }
+ if (cc === '{' || cc === '[' || cc === '(') depth += 1;
+ else if (cc === '}' || cc === ']' || cc === ')') { if (depth === 0) break; depth -= 1; }
+ else if (cc === ',' && depth === 0) break;
}
return { raw: objText.slice(j, k).trim(), valueStart: j, valueEnd: k };
};
- let lastMatch = null;
- const markRuntimeOverride = () => {
- if (lastMatch) lastMatch.hasRuntimeOverrideAfter = true;
+ const readPropertyName = (i) => {
+ const c = objText[i];
+ if (c === '"' || c === "'") {
+ const end = scanStringEnd(i);
+ if (end === null) return null;
+ return { name: decodeQuotedKey(i, end), end, quoted: true };
+ }
+ // From the MASK, like every other structural read: a comment is blank there, so a word inside one —
+ // `/* keep pageId */` — never reads as a property. Read from the source, it was taken for a later
+ // `pageId` and the call's real literal for an override.
+ const id = readIdentifier(objText, i);
+ return id ? { name: id.name, end: id.end, quoted: false } : null;
};
+ const skipBalancedGroup = (i, open, close) => {
+ let depth = 0;
+ let inStr = null;
+ for (let k = i; k < objText.length; k += 1) {
+ const c = objText[k];
+ if (inStr) {
+ if (c === '\\') { k += 1; continue; }
+ if (c === inStr) inStr = null;
+ continue;
+ }
+ if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }
+ if (c === open) depth += 1;
+ else if (c === close && --depth === 0) return k + 1;
+ }
+ return objText.length;
+ };
+ let depth = 0;
+ let inStr = null;
+ let lastMatch = null;
+ const markRuntimeOverride = () => { if (lastMatch) lastMatch.hasRuntimeOverrideAfter = true; };
+ const applyRuntimeProperty = (name) => { if (name === key) markRuntimeOverride(); };
+ // The offset of the last non-blank character before each offset (-1 for none), computed in one pass.
+ // Scanning back from every offset instead made a long comment — blank in the mask — quadratic: a
+ // 16,000-character comment inside one call took about 19 seconds.
+ const prevNonBlank = new Int32Array(objText.length);
+ for (let i = 0, last = -1; i < objText.length; i += 1) {
+ prevNonBlank[i] = last;
+ if (!/\s/.test(objText[i])) last = i;
+ }
for (let i = 0; i < objText.length; i += 1) {
const c = objText[i];
if (inStr) { if (c === '\\') { i += 1; continue; } if (c === inStr) inStr = null; continue; }
- if (depth === 1 && followsPropertyBoundary(i) && c === '.' && objText[i + 1] === '.' && objText[i + 2] === '.') {
- markRuntimeOverride();
- i += 2;
- continue;
- }
- if (depth === 1 && followsPropertyBoundary(i) && c === '[') {
- // A later computed property can be `["pageId"]` or `["pageType"]` at runtime. Without
- // evaluating arbitrary JavaScript, the only safe answer is to treat any explicit key before it
- // as possibly overridden; an explicit key after it still wins by normal object-literal order.
- markRuntimeOverride();
- }
- if ((c === '"' || c === "'") && depth === 1) {
- const keyEnd = scanStringEnd(i);
- if (keyEnd !== null) {
- let colon = keyEnd;
- while (colon < objText.length && /\s/.test(objText[colon])) colon += 1;
- // The lexer mask blanks string bodies but preserves delimiters, so quoted property names are
- // validated against the original source at the same offsets. Only literal "pageId"/'pageId'
- // keys are in scope; computed keys (["pageId"]) and template-literal keys are deliberately
- // left unmatched because supporting them would require evaluating property expressions.
- const rawKey = sourceObjText.slice(i, keyEnd);
- if (objText[colon] === ':' && followsPropertyBoundary(i) && (rawKey === `"${key}"` || rawKey === `'${key}'`)) {
- lastMatch = readValue(colon + 1);
+ if (depth === 1) {
+ const p = prevNonBlank[i];
+ const atBoundary = p < 0 || objText[p] === '{' || objText[p] === ',';
+ if (atBoundary) {
+ if (c === '.' && objText[i + 1] === '.' && objText[i + 2] === '.') { markRuntimeOverride(); i += 2; continue; }
+ if (c === '[') { markRuntimeOverride(); i = skipBalancedGroup(i, '[', ']') - 1; continue; }
+
+ let k = i;
+ let modifier = null;
+ if (objText[k] === '*') k = skipSpace(objText, k + 1);
+ if (objText[k] === '[') { markRuntimeOverride(); i = skipBalancedGroup(k, '[', ']') - 1; continue; }
+ let first = readPropertyName(k);
+ if (first) {
+ if ((first.name === 'get' || first.name === 'set' || first.name === 'async') && !first.quoted) {
+ modifier = first.name;
+ k = skipSpace(objText, first.end);
+ if (objText[k] === '*') k = skipSpace(objText, k + 1);
+ if (objText[k] === '[') { markRuntimeOverride(); i = skipBalancedGroup(k, '[', ']') - 1; continue; }
+ first = readPropertyName(k);
+ if (!first) continue;
+ }
+ const prop = first;
+ k = skipSpace(objText, prop.end);
+ if (objText[k] === ':') {
+ const value = readValue(k + 1);
+ if (prop.name === key) lastMatch = value;
+ i = value.valueEnd - 1;
+ continue;
+ }
+ if (objText[k] === '(') {
+ applyRuntimeProperty(prop.name);
+ i = skipBalancedGroup(k, '(', ')') - 1;
+ continue;
+ }
+ if (!modifier) applyRuntimeProperty(prop.name);
}
- i = keyEnd - 1;
- continue;
}
}
- // inStr handles quoted values (delimiters kept, bodies blanked by the mask) so a value is never
- // misread as key or bracket content when scanning for the target key. Template-literal keys are
- // out of scope for the same reason as computed keys above.
if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }
if (c === '{' || c === '[' || c === '(') { depth += 1; continue; }
if (c === '}' || c === ']' || c === ')') { depth -= 1; continue; }
- if (depth !== 1 || c !== key[0]) continue;
- if (!keyRe.test(objText.slice(i))) continue;
- // Reject false hits inside longer identifiers or value expressions; after skipping whitespace,
- // a real top-level key must follow the object's `{` or the previous property's `,`.
- if (!followsPropertyBoundary(i)) continue;
- lastMatch = readValue(i + keyRe.exec(objText.slice(i))[0].length);
}
return lastMatch;
}
@@ -180,11 +326,9 @@ function extractNavTargets(code) {
const src = String(code || '');
const callSites = blankNonCodePreservingTemplateExpressions(src);
const out = [];
- NAV_CALL.lastIndex = 0;
- let m;
- while ((m = NAV_CALL.exec(callSites)) !== null) {
- const open = m.index + m[0].length - 1; // index of the '{' that opens the object argument
- const obj = objectArgAt(callSites, open);
+ const braceMatches = matchingBraces(callSites);
+ for (const open of navigateCallObjectOpens(callSites)) {
+ const obj = objectArgAt(callSites, open, braceMatches);
if (!obj) continue;
// pv.valueStart / pv.valueEnd are relative to obj.text, which starts at `open`; adding `open`
// makes them absolute offsets into the mask and, equally, into the original source.
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index 62394b821..11cffbfa0 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -89,7 +89,7 @@ const {
rowsFromCells,
} = require('./artifact-intent.js');
const { makeGenpageCli, suppliedButBlank } = require('./genpage-cli.js');
-const { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName } = require('./form-container-match.js');
+const { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName, planOrderMoves } = require('./form-container-match.js');
const { rowOccupancy, fitsGrid, strandedRows } = require('./form-occupancy.js');
const { manifestResourceName, buildManifest, serializeManifest, parseManifestBase64, reconcilePageIds } = require('./page-manifest.js');
// MEMBERSHIP authority (the app's live sitemap) + the cross-app shared-page scan. fetchSitemap is
@@ -1058,29 +1058,23 @@ async function applyAppAiDescription(provision, spec, appId) {
}
// #583: halt precisely when the push of an app whose routing description this run changed was refused
-// because Dataverse will not take a header write until the app is PUBLISHED — rather than because of a
-// concurrent edit. Called before requireSuccessfulPush, whose generic 412 remedy (re-download and
-// rebuild) reads the same draft and fails the same way. The SDK reports that state two ways:
-// * APP_DRAFT_HEADER_NOT_WRITABLE, THROWN (see pushAppHeader) for an app that was never published. The
-// SDK's own message names the state, so no read is needed.
-// * VERSION_CONFLICT, RESOLVED (saved:false) for a published app with an unpublished header change.
-// LIVE-MEASURED: once a header change (name, description or routing description) is pushed but not
-// published, the appmodule row has a second, unpublished layer with its own version number, and the
-// SDK's next header PATCH fails with 412 although nothing changed since the fetch; a sitemap-only
-// push over the same state still succeeds, and publishing clears it. The state arises from a header
-// edit saved in Maker but not published, or from a build whose publish did not complete. A 412 is
-// relabelled only when it was the APPMODULE row's and a draft read PROVES that state (componentstate
-// 1 = Unpublished:
-// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule#BKMK_ComponentState);
-// any other outcome — a settled row, a read that fails — returns and leaves the generic halt in place.
+// because the app was never PUBLISHED: Dataverse takes no write to a draft appmodule's name, description
+// or routing description until it is, and the SDK THROWS APP_DRAFT_HEADER_NOT_WRITABLE (see
+// pushAppHeader), naming that state, so no read is needed. Called before requireSuccessfulPush, whose
+// generic remedy (re-download and rebuild) reads the same draft and fails the same way.
//
-// Whose 412 it was matters because the SDK writes an app in two PATCHes, the header then the sitemap,
-// each conditional on its own version, and names the refused one in the error's `detail`:
-// Version conflict (412) from https://contoso.crm.dynamics.com/api/data/v9.2/appmodules(<id>)
-// Version conflict (412) from https://contoso.crm.dynamics.com/api/data/v9.2/sitemaps(<id>)
-// A sitemap 412 is a concurrent sitemap edit — and by then this push's own header write has committed,
-// leaving exactly the unpublished layer the draft read finds. Relabelling it reset the copy, and
-// "publish, then re-run" then overwrote the other edit; the kept copy is what makes that re-run stop.
+// A 412 (VERSION_CONFLICT) is NOT re-explained, wherever it lands. Before cds-maker-sdk 8930278f the
+// header PATCH carried the unpublished-aware read's CONTENT token, which runs one ahead of the row while
+// a header change is unpublished, so a header write over such a change (saved in Maker, or by a build
+// whose publish did not complete) answered 412 although nothing had changed since the fetch, and this
+// halt told the operator to publish first. 8930278f sends the appmodule's ROW token. LIVE-MEASURED with
+// the vendored bundle: over another writer's unpublished header change saved BEFORE the fetch, the push
+// now saves and keeps that change; when another writer moves the row AFTER the fetch, it still answers
+// 412 — where the previous bundle answered 412 to both. So a 412 on the appmodule row is a concurrent
+// edit, as one on the sitemap always was, and takes the generic path: the copy holding this run's edits
+// is kept (discardUnrecordedEdits), which is what stops a blind re-run from overwriting the other edit.
+// Re-explaining it as "publish, then re-run" reset that copy. The row token is pinned against the real
+// bundle in app-ai-description-real-bundle.test.js.
//
// Before halting it RESETS the workspace copy to the server's. The refused push left this run's edits in
// it; once the operator publishes, the server moves, and a plain fetch then refuses to discard unpushed
@@ -1091,25 +1085,7 @@ async function haltOnUnpublishedAppHeader(provision, appId, pushed, name) {
// pushFailed reads `saved`, then the older SDK spelling `success`, then a bare error — the same reading
// requireSuccessfulPush applies, so the precise halt fires for either result shape.
const code = pushFailed(pushed) && pushed.error && pushed.error.code;
- const neverPublished = code === 'APP_DRAFT_HEADER_NOT_WRITABLE';
- if (!neverPublished) {
- if (code !== 'VERSION_CONFLICT' || !provision.dataverse || typeof provision.dataverse.get !== 'function') return;
- if (!/\/appmodules\(/i.test(`${pushed.error.detail || ''} ${pushed.error.message || ''}`)) return;
- let pending = false;
- try {
- // No `$top`: look for the unpublished layer among EVERY row the draft read returns. Measured, it
- // returns only the unpublished row while one exists, but that is not a documented guarantee, and a
- // published row read first would silently fall through to the generic halt this exists to replace.
- const res = await provision.dataverse.get(`/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=componentstate&$filter=appmoduleid eq ${appId}`);
- // `dataverse.get` RESOLVES on a non-2xx, so the status is checked explicitly.
- if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {
- pending = res.body.value.some((r) => r && r.componentstate === 1);
- }
- } catch {
- return;
- }
- if (!pending) return;
- }
+ if (code !== 'APP_DRAFT_HEADER_NOT_WRITABLE') return;
let reset = true;
try {
await provision.fetchArtifact('app', appId, { overwrite: true });
@@ -1118,11 +1094,7 @@ async function haltOnUnpublishedAppHeader(provision, appId, pushed, name) {
}
const workspace = reset ? ''
: ` First reset the workspace, which still holds this run's unpushed copy of the app (a re-run would refuse to overwrite it): ${RESET_WORKSPACE}.`;
- const why = neverPublished
- ? 'the app has never been published, and Dataverse refuses a write to its name, description or routing description until it is'
- : 'the app has an unpublished change to its name, description or routing description (saved in Maker, or by a build whose publish did not complete), and Dataverse refuses another write to those fields until it is published';
- const fix = neverPublished ? 'publish the app in Power Apps' : 'publish the app in Power Apps (or discard the change)';
- throw new BuildHalt(`push app ${name} failed: ${why}. Re-downloading reads the same draft and fails the same way: ${fix}, then re-run the build.${workspace}`, { phase: 'push', code: 'app-header-unpublished', recoverable: true, cause: pushed.error });
+ throw new BuildHalt(`push app ${name} failed: the app has never been published, and Dataverse refuses a write to its name, description or routing description until it is. Re-downloading reads the same draft and fails the same way: publish the app in Power Apps, then re-run the build.${workspace}`, { phase: 'push', code: 'app-header-unpublished', recoverable: true, cause: pushed.error });
}
// #583: push an app artifact whose header this run may have changed (the routing description). A refusal
@@ -1738,7 +1710,116 @@ async function siteMapOverLive(provision, appId, desired, opts, created) {
return siteMap;
}
+// What a DEFERRED `enrichDefaultViews(…, { publish: false })` had already saved when it failed
+// part-way. The SDK attaches that record to the error under a global-registry symbol (its
+// `readPartialEnrichment`, errors/index.ts) and looks for it on the error and its `cause` chain; this
+// reads it the same way, because the engine is handed an SDK instance and never imports the bundle.
+// Those saves are not published, so dropping the record would drop the only proof a publish is owed.
+const PARTIAL_ENRICHMENT = Symbol.for('cds-maker-sdk.partialDefaultViewEnrichment');
+function partialEnrichment(error) {
+ let current = error;
+ for (let depth = 0; current && typeof current === 'object' && depth < 8; depth += 1) {
+ const value = current[PARTIAL_ENRICHMENT];
+ if (value && typeof value === 'object') return value;
+ current = current.cause;
+ }
+ return undefined;
+}
+
+// Publish `entityTargets` (one artifact per table, `[type, id]`) and then the app, in ONE PublishXml
+// envelope when the SDK offers `publishArtifacts`. MEASURED by the SDK: a PublishXml costs ~2-2.5 s
+// even with nothing pending and parallel ones queue on the server — four one-table publishes took
+// 10-19 s, one envelope 3.6-3.8 s, and folding the app into it saved ~2 s more.
+//
+// A failed envelope fails every target with the shared error and may already have published some
+// scopes, so each failed target is published again on its own, which is what the SDK prescribes. A
+// preflight refusal (a target the workspace does not hold) throws before anything is published; the
+// per-target path then runs exactly as it did before this opt-in, and reports what it always did.
+//
+// `keepGoing` is for the halt path (settleOwedPublishes): there a target whose own publish THROWS is
+// reported and the others are still published, because nothing else will publish them. The publish
+// phase keeps the old behaviour — a thrown publish halts it — so a build reports that as it always did.
+async function publishTargets(provision, runner, concurrency, entityTargets, appTarget, warn, { keepGoing = false } = {}) {
+ const labelOf = ([type, id]) => (type === 'app' && appTarget ? appTarget[2] : `${type} ${id}`);
+ const publishOne = async ([type, id], label) => {
+ if (!keepGoing) return reportPartialPush(await provision.publishArtifact(type, id), label, warn);
+ try {
+ return reportPartialPush(await provision.publishArtifact(type, id), label, warn);
+ } catch (e) {
+ if (typeof warn === 'function') warn(`publish ${label} FAILED: ${(e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);
+ return undefined;
+ }
+ };
+ const all = appTarget ? [...entityTargets, appTarget] : entityTargets;
+ if (all.length > 1 && typeof provision.publishArtifacts === 'function') {
+ let results = null;
+ try {
+ results = await provision.publishArtifacts(all.map(([type, id]) => ({ type, id })));
+ } catch {
+ results = null;
+ }
+ if (Array.isArray(results) && results.length === all.length) {
+ const failed = [];
+ results.forEach((outcome, i) => {
+ if (outcome && outcome.publish && outcome.publish.kind === 'failed') failed.push(all[i]);
+ else reportPartialPush(outcome, labelOf(all[i]), warn);
+ });
+ for (const target of failed) await publishOne(target, labelOf(target));
+ return;
+ }
+ }
+ await runner.mapLimit(entityTargets, concurrency, (async (target) => publishOne(target, `${target[0]} ${target[1]}`)));
+ if (appTarget) await publishOne(['app', appTarget[1]], appTarget[2]);
+}
+
+// The publishes a build still OWED when it stopped: the tables whose default views its deferred
+// enrichment (4b) saved and that no completed publish phase (8) covered. `runSdkBuild` attaches them
+// to the halt (`owedPublishes`) instead of publishing them there, because only its caller knows
+// whether the halt is final: the CLI retries a transient one (a 429, a customization lock) at once,
+// the retry saves those views again and owes their publish again, and a publish sent into that
+// throttling would only fail the same way. The CLI keeps what each failed attempt owed, because a later
+// attempt can halt before the enrichment an earlier one did, until a publish phase pays it (`owedPaid`).
+//
+// On a FINAL halt the caller publishes them with this (`owed`: `[type, id]` pairs). Before the publish
+// was batched, the enrichment published each table as it went, so a build that stopped in a later phase
+// left those tables live (live-verified, before and after the batching). Without this they would wait,
+// saved but unpublished, for the full re-run that recovers from the halt — which saves them again and
+// owes their publish again — and nothing makes an operator start one.
+// Best-effort and per target: the halt is what the operator must see, so a failure is a warning, never a
+// throw, and a target that cannot be published does not keep the others back.
+async function settleOwedPublishes(provision, owed, warn) {
+ const targets = Array.isArray(owed) ? owed.filter((target) => Array.isArray(target) && target[0] && target[1]) : [];
+ if (!targets.length || !provision) return;
+ const say = (message) => { if (typeof warn === 'function') warn(`the build stopped before its publish phase; ${message}`); };
+ try {
+ await publishTargets(provision, makeRunner({ emit: () => undefined, total: 0 }), 1, targets, null, say, { keepGoing: true });
+ } catch (e) {
+ say(`publishing the default views it had already enriched FAILED: ${(e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);
+ }
+}
+
+// Every caller enters here; the phases run in runSdkBuildPhases. This wrapper only carries what the
+// deferred default-view enrichment still owes out of a halt: `owedPublishes`, and `owedPaid` when this
+// run's publish phase completed — which pays what an earlier attempt of the same build owed too, since
+// every attempt enriches the same tables (see settleOwedPublishes).
async function runSdkBuild(spec, opts = {}) {
+ // tables: entity logical -> [type, id] of a saved default view that owes its publish.
+ const owed = { tables: new Map(), paid: false };
+ try {
+ return await runSdkBuildPhases(spec, opts, owed);
+ } catch (err) {
+ if ((owed.tables.size > 0 || owed.paid) && err && typeof err === 'object') {
+ try {
+ // Not enumerable: they ride along for the caller, never into a serialized error or the journal.
+ Object.defineProperty(err, 'owedPublishes', { value: [...owed.tables.values()], enumerable: false, configurable: true, writable: true });
+ Object.defineProperty(err, 'owedPaid', { value: owed.paid, enumerable: false, configurable: true, writable: true });
+ } catch { /* a frozen error carries nothing; the re-run saves the views again and owes their publish */ }
+ }
+ throw err;
+ }
+}
+
+async function runSdkBuildPhases(spec, opts, owed) {
const { sdk, apply = false, sampleData = false, publish = false } = opts;
const emit = opts.emit || (() => undefined);
// Header-less client for solution lifecycle + artifact pushes (Dataverse rejects the
@@ -2214,53 +2295,85 @@ async function runSdkBuild(spec, opts = {}) {
const claimedTabs = new Set();
const claimedSections = new Map(); // column pointer -> Set(index)
const claimedIn = (key) => { if (!claimedSections.has(key)) claimedSections.set(key, new Set()); return claimedSections.get(key); };
+ const warn = (message) => { if (typeof opts.warn === 'function') opts.warn(message); };
+ // Every tab is matched — or created — before any section is touched, so that the tabs can be put in
+ // the layout's order first: the section pass records section pointers under their tab's index, and
+ // ordering the tabs after it would shift those.
+ const tabIndexOf = []; // want index -> deployed tab index (a hole when the tab could not be placed)
+ // A tab another tab of the layout claims by NAME is matched only by that name (claimedByAuthoredName)
+ // — the rule sections follow, and verify's rule.
+ const tabSkip = claimedByAuthoredName(new Set(def.__authoredTabNames || []));
for (let ti = 0; ti < wantTabs.length; ti++) {
const wantTab = wantTabs[ti];
// Re-read before every mutation: addElement appends and shifts sibling indices, so a pointer
// computed against an earlier snapshot can address the wrong container.
- let form = await provision.getArtifact('form', formId) || {};
- let tabMatch = matchContainer(form.tabs, wantTab, ti, { claimed: claimedTabs });
+ const form = await provision.getArtifact('form', formId) || {};
+ let tabMatch = matchContainer(form.tabs, wantTab, ti, { claimed: claimedTabs, skip: tabSkip });
if (!tabMatch) {
// A new tab is added with EMPTY form-columns, and its sections then go through the same
// per-section pass as an existing tab's: a section the deployed form already carries elsewhere
// is MOVED in, and only a genuinely new one is created. Adding the tab with its sections created
// a same-named DUPLICATE of any section it relocated — the field pass then emptied the original,
// which the vacated-section sweep spared for its claimed name.
+ //
+ // It goes where the layout places it — right after the furthest tab already matched, the rule a
+ // new section follows — rather than last, where a tab declared mid-layout used to land for good.
+ // Every tab matched so far sits before that index, so inserting there shifts none of them.
+ const at = Math.min((form.tabs || []).length, claimedTabs.size ? Math.max(...claimedTabs) + 1 : 0);
await provision.addElement('form', formId, '/tabs', Object.assign({}, wantTab, {
columns: (wantTab.columns || []).map((c) => Object.assign({}, c, { sections: [] })),
- }));
- form = await provision.getArtifact('form', formId) || {};
- tabMatch = matchContainer(form.tabs, wantTab, (form.tabs || []).length - 1, { claimed: claimedTabs });
+ }), { position: { index: at } });
+ const added = await provision.getArtifact('form', formId) || {};
+ tabMatch = matchContainer(added.tabs, wantTab, at, { claimed: claimedTabs, skip: tabSkip });
if (!tabMatch) continue; // defensive: the added tab could not be found again
}
claimedTabs.add(tabMatch.index);
- const tabPointer = '/tabs/' + tabMatch.index;
+ tabIndexOf[ti] = tabMatch.index;
const tabPatch = diffPatch(tabMatch.item, wantTab, ['label', 'expanded', 'visible']);
- if (Object.keys(tabPatch).length) await provision.updateElement('form', formId, tabPointer, tabPatch);
+ if (Object.keys(tabPatch).length) await provision.updateElement('form', formId, '/tabs/' + tabMatch.index, tabPatch);
+ }
+ // The tabs in the layout's order. The build used to leave every existing tab where it was, so a
+ // reordered layout deployed in the old order, and verify — which checked no order — passed it.
+ // Like a section's width or label, the spec wins over a tab a maker dragged: reported, never silent.
+ const placedTabs = wantTabs.map((_, ti) => ti).filter((ti) => Number.isInteger(tabIndexOf[ti]));
+ const tabPlan = planOrderMoves(placedTabs.map((ti) => tabIndexOf[ti]));
+ if (tabPlan.moves.length) {
+ for (const m of tabPlan.moves) await provision.moveElement('form', formId, '/tabs/' + m.from, '/tabs', { index: m.to });
+ placedTabs.forEach((ti, k) => { tabIndexOf[ti] = tabPlan.positions[k]; });
+ const ordered = await provision.getArtifact('form', formId) || {};
+ const names = placedTabs.map((ti) => (((ordered.tabs || [])[tabIndexOf[ti]]) || {}).name || `#${tabIndexOf[ti] + 1}`);
+ warn(`form ${def.name}: moved ${tabPlan.moves.length} tab(s) to put the tabs in the layout's order: ${names.join(', ')}.`);
+ }
+ for (let ti = 0; ti < wantTabs.length; ti++) {
+ if (!Number.isInteger(tabIndexOf[ti])) continue;
+ const wantTab = wantTabs[ti];
+ const tabIndex = tabIndexOf[ti];
+ const tabPointer = '/tabs/' + tabIndex;
+ let form;
const wantColumns = wantTab.columns || [];
for (let ci = 0; ci < wantColumns.length; ci++) {
form = await provision.getArtifact('form', formId) || {};
- let liveTab = (form.tabs || [])[tabMatch.index];
+ let liveTab = (form.tabs || [])[tabIndex];
if (!liveTab) break; // defensive: the tab vanished mid-reconcile
if (ci >= (liveTab.columns || []).length) {
// A tab that gained a form-column — e.g. a single-column form widened into two. Added EMPTY,
// for the same reason as a new tab: its sections go through the per-section pass below.
await provision.addElement('form', formId, tabPointer + '/columns', Object.assign({}, wantColumns[ci], { sections: [] }));
form = await provision.getArtifact('form', formId) || {};
- liveTab = (form.tabs || [])[tabMatch.index];
+ liveTab = (form.tabs || [])[tabIndex];
if (!liveTab || ci >= (liveTab.columns || []).length) break; // defensive: the add did not land
}
const liveColumns = liveTab.columns || [];
if (wantColumns[ci].width && liveColumns[ci].width !== wantColumns[ci].width) {
await provision.updateElement('form', formId, tabPointer + '/columns/' + ci, { width: wantColumns[ci].width });
}
+ const columnPointer = tabPointer + '/columns/' + ci;
const wantSections = wantColumns[ci].sections || [];
for (let si = 0; si < wantSections.length; si++) {
const wantSection = wantSections[si];
form = await provision.getArtifact('form', formId) || {};
- const columnPointer = tabPointer + '/columns/' + ci;
- const liveSections = (((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci];
+ const liveSections = (((form.tabs || [])[tabIndex] || {}).columns || [])[ci];
const claimedHere = claimedIn(columnPointer);
// A section may have been dragged to a different tab in Maker, or the spec may now place it
// somewhere else; either way it is still THAT section, so a form-wide name hit outranks a
@@ -2318,10 +2431,10 @@ async function runSdkBuild(spec, opts = {}) {
// for a section's columns and label — so it is reported, never silent.
if (typeof opts.warn === 'function') {
opts.warn(`form ${def.name}: moved section '${wantSection.name}' from tab '${fromTab}' (form-column ${fromColumn}) `
- + `to tab '${liveTab.name || `#${tabMatch.index + 1}`}' (form-column ${ci + 1}), where the layout places it.`);
+ + `to tab '${liveTab.name || `#${tabIndex + 1}`}' (form-column ${ci + 1}), where the layout places it.`);
}
form = await provision.getArtifact('form', formId) || {};
- const moved = ((((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci] || {}).sections || [];
+ const moved = ((((form.tabs || [])[tabIndex] || {}).columns || [])[ci] || {}).sections || [];
global = { pointer: columnPointer + '/sections/' + index, section: moved[index] || global.section };
}
// An ENGINE want has no label or position to go on: its evidence is its name and its own control,
@@ -2334,13 +2447,12 @@ async function runSdkBuild(spec, opts = {}) {
// An authored section is created where the layout places it: right after the furthest section this
// column has already matched, the index the move above uses. Appended, it landed after every
// section still to come — a new one declared mid-column, or a generated one recreated after a
- // drag in Maker — and the build never reorders what exists, so the wrong order was permanent (and
- // verify does not check order). Nothing recorded sits at or after that index, so no recorded
- // pointer shifts. An ENGINE want is still appended: the compiler puts the notes section last.
+ // drag in Maker. Nothing recorded sits at or after that index, so no recorded pointer shifts.
+ // An ENGINE want is still appended: the compiler puts the notes section last.
const at = authoredWant ? Math.min(liveList.length, claimedHere.size ? Math.max(...claimedHere) + 1 : 0) : null;
await provision.addElement('form', formId, columnPointer + '/sections', stripRows(wantSection), ...(at === null ? [] : [{ position: { index: at } }]));
form = await provision.getArtifact('form', formId) || {};
- const addedList = ((((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci] || {}).sections || [];
+ const addedList = ((((form.tabs || [])[tabIndex] || {}).columns || [])[ci] || {}).sections || [];
const addedIdx = at === null ? addedList.length - 1 : at;
claimedHere.add(addedIdx);
if (authoredWant) sectionTargets[wantSection.name] = { pointer: columnPointer + '/sections/' + addedIdx, name: (addedList[addedIdx] || {}).name };
@@ -2388,6 +2500,22 @@ async function runSdkBuild(spec, opts = {}) {
if (Object.keys(patch).length) await provision.updateElement('form', formId, pointer, patch);
if (reflow) await repackSectionRows(formId, pointer, Number(patch.columns));
}
+ // The authored sections of this form-column in the layout's order. Moves and creations above land
+ // after the sections already matched, but a section that was ALREADY here in a different order
+ // stayed there: a reordered layout deployed in the old order, and verify checked no order, so it
+ // passed. Ordered once the column's sections are all matched and before any later column can take
+ // a section from this one; only this column's recorded targets live in this array, so theirs are
+ // the only pointers the moves shift. An ENGINE section is not the author's and keeps its place.
+ const sectionListPointer = columnPointer + '/sections';
+ const orderedWants = wantSections.filter((s) => !isEngineOwnedSection(s) && sectionTargets[s.name]
+ && String(sectionTargets[s.name].pointer || '').startsWith(sectionListPointer + '/'));
+ const sectionPlan = planOrderMoves(orderedWants.map((s) => Number(sectionTargets[s.name].pointer.slice(sectionListPointer.length + 1))));
+ if (sectionPlan.moves.length) {
+ for (const m of sectionPlan.moves) await provision.moveElement('form', formId, sectionListPointer + '/' + m.from, sectionListPointer, { index: m.to });
+ orderedWants.forEach((s, k) => { sectionTargets[s.name].pointer = sectionListPointer + '/' + sectionPlan.positions[k]; });
+ warn(`form ${def.name}: moved ${sectionPlan.moves.length} section(s) in tab '${liveTab.name || `#${tabIndex + 1}`}' (form-column ${ci + 1}) `
+ + `to put them in the layout's order: ${orderedWants.map((s) => sectionTargets[s.name].name || s.name).join(', ')}.`);
+ }
}
}
return sectionTargets;
@@ -2689,19 +2817,22 @@ async function runSdkBuild(spec, opts = {}) {
const section = sectionAt(form, sectionPointer) || {};
const rows = section.rows || [];
const rowIndex = firstAppendRowThatFits(rows, wantCell, section.columns);
- while ((section.rows || []).length < rowIndex) {
- await provision.addElement('form', formId, sectionPointer + '/rows', { cells: [] });
- section.rows = [...(section.rows || []), { cells: [] }];
- }
- if (rowIndex < rows.length) {
+ // Counted before any add, and locally: `rows` may alias the stored artifact (then every add grows
+ // it) or be a copy (then none does), so neither its length nor a re-assigned `section.rows` can say
+ // how many rows exist — re-assigning them added a phantom row wherever they alias.
+ const priorRowCount = rows.length;
+ if (rowIndex < priorRowCount) {
await provision.updateElement('form', formId, sectionPointer + '/rows/' + rowIndex,
{ cells: [...(rows[rowIndex].cells || []), wantCell] });
return;
}
+ for (let rowCount = priorRowCount; rowCount < rowIndex; rowCount += 1) {
+ await provision.addElement('form', formId, sectionPointer + '/rows', { cells: [] });
+ }
await provision.addElement('form', formId, sectionPointer + '/rows', { cells: [wantCell] });
};
- const placeFieldInSection = async (formId, logical, wantCell, target, vacated, rawSpan) => {
+ const placeFieldInSection = async (formId, logical, wantCell, target, vacated, rawSpan, formName) => {
let form = await provision.getArtifact('form', formId) || {};
const targetPointer = resolveSectionPointer(form, target);
const existing = findFieldCellLocation(form, logical);
@@ -2762,13 +2893,22 @@ async function runSdkBuild(spec, opts = {}) {
// reading `.length` afterwards would yield the POST-add count and target a row one past the end,
// which silently skips the move (the `if (!row) return` guard below).
const priorRowCount = targetRows.length;
- let rowIndex = firstAppendRowThatFits(targetRows, wantCell, targetSection.columns);
- while (rowIndex >= priorRowCount && ((targetSection.rows || []).length <= rowIndex)) {
- // Either the section this run just created has no row yet, or all existing rows whose carried
- // row-span reservations leave enough capacity are behind us. The SDK accepts a row with an
- // empty cells array and serializes it correctly, so seed rows until the chosen target exists.
+ // The row is sized for the cell being MOVED, as it will be in the destination — not for the
+ // compiled one. A span the author did not declare is kept from the live cell, so the compiled cell
+ // (no span: "no opinion") under-states it: a maker's colspan-2 field moved into a one-column
+ // section was placed as if it were one column wide and then kept its colspan 2, overflowing that
+ // section on every apply. A kept colspan wider than the destination grid is clamped to the grid —
+ // a cell cannot be wider than the grid it sits in, and it is the clamp a grid narrowing applies
+ // (`rowsFromCells`).
+ const landing = landingSpans(cellAt(form, existing) || {}, wantCell, rawSpan, targetSection);
+ let rowIndex = firstAppendRowThatFits(targetRows, { ...wantCell, colspan: landing.colspan, rowspan: landing.rowspan }, targetSection.columns);
+ // Either the section this run just created has no row yet, or all existing rows whose carried
+ // row-span reservations leave enough capacity are behind us. The SDK accepts a row with an empty
+ // cells array and serializes it correctly, so seed rows until the chosen target exists. Counted
+ // locally: whether `targetSection` aliases the stored artifact is the SDK's business, and
+ // re-assigning its `rows` to track the count added a phantom row wherever it does.
+ for (let rowCount = priorRowCount; rowCount <= rowIndex; rowCount += 1) {
await provision.addElement('form', formId, targetPointer + '/rows', { cells: [] });
- targetSection.rows = [...(targetSection.rows || []), { cells: [] }];
}
form = await provision.getArtifact('form', formId) || {};
const from = findFieldCellLocation(form, logical);
@@ -2787,7 +2927,40 @@ async function runSdkBuild(spec, opts = {}) {
// possible stranded-row removal) invalidated every pointer computed above.
const settledForm = await provision.getArtifact('form', formId) || {};
const settled = findFieldCellLocation(settledForm, logical);
- if (settled) await convergeCellSpans(formId, settledForm, settled, wantCell, rawSpan);
+ if (!settled) return;
+ if (landing.narrowed) {
+ // Written through the span-convergence path as if declared, so it is applied exactly like an
+ // authored narrowing (a narrowing never overflows its row). Reported: the build changed the
+ // width of a cell whose width the spec leaves to the maker.
+ await convergeCellSpans(formId, settledForm, settled, { ...wantCell, colspan: landing.colspan }, { ...(rawSpan || {}), colspan: landing.colspan });
+ if (typeof opts.warn === 'function') {
+ const destination = (sectionAt(settledForm, settled.sectionPointer) || {}).name || settled.sectionPointer;
+ opts.warn(`form ${formName}: '${logical}' spanned ${landing.liveColspan} columns, wider than the ${landing.gridWidth}-column `
+ + `section '${destination}' the layout moves it to, so it now spans ${landing.colspan}. Declare its colspan to choose the width.`);
+ }
+ return;
+ }
+ await convergeCellSpans(formId, settledForm, settled, wantCell, rawSpan);
+ };
+
+ // The spans a cell MOVING into `section` will have there: a span the author declared (clamped to
+ // the section's grid, as spanForLiveSection clamps it), otherwise the one the live cell already
+ // carries — with an undeclared colspan wider than the grid clamped to it. `narrowed` says the clamp
+ // changed a width the spec did not declare, which the caller writes and reports.
+ const landingSpans = (liveCell, wantCell, rawSpan, section) => {
+ const gridWidth = Math.max(1, Math.min(4, Number(section && section.columns) || 1));
+ const liveColspan = Math.max(1, Number(liveCell && liveCell.colspan) || 1);
+ const liveRowspan = Math.max(1, Number(liveCell && liveCell.rowspan) || 1);
+ const declaredColspan = spanForLiveSection('colspan', wantCell, rawSpan, section);
+ const declaredRowspan = spanForLiveSection('rowspan', wantCell, rawSpan, section);
+ const colspan = declaredColspan !== undefined ? declaredColspan : Math.min(liveColspan, gridWidth);
+ return {
+ colspan,
+ rowspan: declaredRowspan !== undefined ? declaredRowspan : liveRowspan,
+ liveColspan,
+ gridWidth,
+ narrowed: declaredColspan === undefined && colspan < liveColspan,
+ };
};
const reconcileForm = async (formId, def) => {
@@ -2824,7 +2997,7 @@ async function runSdkBuild(spec, opts = {}) {
// stand-in that reconcile never deploys.
const rawSpans = def.__fieldSpans || {};
for (const logical of want) {
- await placeFieldInSection(formId, logical, wantCellByLogical[logical], sectionTargets[declaredSection[logical]], vacatedSections, rawSpans[logical]);
+ await placeFieldInSection(formId, logical, wantCellByLogical[logical], sectionTargets[declaredSection[logical]], vacatedSections, rawSpans[logical], def.name);
}
await addSubgrids(formId, def.__subgrids);
// Re-assert per-control attributes (read-only / hidden) on fields that were ALREADY on the form.
@@ -3293,6 +3466,21 @@ async function runSdkBuild(spec, opts = {}) {
// them with only the primary column). One step per enrichable entity; opt out per-entity with
// enrichDefaultViews:false. Author-declared views (also querytype 0) are excluded by id; the SDK
// owns the default-view resolution + fetch/setViewColumns/push/publish mechanics.
+ //
+ // When this build publishes at the end (phase 8), the enrichment's own publish is deferred to that
+ // phase's single envelope: every enriched table used to be published twice, and each PublishXml
+ // costs ~2-2.5 s even with nothing pending (measured by the SDK). The deferred call returns the
+ // views whose saves still owe that publish (`pendingPublish`), and a call that fails part-way
+ // carries the same record on its error. Without --publish nothing is deferred: the SDK publishes
+ // the enrichment itself, as before. What is still owed when a phase halts leaves with the halt
+ // (runSdkBuild), and the caller publishes it once no retry follows (settleOwedPublishes).
+ const deferDefaultViewPublish = has('publish') && publish;
+ const recordOwed = (logical, record) => {
+ for (const pending of (record && record.pendingPublish) || []) {
+ const first = (pending.artifacts || [])[0];
+ if (first && first.id && !owed.tables.has(logical)) owed.tables.set(logical, [first.type || 'view', first.id]);
+ }
+ };
if (has('views')) {
const authorViewIds = Object.values(result.created.views || {}).filter(Boolean);
for (const e of spec.entities || []) {
@@ -3300,8 +3488,26 @@ async function runSdkBuild(spec, opts = {}) {
const logical = e.schemaName.toLowerCase();
const cols = defaultViewColumns(spec, e);
await runner.run('views', `enrich default views for ${logical}`, async () => {
- const { updated } = await provision.enrichDefaultViews(logical, cols, { excludeViewIds: authorViewIds });
- return updated;
+ if (!deferDefaultViewPublish) {
+ const { updated } = await provision.enrichDefaultViews(logical, cols, { excludeViewIds: authorViewIds });
+ return updated;
+ }
+ try {
+ const record = await provision.enrichDefaultViews(logical, cols, { excludeViewIds: authorViewIds, publish: false });
+ recordOwed(logical, record);
+ // A view whose push was REFUSED — the SDK answers a concurrent edit's 412 by value, not with a
+ // throw — saved nothing, so it fails the step as any other refused push does, rather than leave
+ // the table looking enriched. That is also what lets the CLI treat a completed publish phase as
+ // paying an earlier attempt's debt (`owedPaid`): every attempt that gets past this step has saved
+ // each table's default views again, so it owes, and publishes, the same tables. Without --publish
+ // the SDK publishes the enrichment itself and reports no per-view results, so a refusal there
+ // stays as silent as it always was.
+ for (const pushed of record.results || []) requireSuccessfulPush(pushed, `default view ${pushed && pushed.id} of ${logical}`);
+ return record.updated;
+ } catch (err) {
+ recordOwed(logical, partialEnrichment(err));
+ throw err;
+ }
});
}
}
@@ -4396,7 +4602,7 @@ async function runSdkBuild(spec, opts = {}) {
for (const p of implemented) {
const key = keyOf(p);
if (keyToId.has(key) || !navTargets.has(key)) continue; // only ABSENT targets need pre-minting
- const up = await genpageCli.upload({ appId: result.created.app, codeFile: canonicalPath(p), name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources });
+ const up = await genpageCli.upload({ appId: result.created.app, codeFile: canonicalPath(p), name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources, model: p.model });
keyToId.set(key, up.pageId);
result.created.pages[key] = up.pageId;
mintedKeys.add(key);
@@ -4434,7 +4640,9 @@ async function runSdkBuild(spec, opts = {}) {
// canonical file content.
const deployedBytes = isNav ? deployment.get(key) : fs.readFileSync(canonicalPath(p), 'utf8');
const codeFile = isNav ? writeStagingFile(stagingDir, key, deployment.get(key)) : canonicalPath(p);
- const up = await genpageCli.upload({ appId: result.created.app, pageId: requestedId, codeFile, name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources });
+ // `model` rides along because pac stores whatever `--model` an upload sends: re-uploading without it
+ // wiped a deployed page's model id to "". A downloaded spec carries it (pages[].model).
+ const up = await genpageCli.upload({ appId: result.created.app, pageId: requestedId, codeFile, name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources, model: p.model });
// I7: an UPDATE (requestedId set) must return the SAME id, else a resolved sibling could point at
// a stale target. Case-insensitive (Dataverse may echo a differently-cased GUID).
if (requestedId && String(up.pageId).toLowerCase() !== String(requestedId).toLowerCase()) throw new BuildHalt(`page "${p.name}" UPDATE returned a different id (${up.pageId} != ${requestedId}) — refusing to finalize with an inconsistent target`, { phase: 'pages', code: 'pages-update-identity-mismatch', recoverable: false });
@@ -5097,9 +5305,15 @@ async function runSdkBuild(spec, opts = {}) {
// halts the phase. `chartsToPublish` is populated at exactly the two points that put a chart in
// the workspace, and keyed by entity because publishing is per-entity.
for (const [k, cid] of chartsToPublish) { if (cid && !seen.has(k)) { seen.add(k); perEntity.push(['chart', cid]); } }
- await runner.mapLimit(perEntity, concurrency, (async ([type, id]) => reportPartialPush(await provision.publishArtifact(type, id), `${type} ${id}`, opts.warn)));
- if (result.created.app) reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);
+ // Tables whose enriched default views still owe their publish (4b), when nothing above names them.
+ for (const [k, target] of owed.tables) { if (!seen.has(k)) { seen.add(k); perEntity.push(target); } }
+ const appTarget = result.created.app ? ['app', result.created.app, `app ${(spec.app && spec.app.name) || result.created.app}`] : null;
+ await publishTargets(provision, runner, concurrency, perEntity, appTarget, opts.warn);
});
+ // Paid. A target that failed to publish was reported above, and the build is idempotent, so its
+ // re-run publishes it; a halt from here on owes nothing more, nor does an earlier attempt's.
+ owed.paid = true;
+ owed.tables.clear();
}
// 8b. AI feature re-issue + re-confirmation. An app-scope setting write is a NO-OP on a freshly
@@ -5195,4 +5409,4 @@ async function runSdkBuild(spec, opts = {}) {
return result;
}
-module.exports = { runSdkBuild, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
+module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.js
index 9227dc836..4a765b4b3 100644
--- a/plugins/model-apps/scripts/lib/sdk-http-client.js
+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js
@@ -10,7 +10,7 @@
// (ensureToken) or when the underlying transport itself fails — a network/timeout error (res.error)
// after exhausting retries, or at once for a write that must not be re-sent (see `call`). We never
// throw purely on a non-2xx HTTP status.
-const { dataverseOrigin, getAuthToken, makeRequest } = require('./dataverse-auth.js');
+const { dataverseOrigin, getAuthToken, makeRequest, tokenFailureMessage } = require('./dataverse-auth.js');
// How Dataverse reports that SQL Server chose a request's transaction as a deadlock VICTIM and rolled
// it back. Two live captures, both HTTP 500 (a process-flow delete during a teardown, and PublishXml):
@@ -268,7 +268,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
if (!token) {
token = getToken(clean, options);
if (!token) {
- throw new Error(`Failed to get Azure CLI token for ${clean}. Run 'az login' first.`);
+ throw new Error(tokenFailureMessage(clean, `Failed to get Azure CLI token for ${clean}. Run 'az login' first.`));
}
}
return token;
@@ -356,7 +356,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
// rejected bearer value and convert a refresh path into a guaranteed second 401.
token = getToken(clean, { fresh: true });
if (!token) {
- throw new Error(`Failed to refresh Azure CLI token for ${clean}. Run 'az login' first.`);
+ throw new Error(tokenFailureMessage(clean, `Failed to refresh Azure CLI token for ${clean}. Run 'az login' first.`));
}
continue;
}
diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.js
index 4a805274f..a36375cbc 100644
--- a/plugins/model-apps/scripts/lib/sdk-teardown.js
+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js
@@ -15,6 +15,7 @@
// SDK reports them and the owner decides. Runs AFTER the app so the app's own
// sitemap reference is already gone and the only dependency the platform can
// still report is a GENUINE other consumer; such a page is SKIPPED, not deleted.
+// When this step fails, runTeardown keeps the manifest (step 9) for a re-run.
// 2. dashboards — systemform (type 0) rows, pinned as app components
// 3. commands — appactions per entity (they reference the web-resource JS; delete first).
// The SDK's command delete is ENTITY-keyed (removes every appaction on that
@@ -294,7 +295,8 @@ const KIND_HANDLERS = {
async resolve(sdk, target) {
if (typeof sdk.queryRecords !== 'function') return [];
// The manifest lives in a web resource this same teardown deletes later (web-resources phase),
- // so it is still readable here.
+ // so it is still readable here. runTeardown keeps it when this step fails, so a re-run can read
+ // it again.
let manifest = null;
try {
const rows = await sdk.queryRecords('webresource', {
@@ -303,10 +305,16 @@ const KIND_HANDLERS = {
top: 1,
});
if (rows && rows[0] && rows[0].content) manifest = parseManifestBase64(rows[0].content);
- } catch {
- // No manifest readable → nothing provably ours → delete nothing. Leaving a row behind is
- // recoverable; deleting a page we cannot prove we authored is not.
- return [];
+ } catch (err) {
+ // A failed read deletes nothing — a page we cannot prove we authored is never deleted — but it
+ // is a FAILED step, not "no pages". Read as an empty resolution, the step reported clean, the
+ // web-resources phase then deleted the manifest, and every later run found nothing: the pages
+ // stayed behind for good. As a failure, the manifest and the solution are kept for a re-run.
+ // `failClosed` stops runTeardown's not-found shortcut from turning a proxy's 404 back into "none".
+ // (No manifest row at all is different: the app never recorded a page, so [] is the truth.)
+ const e = new Error(`could not read the page manifest '${target.manifestName}' (${errMsg(err)}) — no page is deleted; re-run the teardown`);
+ e.failClosed = true;
+ throw e;
}
const authored = [];
for (const p of (manifest && manifest.pages) || []) {
@@ -317,14 +325,19 @@ const KIND_HANDLERS = {
if (!authored.length) return [];
// Only pages that still exist (a re-run, or a maker deleting one by hand, is not a failure).
+ let rows;
try {
const filter = authored.map((a) => `uxagentprojectid eq ${String(a.id).toLowerCase()}`).join(' or ');
- const rows = await sdk.queryRecords('uxagentproject', { select: ['uxagentprojectid'], filter });
- const live = new Set((rows || []).map((r) => String(r.uxagentprojectid).toLowerCase()));
- return authored.filter((a) => live.has(String(a.id).toLowerCase()));
- } catch {
- return [];
+ rows = await sdk.queryRecords('uxagentproject', { select: ['uxagentprojectid'], filter });
+ } catch (err) {
+ // Same as the manifest read above: not being able to look deletes nothing and fails the step,
+ // so the manifest naming these pages survives for a re-run.
+ const e = new Error(`could not check which of the ${authored.length} page(s) in '${target.manifestName}' still exist (${errMsg(err)}) — no page is deleted; re-run the teardown`);
+ e.failClosed = true;
+ throw e;
}
+ const live = new Set((rows || []).map((r) => String(r.uxagentprojectid).toLowerCase()));
+ return authored.filter((a) => live.has(String(a.id).toLowerCase()));
},
// Delete ONLY the project row. Its `uxagentprojectfile` children go with it: the
// uxagentproject_uxagentprojectfile_uxagentprojectid relationship is CascadeConfiguration
@@ -1262,10 +1275,24 @@ async function runTeardown(spec, opts = {}, deps = {}) {
}
const result = { ok: true, dryRun: false, deleted: {}, skipped: [], errors: [] };
+ // The page manifest is the only record of which generative pages this app authored (see the genpage
+ // handler), and it is deleted in the web-resources phase, well after the pages step. When that step
+ // failed, deleting the manifest anyway left a re-run nothing to find the pages by: it resolved none,
+ // reported success, released the workspace's teardown record, and the pages stayed behind for good.
+ // So the manifest is kept until a run gets through the pages step. Matched by name, so a declared web
+ // resource with the manifest's name is kept as well.
+ const pageManifests = new Set(plan.filter((p) => p.kind === 'genpage').map((p) => String(p.target.manifestName).toLowerCase()));
+ let pagesFailed = false;
let n = 0;
for (const step of plan) {
const myN = (n += 1);
emit({ phase: step.phase, status: 'start', label: step.label, n: myN, total });
+ if (step.kind === 'webResource' && pagesFailed && pageManifests.has(String(step.target.name).toLowerCase())) {
+ const why = `${step.label} (kept — the generative pages step failed, and a re-run needs this manifest to find the pages this app authored; it is deleted once that step succeeds)`;
+ result.skipped.push(why);
+ emit({ phase: step.phase, status: 'skip', skip: 'kept', label: why, n: myN, total });
+ continue;
+ }
// The solution goes last, and only once every step before it succeeded. It is how a re-run tells
// this app's dashboards from same-named ones elsewhere (the dashboard resolver): deleted after a
// failed step, it left the retry nothing to prove them by, so the retry kept them — and their
@@ -1324,6 +1351,7 @@ async function runTeardown(spec, opts = {}, deps = {}) {
const message = errMsg(err);
result.errors.push({ step: step.label, message });
emit({ phase: step.phase, status: 'error', label: step.label, n: myN, total, detail: message });
+ if (step.kind === 'genpage') pagesFailed = true;
// Best-effort continue-on-error is right for the steps AFTER the dependency root is gone — one
// undeletable view should not strand the rest. It is WRONG for the root itself (#587 item 5):
// tables, forms, views and charts are COMPONENTS of the app module, so continuing past a failed
diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.js
index 1e6ed4210..0d55a3c1e 100644
--- a/plugins/model-apps/scripts/lib/source-literals.js
+++ b/plugins/model-apps/scripts/lib/source-literals.js
@@ -26,6 +26,23 @@
const EXPR_START_PUNCT = new Set(['(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '<', '>', '~', '^', '\n']);
const EXPR_START_WORDS = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'case', 'do', 'else', 'yield', 'await']);
+// ECMAScript LineTerminator is LF, CR, LS and PS; CRLF is one terminator. LS/PS also
+// terminate // comments and regex literals, but since ES2019 they are legal inside string
+// literals. See https://tc39.es/ecma262/#sec-line-terminators and
+// https://tc39.es/ecma262/#sec-literals-string-literals.
+function isLineTerminator(ch) {
+ return ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029';
+}
+
+function lineTerminatorStart(src, from) {
+ for (let i = from; i < src.length; i += 1) if (isLineTerminator(src[i])) return i;
+ return -1;
+}
+
+function isRawStringBreak(ch) {
+ return ch === '\n' || ch === '\r';
+}
+
function prevSignificant(src, i) {
for (let j = i - 1; j >= 0; j -= 1) {
if (!/\s/.test(src[j])) return { ch: src[j], index: j };
@@ -345,7 +362,7 @@ function skipTrivia(src, j) {
const c = src[j];
const n = src[j + 1];
if (c === '/' && n === '/') {
- const end = src.indexOf('\n', j);
+ const end = lineTerminatorStart(src, j);
return end === -1 ? src.length : end;
}
if (c === '/' && n === '*') {
@@ -356,7 +373,7 @@ function skipTrivia(src, j) {
for (let k = j + 1; k < src.length; k += 1) {
if (src[k] === '\\') { k += 1; continue; }
if (src[k] === c) return k + 1;
- if (src[k] === '\n' && c !== '`') return j; // not a string after all
+ if (isRawStringBreak(src[k]) && c !== '`') return j; // not a string after all
}
return src.length;
}
@@ -463,43 +480,144 @@ function blankLiterals(code, opts) {
// as the start of a regex that swallowed the closing `}`, and the apostrophe in `${<p>it's</p>}` as a
// string. Either way the template never ended, and the page's `export default` vanished with it.
// Otherwise it returns src.length.
-function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTagEnd = null, untilCloseBrace = false, onEnd = null } = {}) {
+function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTagEnd = null, untilCloseBrace = false, onEnd = null, keep = null } = {}) {
+ // `out` is the literal view every position judgment below reads: comments, strings, regexes, JSX
+ // text AND whole template bodies blanked. `keep`, when given, is the executable view built in the
+ // same pass (blankNonCodePreservingTemplateExpressions): blanked exactly like `out`, except that a
+ // template's `${…}` bodies stay code.
const blank = (from, to) => {
- for (let k = Math.max(0, from); k < to && k < src.length; k += 1) if (src[k] !== '\n') out[k] = ' ';
+ for (let k = Math.max(0, from); k < to && k < src.length; k += 1) {
+ if (isLineTerminator(src[k])) continue;
+ out[k] = ' ';
+ if (keep) keep[k] = ' ';
+ }
+ };
+ const blankLiteralViewOnly = (from, to) => {
+ for (let k = Math.max(0, from); k < to && k < src.length; k += 1) if (!isLineTerminator(src[k])) out[k] = ' ';
+ };
+ // A template literal from its opening backtick at `open` to its closing one at `close`, whose `${…}`
+ // bodies (`expressions`) were lexed by frames of their own. Its TEXT — the `${` and `}` delimiters
+ // included — is blanked in both views. Its bodies are blanked in the literal view only (no
+ // declaration lives in one), and there only around the templates each body closed itself: those are
+ // blank already. Blanking the whole body at every level instead cost one pass per enclosing template
+ // over every nested character — quadratic in the nesting depth. In `keep` a body's closing `}`
+ // becomes `;`, so two bodies separated only by blanked text cannot read as one call:
+ // `${Xrm.Navigation.navigateTo} text ${({ pageType: "generative", pageId: "PAGEREF_x" })}`
+ // blanked to spaces would present `navigateTo ({ ... })`.
+ const closeTemplate = (open, close, expressions, closedBy) => {
+ let from = open + 1;
+ for (const e of expressions) {
+ blank(from, e.start);
+ let k = e.start;
+ for (const [o, c] of e.closed) { blankLiteralViewOnly(k, o + 1); k = c; }
+ blankLiteralViewOnly(k, e.end);
+ if (e.end >= close) { from = close; break; } // an unterminated body ran to the end
+ out[e.end] = ' ';
+ if (keep) keep[e.end] = ';';
+ from = e.end + 1;
+ }
+ blank(from, close);
+ closedBy.push([open, close]);
};
- let mode = 'code';
- let jsxDepth = 0; // open JSX elements in the CURRENT expression frame
- let angleDepth = 0; // nested < > inside a tag's type arguments
- const frames = []; // JSX-expression frames: { returnMode, braceDepth, savedJsxDepth }
- let braceDepth = 0; // `{` opened in plain code inside a `${…}` body (untilCloseBrace)
- let unterminated = false; // a string, regex, template, comment or closing tag ran off the end
+ // The lexer's state is a STACK OF FRAMES, not the call stack. A CODE frame lexes code — the module,
+ // or one `${…}` body — and a TEMPLATE frame reads a template literal's text around its bodies. Each
+ // body used to be lexed by a recursive call, which overflowed the call stack a little over a thousand
+ // templates deep: page source is untrusted input, so its nesting now costs heap, at any depth. A code
+ // frame carries its own lexer state, the templates it closed itself (`closed`), and — for a body —
+ // the `${…}` record it fills in (`bodyOf`).
+ const codeFrame = (bodyOf) => ({
+ kind: 'code',
+ mode: 'code',
+ jsxDepth: 0, // open JSX elements in the CURRENT expression frame
+ angleDepth: 0, // nested < > inside a tag's type arguments
+ frames: [], // JSX-expression frames: { returnMode, braceDepth, savedJsxDepth }
+ braceDepth: 0, // `{` opened in plain code inside a `${…}` body (untilCloseBrace)
+ unterminated: false, // a string, regex, template, comment or closing tag ran off the end
+ untilCloseBrace: !!bodyOf,
+ bodyOf,
+ closed: [],
+ });
+ const root = codeFrame(null);
+ root.untilCloseBrace = untilCloseBrace;
+ const stack = [root];
let i = start;
+ // Only the module frame reports regex and JSX-tag ends: a body's are inside a template literal, which
+ // the checks that listen for them read as one inert token.
+ const reportRegexEnd = (fr, j) => { if (onRegexEnd && fr === root) onRegexEnd(j); };
+ const reportJsxTagEnd = (fr, j) => { if (onJsxTagEnd && fr === root) onJsxTagEnd(j); };
- const leaveJsxExpr = () => {
- const f = frames.pop();
- if (!f) { mode = 'code'; return; }
+ const leaveJsxExpr = (fr) => {
+ const f = fr.frames.pop();
+ if (!f) { fr.mode = 'code'; return; }
// Restore the enclosing element depth. It must be per-frame: in
// <div>{items.map(x => { return (<section>…</section>); })}</div>
// the `<div>` is open across the whole expression, but once `</section>` closes we are back in
// CODE (inside the arrow body), not in the div's text run. A single global counter left the
// lexer in jsxText for the rest of the file and blanked the real `export default`.
- jsxDepth = f.savedJsxDepth;
- mode = f.returnMode;
+ fr.jsxDepth = f.savedJsxDepth;
+ fr.mode = f.returnMode;
+ };
+ const enterJsxExpr = (fr, returnMode) => {
+ fr.frames.push({ returnMode, braceDepth: 0, savedJsxDepth: fr.jsxDepth });
+ fr.jsxDepth = 0;
+ fr.mode = 'code';
+ };
+ // A template literal starts at the backtick `i`: its text is read by a frame of its own.
+ const openTemplate = () => {
+ stack.push({ kind: 'template', open: i, expressions: [] });
+ i += 1;
+ };
+ // The template frame `tf` ends at `end` — its closing backtick, or src.length when none closes it —
+ // and the code frame that opened it resumes right after it.
+ const endTemplate = (tf, end) => {
+ stack.pop();
+ const opener = stack[stack.length - 1];
+ if (end >= src.length) opener.unterminated = true;
+ closeTemplate(tf.open, end, tf.expressions, opener.closed);
+ i = Math.min(end + 1, src.length);
};
- const enterJsxExpr = (returnMode) => {
- frames.push({ returnMode, braceDepth: 0, savedJsxDepth: jsxDepth });
- jsxDepth = 0;
- mode = 'code';
+ // The `${…}` body `fr` ends at `end` — its closing `}`, or src.length — and its template's text
+ // resumes right after it.
+ const endBody = (fr, end) => {
+ fr.bodyOf.end = end;
+ fr.bodyOf.closed = fr.closed;
+ stack.pop();
+ i = end < src.length ? end + 1 : src.length;
};
- while (i < src.length) {
+ for (;;) {
+ const fr = stack[stack.length - 1];
+
+ if (fr.kind === 'template') {
+ // Template text: only an escape, the closing backtick and a `${` mean anything here.
+ if (i >= src.length) { endTemplate(fr, src.length); continue; }
+ const t = src[i];
+ if (t === '\\') { i += 2; continue; }
+ if (t === '`') { endTemplate(fr, i); continue; }
+ if (t === '$' && src[i + 1] === '{') {
+ const body = { start: i + 2, end: src.length, closed: [] };
+ fr.expressions.push(body);
+ stack.push(codeFrame(body));
+ i += 2;
+ continue;
+ }
+ i += 1;
+ continue;
+ }
+
+ if (i >= src.length) {
+ if (fr.bodyOf) { endBody(fr, src.length); continue; }
+ // Where the lexer stopped: a complete module ends in plain code, with nothing left open.
+ if (onEnd) onEnd({ open: fr.unterminated || fr.mode !== 'code' || fr.frames.length > 0 });
+ return src.length;
+ }
const c = src[i];
const n = src[i + 1];
- if (mode === 'code') {
+ if (fr.mode === 'code') {
if (c === '/' && n === '/') {
- const end = src.indexOf('\n', i);
+ const end = lineTerminatorStart(src, i);
blank(i, end === -1 ? src.length : end);
if (onComment) onComment(i, end === -1 ? src.length : end);
i = end === -1 ? src.length : end;
@@ -508,7 +626,7 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
if (c === '/' && n === '*') {
const end = src.indexOf('*/', i + 2);
const stop = end === -1 ? src.length : end + 2;
- if (end === -1) unterminated = true;
+ if (end === -1) fr.unterminated = true;
blank(i, stop);
if (onComment) onComment(i, stop);
i = stop;
@@ -519,10 +637,10 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
for (; j < src.length; j += 1) {
if (src[j] === '\\') { j += 1; continue; }
if (src[j] === c) break;
- if (src[j] === '\n') { j = -1; break; } // a string cannot span a raw newline
+ if (isRawStringBreak(src[j])) { j = -1; break; } // a string cannot span a raw LF/CR
}
if (j === -1) { i += 1; continue; }
- if (j >= src.length) unterminated = true;
+ if (j >= src.length) fr.unterminated = true;
blank(i + 1, j);
i = Math.min(j + 1, src.length);
continue;
@@ -534,10 +652,7 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
// ended `[${rows.map((r) => `{"id":"${r.id}"}`).join(",")}]` at the `}` in the nested
// template's TEXT, and everything up to the next backtick — `export default` included — was
// misread, so a complete page failed as truncated and later nav calls went unseen.
- const j = scanTemplateLiteral(src, i, out, onComment).end;
- if (j >= src.length) unterminated = true;
- blank(i + 1, j);
- i = Math.min(j + 1, src.length);
+ openTemplate();
continue;
}
// Position is judged on the blanked output, not the raw source: every comment before `i` is
@@ -554,42 +669,45 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
let inClass = false;
for (; j < src.length; j += 1) {
if (src[j] === '\\') { j += 1; continue; }
- if (src[j] === '\n') { j = -1; break; }
+ if (isLineTerminator(src[j])) { j = -1; break; }
if (src[j] === '[') inClass = true;
else if (src[j] === ']') inClass = false;
else if (src[j] === '/' && !inClass) break;
}
if (j === -1) { i += 1; continue; }
- if (j >= src.length) unterminated = true;
- else if (onRegexEnd) onRegexEnd(j);
+ if (j >= src.length) fr.unterminated = true;
+ else reportRegexEnd(fr, j);
blank(i + 1, j);
i = Math.min(j + 1, src.length);
continue;
}
if (c === '<' && /[A-Za-z_$>]/.test(n || '') && expressionPosition(out, i) && !looksLikeTypeParams(src, i)) {
- mode = 'jsxTag';
+ fr.mode = 'jsxTag';
i += 1;
continue;
}
- if (frames.length) {
- const top = frames[frames.length - 1];
+ if (fr.frames.length) {
+ const top = fr.frames[fr.frames.length - 1];
if (c === '{') { top.braceDepth += 1; i += 1; continue; }
if (c === '}') {
- if (top.braceDepth === 0) { leaveJsxExpr(); i += 1; continue; }
+ if (top.braceDepth === 0) { leaveJsxExpr(fr); i += 1; continue; }
top.braceDepth -= 1; i += 1; continue;
}
- } else if (untilCloseBrace) {
- if (c === '{') braceDepth += 1;
+ } else if (fr.untilCloseBrace) {
+ if (c === '{') fr.braceDepth += 1;
else if (c === '}') {
- if (braceDepth === 0) return i;
- braceDepth -= 1;
+ if (fr.braceDepth === 0) {
+ if (fr.bodyOf) { endBody(fr, i); continue; }
+ return i;
+ }
+ fr.braceDepth -= 1;
}
}
i += 1;
continue;
}
- if (mode === 'jsxTag') {
+ if (fr.mode === 'jsxTag') {
// Comments come FIRST. A `//` or `/* */` comment between attributes is valid TSX, and a
// generator naturally emits one to explain an attribute. Without this branch the attribute-
// value case below sees an apostrophe in the comment prose ("Griffel's") and treats it as a
@@ -600,7 +718,7 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
//
// `/` in a tag is otherwise only the start of `/>`, and `n` distinguishes all three cases.
if (c === '/' && n === '/') {
- const end = src.indexOf('\n', i);
+ const end = lineTerminatorStart(src, i);
blank(i, end === -1 ? src.length : end);
if (onComment) onComment(i, end === -1 ? src.length : end);
i = end === -1 ? src.length : end;
@@ -609,7 +727,7 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
if (c === '/' && n === '*') {
const end = src.indexOf('*/', i + 2);
const stop = end === -1 ? src.length : end + 2;
- if (end === -1) unterminated = true;
+ if (end === -1) fr.unterminated = true;
blank(i, stop);
if (onComment) onComment(i, stop);
i = stop;
@@ -618,7 +736,7 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
if (c === '"' || c === "'") { // attribute value
let j = i + 1;
while (j < src.length && src[j] !== c) j += 1;
- if (j >= src.length) unterminated = true;
+ if (j >= src.length) fr.unterminated = true;
blank(i + 1, j);
i = Math.min(j + 1, src.length);
continue;
@@ -630,17 +748,11 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
// would blank to end of line and reject a valid module, and could also hide a genuinely
// malformed expression that follows on the same line. Mirrors the `code`-mode scanner: the
// body is blanked, and its end is found by the expression-aware scanner.
- if (c === '`') {
- const j = scanTemplateLiteral(src, i, out, onComment).end;
- if (j >= src.length) unterminated = true;
- blank(i + 1, j);
- i = Math.min(j + 1, src.length);
- continue;
- }
- if (c === '{') { enterJsxExpr('jsxTag'); i += 1; continue; }
+ if (c === '`') { openTemplate(); continue; }
+ if (c === '{') { enterJsxExpr(fr, 'jsxTag'); i += 1; continue; }
if (c === '/' && n === '>') { // self-closing: no text run follows
- if (onJsxTagEnd) onJsxTagEnd(i + 1);
- mode = jsxDepth > 0 ? 'jsxText' : 'code';
+ reportJsxTagEnd(fr, i + 1);
+ fr.mode = fr.jsxDepth > 0 ? 'jsxText' : 'code';
i += 2;
continue;
}
@@ -648,12 +760,12 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
// Without tracking that, the `>` of `<Row>` would end the tag early and the element would
// never close, desynchronising the rest of the file. A bare `<` can only be a type argument
// here — a comparison would be inside a `{…}` expression, which switches to code mode.
- if (c === '<') { angleDepth += 1; i += 1; continue; }
+ if (c === '<') { fr.angleDepth += 1; i += 1; continue; }
if (c === '>') {
- if (angleDepth > 0) { angleDepth -= 1; i += 1; continue; }
- if (onJsxTagEnd) onJsxTagEnd(i);
- jsxDepth += 1;
- mode = 'jsxText';
+ if (fr.angleDepth > 0) { fr.angleDepth -= 1; i += 1; continue; }
+ reportJsxTagEnd(fr, i);
+ fr.jsxDepth += 1;
+ fr.mode = 'jsxText';
i += 1;
continue;
}
@@ -662,53 +774,31 @@ function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTa
}
// mode === 'jsxText' — everything here is prose until a tag or an expression starts.
- if (c === '{') { enterJsxExpr('jsxText'); i += 1; continue; }
+ if (c === '{') { enterJsxExpr(fr, 'jsxText'); i += 1; continue; }
if (c === '<' && n === '/') { // closing tag
const end = src.indexOf('>', i);
const stop = end === -1 ? src.length : end + 1;
- if (end === -1) unterminated = true;
- else if (onJsxTagEnd) onJsxTagEnd(end);
- jsxDepth = Math.max(0, jsxDepth - 1);
- mode = jsxDepth > 0 ? 'jsxText' : 'code';
+ if (end === -1) fr.unterminated = true;
+ else reportJsxTagEnd(fr, end);
+ fr.jsxDepth = Math.max(0, fr.jsxDepth - 1);
+ fr.mode = fr.jsxDepth > 0 ? 'jsxText' : 'code';
i = stop;
continue;
}
- if (c === '<' && /[A-Za-z_$>]/.test(n || '')) { mode = 'jsxTag'; i += 1; continue; }
+ if (c === '<' && /[A-Za-z_$>]/.test(n || '')) { fr.mode = 'jsxTag'; i += 1; continue; }
blank(i, i + 1);
i += 1;
}
- // Where the lexer stopped: a complete module ends in plain code, with nothing left open.
- if (onEnd) onEnd({ open: unterminated || mode !== 'code' || frames.length > 0 });
- return src.length;
}
// Index of the `}` that closes the `${…}` whose body starts at `start`, or src.length. The body is
// lexed into `scratch` — a `src.split('')` the caller owns and whose blanks inside the body do not
-// matter to it (the lexer passes its own output, which blanks the whole template anyway) — or into
-// a fresh copy when none is given. `onComment` hears the body's comments: they are real comments,
-// so an elision marker or a comment inside an import there counts like any other.
+// matter to it — or into a fresh copy when none is given. `onComment` hears the body's comments: they
+// are real comments, so an elision marker or a comment inside an import there counts like any other.
function scanTemplateExpressionEnd(src, start, scratch, onComment) {
return lexInto(src, scratch || src.split(''), start, { untilCloseBrace: true, onComment: onComment || null });
}
-function scanTemplateLiteral(src, start, scratch, onComment) {
- const expressions = [];
- let view = scratch || null; // one copy for every `${…}` in this template, made on the first
- for (let i = start + 1; i < src.length; i += 1) {
- const c = src[i];
- if (c === '\\') { i += 1; continue; }
- if (c === '`') return { end: i, expressions };
- if (c === '$' && src[i + 1] === '{') {
- if (!view) view = src.split('');
- const exprStart = i + 2;
- const exprEnd = scanTemplateExpressionEnd(src, exprStart, view, onComment);
- expressions.push({ start: exprStart, end: exprEnd });
- i = exprEnd < src.length ? exprEnd : src.length;
- }
- }
- return { end: src.length, expressions };
-}
-
/**
* Blank inert source while leaving executable JavaScript inside template `${...}` expressions.
*
@@ -723,29 +813,16 @@ function scanTemplateLiteral(src, start, scratch, onComment) {
*
* `blankLiterals` intentionally blanks whole template bodies for declaration/bracket checks. The
* navigation oracle needs a different view: template text is still data, but `${...}` is live code.
- * This overlays recursively blanked expression bodies back onto the normal blanked output without
- * changing `blankLiterals` for its existing callers.
+ * Both views come out of ONE lexing pass (lexInto's `keep` buffer), so every position judgment is the
+ * one `blankLiterals` makes. Overlaying each body with a fresh lex of its own slice, recursively,
+ * re-lexed a template nested n deep n times over — cubic: a valid 2.5 KB page of nested templates
+ * took seconds.
*/
function blankNonCodePreservingTemplateExpressions(code) {
const src = String(code || '');
- const out = blankLiterals(src).split('');
- const scratch = src.split(''); // raw copy every `${…}` body below is lexed into
- for (let i = 0; i < src.length; i += 1) {
- if (src[i] !== '`' || out[i] !== '`') continue;
- const { end, expressions } = scanTemplateLiteral(src, i, scratch);
- for (const expr of expressions) {
- // Keep executable substitutions from being concatenated through blanked template text. In
- // `${Xrm.Navigation.navigateTo} text ${({ pageType: "generative", pageId: "PAGEREF_x" })}`
- // the two expressions are independent, but blanking the `${` / `}` delimiters to spaces made
- // call-site regexes see `navigateTo ({ ... })`. A same-length semicolon at the close boundary
- // preserves offsets while making the expression boundary syntactically non-whitespace.
- if (expr.end < out.length && out[expr.end] !== '\n') out[expr.end] = ';';
- const blanked = blankNonCodePreservingTemplateExpressions(src.slice(expr.start, expr.end));
- for (let k = 0; k < blanked.length; k += 1) out[expr.start + k] = blanked[k];
- }
- i = end;
- }
- return out.join('');
+ const keep = src.split('');
+ lexInto(src, src.split(''), 0, { keep });
+ return keep.join('');
}
/**
@@ -762,7 +839,7 @@ function blankNonCodePreservingTemplateExpressions(code) {
* export { P as default } / export { default } from './x'
*/
// Identifiers may be non-ASCII (`Página`), so every name below is matched by Unicode property.
-const DEFAULT_EXPORT = /(?:^[ \t]*|[;}][ \t]*)export[ \t]+default[ \t\r\n]+[\p{ID_Continue}$({[*]/gmu;
+const DEFAULT_EXPORT = /(?:^[ \t]*|[;}][ \t]*)export[ \t]+default\s+[\p{ID_Continue}$({[*]/gmu;
const NAMED_DEFAULT_EXPORT = /(?:^[ \t]*|[;}][ \t]*)export[ \t]*\{[^}]*\bdefault\b[^}]*\}/m;
function hasDefaultExport(code) {
const bare = blankLiterals(code);
@@ -791,12 +868,12 @@ function defaultExportIsComplete(bare, at) {
if (mod) {
const after = rest.slice(mod[0].length);
if (!after.trim()) return false;
- if (!/^(?:function|class)\b/.test(after) && !/^(?:;|\r?\n)/.test(after)) {
+ if (!/^(?:function|class)\b/.test(after) && !/^(?:;|[\r\n\u2028\u2029])/.test(after)) {
// Only an async ARROW is left — `async (x) => …`, `async x => …` — and it needs its `=>` and body.
return mod[1] === 'async' && /=>/.test(after) && !/=>\s*$/.test(after);
}
}
- const fn = /^(?:async[ \t\r\n]+)?function\b\s*\*?\s*(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)?\s*/u.exec(rest);
+ const fn = /^(?:async\s+)?function\b\s*\*?\s*(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)?\s*/u.exec(rest);
if (fn) {
// Type parameters come first and may hold parentheses of their own: `<T extends (a: A) => void>`.
let k = fn[0].length;
@@ -810,9 +887,9 @@ function defaultExportIsComplete(bare, at) {
}
return false;
}
- const cls = /^(?:abstract[ \t\r\n]+)?class\b/.exec(rest);
+ const cls = /^(?:abstract\s+)?class\b/.exec(rest);
if (cls) return hasDeclarationBody(rest, cls[0].length);
- const name = /^([\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)[ \t]*(?:;|\r?\n|$)/u.exec(rest);
+ const name = /^([\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)[ \t]*(?:;|[\r\n\u2028\u2029]|$)/u.exec(rest);
if (!name) {
// A member chain at EOF is syntactically complete: `export default UI.Spinner` and
// `export default pages.Home` are valid exports whether the base is imported or local. A cut at
@@ -1134,4 +1211,4 @@ function ellipsisFollowedByStatement(mask, k) {
return STATEMENT_WORDS.has(word) || word === 'import' || word === 'export';
}
-module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, scanTemplateExpressionEnd };
+module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, scanTemplateExpressionEnd, isLineTerminator };
diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.js
index 795eb2291..22b246bb7 100644
--- a/plugins/model-apps/scripts/lib/spec-lint.js
+++ b/plugins/model-apps/scripts/lib/spec-lint.js
@@ -3,6 +3,7 @@
// gate; warnings teach. Bakes in the modeling lessons hit live — notably the
// relationship schema-name vs lookup-name collision Dataverse rejects.
const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef, labelText } = require('./app-spec.js');
+const { compileFormIntent, formFieldLogicals, NON_FORM_RENDERABLE_TYPES } = require('./artifact-intent.js');
const { normalizeSpecShape } = require('./spec-shape.js');
const { resolveSurfaces, unresolvedSurfaceMessage } = require('./surface-resolver.js');
const { nearestName } = require('./nearest-name.js');
@@ -222,6 +223,31 @@ function lintAppSpec(spec) {
if (!Array.isArray(sections) || sections.length === 0) E(`Form ${f.entity} explicit tab '${t.label || t.name || ''}' has no sections — add at least one section with fields`);
}
}
+ // Under an AUTO layout the build writes a `readOnly` / `hidden` flag only on a field the layout
+ // places — the primary column, the table's declared columns and its parent lookups — so a flag on any
+ // other field (a stock column on an existing form, say) is never applied, and `--verify` does not
+ // prove it. The placed set is the compiler's own, the list the build reconciles.
+ if (!isExplicit && f.fieldOptions && typeof f.fieldOptions === 'object' && !Array.isArray(f.fieldOptions)) {
+ let placed = null;
+ try { placed = new Set(formFieldLogicals(compileFormIntent(spec, f))); } catch { /* a malformed form is the validator's to report */ }
+ for (const [key, opt] of Object.entries(placed ? f.fieldOptions : {})) {
+ const flags = [opt && opt.readOnly === true && 'readOnly', opt && opt.hidden === true && 'hidden'].filter(Boolean);
+ if (!flags.length || placed.has(lc(key))) continue;
+ // Why the field is off the form decides the advice. A DECLARED column the layout still leaves off is
+ // either a type with no form control at all (BigInt — validation explains it) or a type the auto
+ // layout simply does not place (a Customer column, say), which an explicit layout can list.
+ const ent = arrOf(spec.entities).find((e) => e && lc(e.schemaName) === lc(f.entity));
+ const col = ent && arrOf(ent.columns).find((c) => c && lc(c.schemaName) === lc(key));
+ const what = `Form ${f.entity} '${f.name || ''}': fieldOptions['${key}'] sets ${flags.join(' and ')}`;
+ if (col && NON_FORM_RENDERABLE_TYPES.has(col.type)) {
+ W(`${what} on a ${col.type} column, which has no form control, so the auto layout leaves it off the form and the build never applies it.`);
+ } else if (col) {
+ W(`${what} on a ${col.type} column, a type the auto layout does not place, so the build never applies it. List '${key}' in an explicit layout to place it (prune: false keeps the rest of the form).`);
+ } else {
+ W(`${what} on a field the auto layout does not place — it places the primary column, the table's declared columns and its parent lookups — so the build never applies it. Declare '${key}' as a column, or list it in an explicit layout (prune: false keeps the rest of the form).`);
+ }
+ }
+ }
for (const sg of f.subgrids || []) {
const has1N = (spec.relationships || []).some(
(r) => r.type === 'OneToMany' && lc(r.referenced) === lc(f.entity) && lc(r.referencing) === lc(sg.childEntity)
@@ -346,6 +372,12 @@ function lintAppSpec(spec) {
for (const ds of p.dataSources || []) {
if (!entityLowerSet.has(lc(ds))) W(`Page '${p.name}' data source '${ds}' isn't a declared entity — ok if it's a standard table, otherwise a likely typo`);
}
+ // pac stores each ASCII `"` in a page's name as `\"` on the page's own record, and changes nothing else
+ // (live-measured). A warning, not an error: the navigation shows the subarea's `title`, which the build
+ // writes as given. (The standalone genpage upload refuses such a name — there pac writes the title too.)
+ if (typeof p.name === 'string' && p.name.includes('"')) {
+ W(`Page '${p.name}': pac stores each ASCII double quote (") in a page's name as \\" on the page's own record — use typographic quotes (“ ”) or an apostrophe instead`);
+ }
}
// The sitemap `VectorIcon` attribute must be an SVG path (e.g. /_imgs/TableIconsFluentV9/x.svg) or
// a $webresource:<name>.svg reference — NOT a bare Fluent token, which breaks the modern
@@ -510,9 +542,14 @@ function lintAppSpec(spec) {
}
}
- dupWarn((spec.views || []).map((v) => v.name), 'view', W);
- dupWarn((spec.charts || []).map((c) => c.name), 'chart', W);
- dupWarn((spec.forms || []).map((f) => f.name).filter(Boolean), 'form', W);
+ // Views, charts and forms belong to a TABLE, and the build finds each by its table and name (a form also
+ // by its type) — so one name on two tables is two artifacts, not a duplicate; a dashboard tile that
+ // could mean either is refused by validation until it names its table. Only a repeat on ONE table
+ // collides. Warning on the name alone flagged the supported same-named-charts-on-two-tables shape.
+ const forms = (spec.forms || []).filter((f) => f && f.name);
+ dupWarn(spec.views || [], 'view', W, (v) => `${lc(v.entity)}|${lc(v.name)}`);
+ dupWarn(spec.charts || [], 'chart', W, (c) => `${lc(c.entity)}|${lc(c.name)}`);
+ dupWarn(forms, 'form', W, (f) => `${lc(f.entity)}|${lc(f.formType || 'Main')}|${lc(f.name)}`);
// Design-completeness warnings. These are WARNINGS, never errors: a spec without personas or pages
// is still buildable, and the author may have good reason. They exist because all three were steps
@@ -558,11 +595,12 @@ function lintAppSpec(spec) {
return { ok: errors.length === 0, errors, warnings };
}
-function dupWarn(names, kind, W) {
+function dupWarn(items, kind, W, keyOf) {
const seen = new Set();
- for (const n of names) {
- const k = String(n || '').toLowerCase();
- if (k && seen.has(k)) W(`Duplicate ${kind} name: ${n}`);
+ for (const item of items) {
+ if (!item || typeof item !== 'object' || !item.name) continue;
+ const k = keyOf(item);
+ if (seen.has(k)) W(`Duplicate ${kind} name on ${item.entity || '?'}: ${item.name}`);
seen.add(k);
}
}
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index ff8997d22..65d72ca15 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -6,7 +6,7 @@
const { odataLit } = require('./odata.js');
const { matchContainer, isEngineOwnedSection, isEngineHostSection, claimedByAuthoredName } = require('./form-container-match.js');
-const { authoredSectionNames } = require('./app-spec.js');
+const { authoredSectionNames, authoredTabNames } = require('./app-spec.js');
const { decodeXmlEntities } = require('./sitemap-pages.js');
const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS, generatedTabName, generatedSectionName, formColumnsOf } = require('./app-spec.js');
const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName, findPinnedDashboard } = require('./sdk-build.js');
@@ -19,7 +19,7 @@ const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges
const { resolveSurfaces } = require('./surface-resolver.js');
const { selectSummaryTables } = require('./ai-candidates.js');
const { isVisualizationUnsupported } = require('./entity-provision.js');
-const { sectionGridWidth, mergeFieldOptions, fieldOptionsMap, normalizeFieldEntry } = require('./artifact-intent.js');
+const { sectionGridWidth, mergeFieldOptions, fieldOptionsMap, normalizeFieldEntry, compileFormIntent, isNonFieldControl } = require('./artifact-intent.js');
const { rowOccupancy } = require('./form-occupancy.js');
const { isMainForm, selectDefaultForm, plannedMainFormSequence, displayConditionsOrder, compareServedOrder } = require('./form-order.js');
@@ -441,12 +441,33 @@ async function verifySpec(spec, read, opts = {}) {
const canReadTopology = typeof read.formTopology === 'function';
{
for (const f of spec.forms || []) {
- if (!Array.isArray(f.tabs) || !f.tabs.length) continue;
+ const explicit = Array.isArray(f.tabs) && f.tabs.length > 0;
const entity = String(f.entity || '').toLowerCase();
const name = f.name || `${f.entity} form`;
const formFieldOptions = fieldOptionsMap(f);
+ // An AUTO layout declares no shape, so it has no topology to prove — but its `fieldOptions` can
+ // still make a field read-only or hidden, which the build asserts on every apply. Those flags are
+ // proven on their own (`form-field-state`); without this an auto-layout form's declared state was
+ // never checked at all. Exactly the flags the BUILD writes are proven: those on the fields the
+ // compiled layout places (autoLayoutFieldFlags). A flag on any other field is never applied, so
+ // proving it failed a form the build had never been asked to change.
+ const flagsAny = !explicit && Object.values(formFieldOptions).some((o) => o.readOnly === true || o.hidden === true);
+ let autoFlagged = [];
+ let autoCompileError = null;
+ if (flagsAny) {
+ try { autoFlagged = autoLayoutFieldFlags(spec, f); } catch (e) { autoCompileError = (e && e.message) || String(e); }
+ }
+ if (!explicit && !autoFlagged.length && !autoCompileError) continue;
+ const kind = explicit ? 'form-topology' : 'form-field-state';
+ if (autoCompileError) {
+ // Only an unvalidated spec reaches this (validation requires every table's primary column), but a
+ // layout the compiler cannot read cannot say which fields the build places — so nothing is proven.
+ add(kind, `${entity}.${name}`, false,
+ `could not compile the layout to tell which fields the build places (${autoCompileError}) — the field state is unverified, not proven correct`);
+ continue;
+ }
if (!canReadTopology) {
- add('form-topology', `${entity}.${name}`, false,
+ add(kind, `${entity}.${name}`, false,
'this reader exposes no deployed-layout source, so the layout is UNVERIFIED — not proven correct');
continue;
}
@@ -461,7 +482,7 @@ async function verifySpec(spec, read, opts = {}) {
// and correct, and silently skipping the layout check let a transient read failure pass as a
// verified layout.
if (idError) {
- add('form-topology', `${entity}.${name}`, false,
+ add(kind, `${entity}.${name}`, false,
`could not resolve the deployed form id (${idError}) — the layout is unverified, not proven correct`);
}
continue;
@@ -471,12 +492,56 @@ async function verifySpec(spec, read, opts = {}) {
let readError = null;
try { xml = await read.formTopology(entity, id); } catch (e) { readError = (e && e.message) || String(e); }
if (!xml) {
- add('form-topology', `${entity}.${name}`, false,
+ add(kind, `${entity}.${name}`, false,
`could not read the deployed form layout${readError ? `: ${readError}` : ''} — the layout is unverified, not proven correct`);
continue;
}
const deployed = parseFormTopology(xml);
+ const problems = [];
+ // A declared flag against the deployed attribute, where an absent attribute is what the form
+ // renders without one: shown, expanded, labelled, editable. Reported in the spec's own terms
+ // (`specClause`), which for `hidden` is the inverse of the attribute it sets.
+ const flagProblem = (what, xmlAttr, deployedValue, wantAttr, renderedDefault, specClause) => {
+ const got = deployedValue === undefined ? renderedDefault : deployedValue;
+ if (got !== wantAttr) {
+ problems.push(`${what} is deployed with ${xmlAttr}="${got}"${deployedValue === undefined ? ' (absent, the default)' : ''}, the spec declares ${specClause}`);
+ }
+ };
+ const stateFlag = (what, specKey, xmlAttr, deployedValue, want) => flagProblem(what, xmlAttr, deployedValue, want, true, `${specKey}: ${want}`);
+ // The state the build asserts for a field: only the ENABLED flags are ever written (a rebuild never
+ // clears a lock or a hide applied in the designer), so only `true` is proven.
+ const fieldStateProblems = (fl, eff, dc) => {
+ if (eff.hidden === true) flagProblem(`field '${fl}'`, 'visible', dc.visible, false, true, 'hidden: true');
+ if (eff.readOnly === true) flagProblem(`field '${fl}'`, 'disabled', (dc.control || {}).disabled, true, false, 'readOnly: true');
+ };
+ if (!explicit) {
+ // The FIRST cell binding the field — the one the build's cell lookup patches. Every field here is
+ // one the build places on the form, so a flagged field the deployed form does not carry is a
+ // mismatch: its state cannot be deployed without it. Skipping it passed a form whose read-only
+ // field a maker had removed.
+ const cellOf = (fl) => deployed.flatMap((t) => (t.columns || []).flatMap((c) => (c.sections || []).flatMap((s) => (s.rows || []).flatMap((r) => r.cells || []))))
+ .find((c) => c.control && c.control.fieldName === fl && !isNonFieldControl(c.control));
+ for (const { field, readOnly, hidden } of autoFlagged) {
+ const dc = cellOf(field);
+ if (!dc) {
+ const declared = [readOnly && 'readOnly: true', hidden && 'hidden: true'].filter(Boolean).join(' and ');
+ problems.push(`field '${field}' is not on the deployed form, so its ${declared} is not deployed`);
+ continue;
+ }
+ fieldStateProblems(field, { readOnly, hidden }, dc);
+ }
+ add(kind, `${entity}.${name}`, problems.length === 0,
+ problems.length ? `deployed field state does not match the authored one — ${problems.slice(0, 6).join('; ')}${problems.length > 6 ? `; +${problems.length - 6} more` : ''}` : '');
+ continue;
+ }
+ // What the COMPILER emitted for this layout — tab state, form-column widths, section state — taken
+ // from the compiler itself rather than re-derived, so verify expects exactly what the build was asked
+ // to converge (an undeclared width is the equal split, an undeclared flag is `true`). Its tabs, their
+ // form-columns and their sections line up index for index with the spec's; the compiler only APPENDS
+ // (the notes section, after the first tab's authored sections). The build compiled this same layout,
+ // so it compiles here too.
+ const compiledTabs = compileFormIntent(spec, f).tabs || [];
// Where the DEPLOYED form actually placed each bound field, as the IDENTITY of the section
// holding it — not merely its name.
//
@@ -493,16 +558,31 @@ async function verifySpec(spec, read, opts = {}) {
for (const fl of sec.fields || []) if (!placedIn.has(fl)) placedIn.set(fl, sec);
}
- const problems = [];
+ // ORDER. The authored containers must deploy in the layout's order — the build moves them into it
+ // (planOrderMoves). Only their RELATIVE order is compared: a tab or section the layout does not
+ // mention (a maker's own, an engine host) has no place in it. `matched` holds the deployed index of
+ // each container matched, in layout order.
+ const orderProblem = (matched, what) => {
+ if (matched.every((m, i) => i === 0 || matched[i - 1].index < m.index)) return;
+ const deployedOrder = matched.slice().sort((a, b) => a.index - b.index).map((m) => m.name);
+ problems.push(`${what} are deployed in the order ${deployedOrder.join(', ')}; the spec orders them ${matched.map((m) => m.name).join(', ')}`);
+ };
+ const sameWidth = (got, want) => {
+ const pct = (w) => { const m = /^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(String(w === undefined ? '' : w)); return m ? Number(m[1]) : null; };
+ return pct(got) !== null && pct(got) === pct(want);
+ };
// Match containers the way the BUILD does — name, then label, then position — using the same
// function it uses. A label- or position-matched container deliberately KEEPS its deployed
// name (form scripts and business rules reference section names), so looking one up by the
// AUTHORED name reported a perfectly good auto-to-explicit migration as "section absent" and
// failed a build that had done exactly what was asked. Live-reproduced.
const claimedTabs = new Set();
+ const tabOrder = [];
// The section names the author declared — the same set the build's compiler records — so the
// label and position passes skip a section another want owns by name, exactly as the build does.
+ // Tabs follow the same rule, from the same kind of set.
const authoredNames = authoredSectionNames(f);
+ const tabSkip = claimedByAuthoredName(authoredTabNames(f));
f.tabs.forEach((t, ti) => {
if (!t || typeof t !== 'object') return;
const tabName = String(t.name || generatedTabName(ti)).toLowerCase();
@@ -510,18 +590,29 @@ async function verifySpec(spec, read, opts = {}) {
// a tab to 'General' and a section to 'Details', so the deployed container carries the
// default — comparing against `undefined` would skip the label pass and fall through to
// position, picking a different container than the build did.
- const tabHit = matchContainer(deployed, { name: tabName, label: t.label || 'General' }, ti, { claimed: claimedTabs });
+ const tabHit = matchContainer(deployed, { name: tabName, label: t.label || 'General' }, ti, { claimed: claimedTabs, skip: tabSkip });
if (!tabHit) { problems.push(`tab '${tabName}' is absent`); return; }
claimedTabs.add(tabHit.index);
+ tabOrder.push({ name: tabName, index: tabHit.index });
const got = tabHit.item;
+ const compiledTab = compiledTabs[ti] || {};
+ stateFlag(`tab '${tabName}'`, 'expanded', 'expanded', got.expanded, compiledTab.expanded !== false);
+ stateFlag(`tab '${tabName}'`, 'visible', 'visible', got.visible, compiledTab.visible !== false);
const authoredColumns = formColumnsOf(t);
if ((got.columns || []).length < authoredColumns.length) {
problems.push(`tab '${tabName}' has ${(got.columns || []).length} form-column(s), the spec declares ${authoredColumns.length}`);
}
authoredColumns.forEach((col, ci) => {
const sections = (col && Array.isArray(col.sections)) ? col.sections : [];
- const deployedSections = ((got.columns || [])[ci] || {}).sections || [];
+ const deployedColumn = (got.columns || [])[ci];
+ const deployedSections = (deployedColumn || {}).sections || [];
+ const compiledColumn = (compiledTab.columns || [])[ci] || {};
+ // The width the build writes on every apply — the authored one, or the compiler's equal split.
+ if (deployedColumn && compiledColumn.width !== undefined && !sameWidth(deployedColumn.width, compiledColumn.width)) {
+ problems.push(`tab '${tabName}' form-column ${ci + 1} is deployed ${deployedColumn.width === undefined ? 'with no width' : `${deployedColumn.width} wide`}, the spec declares ${compiledColumn.width}`);
+ }
const claimedSections = new Set();
+ const sectionOrder = [];
sections.forEach((sec, si) => {
if (!sec || typeof sec !== 'object') return;
const secName = String(sec.name || generatedSectionName(ti, ci, si)).toLowerCase();
@@ -536,6 +627,10 @@ async function verifySpec(spec, read, opts = {}) {
return;
}
claimedSections.add(secHit.index);
+ sectionOrder.push({ name: secName, index: secHit.index });
+ const compiledSection = (compiledColumn.sections || [])[si] || {};
+ stateFlag(`section '${secName}'`, 'visible', 'visible', secHit.item.visible, compiledSection.visible !== false);
+ stateFlag(`section '${secName}'`, 'showLabel', 'showlabel', secHit.item.showLabel, compiledSection.showLabel !== false);
// The grid width the COMPILER emits for this authored section — taken from the same
// function the compiler uses, never re-derived here. Reading the raw `columns` instead
// failed forms that deployed exactly as compiled: an omitted `columns` compiles to 1,
@@ -579,7 +674,7 @@ async function verifySpec(spec, read, opts = {}) {
// every `fieldOptions` span unverified — including one the build had to skip.
const deployedCellOf = (logical) => (secHit.item.rows || [])
.flatMap((r2) => r2.cells || [])
- .find((c) => c.control && c.control.fieldName === logical);
+ .find((c) => c.control && c.control.fieldName === logical && !isNonFieldControl(c.control));
for (const entry of (sec.fields || [])) {
const inline = normalizeFieldEntry(entry);
const fl = inline.name;
@@ -587,6 +682,7 @@ async function verifySpec(spec, read, opts = {}) {
const eff = mergeFieldOptions(formFieldOptions[fl], inline, fl);
const dc = deployedCellOf(fl);
if (!dc) continue; // placement is reported separately below
+ fieldStateProblems(fl, eff, dc);
for (const key of ['colspan', 'rowspan']) {
const declared = Number(eff[key]);
if (!Number.isFinite(declared) || declared < 1) continue; // not declared
@@ -624,8 +720,10 @@ async function verifySpec(spec, read, opts = {}) {
}
}
});
+ orderProblem(sectionOrder, `the sections of tab '${tabName}' form-column ${ci + 1}`);
});
});
+ orderProblem(tabOrder, 'the tabs');
add('form-topology', `${entity}.${name}`, problems.length === 0,
problems.length ? `deployed layout does not match the authored one — ${problems.slice(0, 6).join('; ')}${problems.length > 6 ? `; +${problems.length - 6} more` : ''}` : '');
@@ -1551,6 +1649,30 @@ function parseFetchXml(xml) {
return { conditions, orders };
}
+// The read-only / hidden flags the build writes for an AUTO-layout form: one entry per field the compiled
+// layout places — the primary column, the table's declared columns, its parent lookups — whose compiled cell
+// carries a flag, in the cell's own terms (`control.isReadOnly`, `visible: false`). These are exactly the
+// fields the build's reconcile places and re-asserts (`want` → applyFieldControlOptions in sdk-build.js); a
+// `fieldOptions` flag on any other field is never written (spec-lint warns about it).
+function autoLayoutFieldFlags(spec, formSpec) {
+ const out = [];
+ const seen = new Set();
+ const def = compileFormIntent(spec, formSpec);
+ for (const t of def.tabs || []) for (const col of t.columns || []) for (const sec of col.sections || []) {
+ for (const row of sec.rows || []) for (const cell of row.cells || []) {
+ const fn = cell.control && cell.control.fieldName;
+ if (!fn || isNonFieldControl(cell.control)) continue;
+ const field = String(fn).toLowerCase();
+ if (seen.has(field)) continue;
+ seen.add(field);
+ const readOnly = cell.control.isReadOnly === true;
+ const hidden = cell.visible === false;
+ if (readOnly || hidden) out.push({ field, readOnly, hidden });
+ }
+ }
+ return out;
+}
+
// Parse a deployed form's FormXml into the container tree `--verify` needs to prove a layout.
//
// Why this exists: form verification used to prove only that a form row EXISTS with the right
@@ -1582,6 +1704,15 @@ function parseFormTopology(xml) {
const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(raw || '');
return m ? (m[1] != null ? m[1] : m[2]) : undefined;
};
+ // The display flags verify compares — tab `expanded`/`visible`, section `visible`/`showlabel`, cell
+ // `visible`, control `disabled` — are `xs:boolean`, so "true"/"false" or "1"/"0", and the schema gives
+ // none of them a default. An absent (or unreadable) one stays undefined; the comparison applies what
+ // the form renders without it.
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/form-xml-schema
+ const flag = (raw, name) => {
+ const v = String(attr(raw, name) === undefined ? '' : attr(raw, name)).trim().toLowerCase();
+ return v === 'true' || v === '1' ? true : (v === 'false' || v === '0' ? false : undefined);
+ };
let m;
while ((m = re.exec(s)) !== null) {
const closing = m[1] === '/';
@@ -1596,14 +1727,14 @@ function parseFormTopology(xml) {
else if (tag === 'cell') { inCell = false; cell = null; }
continue;
}
- if (tag === 'tab') { tab = { name: attr(raw, 'name'), label: undefined, columns: [] }; tabs.push(tab); if (selfClosing) tab = null; }
+ if (tag === 'tab') { tab = { name: attr(raw, 'name'), label: undefined, expanded: flag(raw, 'expanded'), visible: flag(raw, 'visible'), columns: [] }; tabs.push(tab); if (selfClosing) tab = null; }
else if (tag === 'column' && tab) { column = { width: attr(raw, 'width'), sections: [] }; tab.columns.push(column); if (selfClosing) column = null; }
else if (tag === 'section' && column) {
const ratio = attr(raw, 'columns');
// `columns` is a width RATIO string, not a count: "11" is two equal columns, "1111" is four.
// ABSENT means the width is UNKNOWN — left undefined so the occupancy check skips rather than
// assuming a 1-column grid and inventing an overflow that is not there.
- section = { name: attr(raw, 'name'), label: undefined, columns: ratio ? String(ratio).length : undefined, rows: [], fields: [] };
+ section = { name: attr(raw, 'name'), label: undefined, columns: ratio ? String(ratio).length : undefined, visible: flag(raw, 'visible'), showLabel: flag(raw, 'showlabel'), rows: [], fields: [] };
column.sections.push(section);
if (selfClosing) section = null;
}
@@ -1612,7 +1743,7 @@ function parseFormTopology(xml) {
inCell = !selfClosing;
// A cell with no <control> child stays control-less, which is what keeps a SPACER from
// reading as engine-owned.
- cell = { colspan: Number(attr(raw, 'colspan')) || 1, rowspan: Number(attr(raw, 'rowspan')) || 1 };
+ cell = { colspan: Number(attr(raw, 'colspan')) || 1, rowspan: Number(attr(raw, 'rowspan')) || 1, visible: flag(raw, 'visible') };
if (row) row.cells.push(cell);
if (selfClosing) cell = null;
}
@@ -1635,8 +1766,12 @@ function parseFormTopology(xml) {
// marks a timeline or sub-grid host a maker added a field to (isEngineHostSection).
const f = attr(raw, 'datafieldname');
const classId = attr(raw, 'classid');
- if (f) section.fields.push(String(f).toLowerCase());
- if (cell) cell.control = Object.assign(f ? { fieldName: String(f).toLowerCase() } : {}, classId ? { classId } : {});
+ const disabled = flag(raw, 'disabled');
+ // A quick view binds a LOOKUP's datafieldname too, but it is not that field: counted as one, it placed
+ // the lookup wherever the quick view sat and lent the field its visibility and state. The build skips it
+ // the same way (isNonFieldControl) when it picks the cell to place or patch.
+ if (f && !isNonFieldControl({ classId })) section.fields.push(String(f).toLowerCase());
+ if (cell) cell.control = Object.assign(f ? { fieldName: String(f).toLowerCase() } : {}, classId ? { classId } : {}, disabled === undefined ? {} : { disabled });
}
}
return tabs;
diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.js
index 6f4ca11e8..4d7098d4d 100644
--- a/plugins/model-apps/scripts/list-connections.js
+++ b/plugins/model-apps/scripts/list-connections.js
@@ -29,22 +29,25 @@ function mapConnectionRow(row) {
for (const [key, value] of Object.entries(row)) {
normalized[normalizeHeader(key)] = value;
}
+ // An identifier is a non-empty STRING, trimmed. A number, an object, an array or whitespace in an id
+ // column is not one: kept, it made a row with "both ids" that no connection reference could ever bind.
+ const text = (value) => (typeof value === 'string' ? value.trim() : '');
const connectionId =
- normalized.connectionid ||
- normalized.id ||
- normalized.connection ||
+ text(normalized.connectionid) ||
+ text(normalized.id) ||
+ text(normalized.connection) ||
'';
const connectorId =
- normalized.connectorid ||
- normalized.apiid ||
- normalized.connector ||
+ text(normalized.connectorid) ||
+ text(normalized.apiid) ||
+ text(normalized.connector) ||
extractConnectorId(connectionId) ||
'';
const displayName =
- normalized.connectionname ||
- normalized.displayname ||
- normalized.name ||
+ text(normalized.connectionname) ||
+ text(normalized.displayname) ||
+ text(normalized.name) ||
connectorId ||
connectionId;
@@ -56,6 +59,16 @@ function extractConnectorId(connectionId) {
return match ? match[1] : '';
}
+// Whether a row of column names is a connection table's header: at least two columns, one of them a column
+// `mapConnectionRow` reads the connection id from. A line that only MENTIONS a connector — "Warning: failed to
+// retrieve connector metadata." — is prose; read as a header it made an empty table, and so "no connections", the
+// answer that sends connection setup on to create a duplicate.
+const CONNECTION_ID_COLUMNS = new Set(['connectionid', 'id', 'connection']);
+function isConnectionHeader(names) {
+ const columns = names.map(normalizeHeader).filter(Boolean);
+ return columns.length >= 2 && columns.some((column) => CONNECTION_ID_COLUMNS.has(column));
+}
+
function usableConnection(row) {
return Boolean(row.connectorId && row.connectionId);
}
@@ -86,7 +99,7 @@ function parseFixedWidthTable(raw) {
const runs = line.match(/-{3,}/g) || [];
return runs.length >= 2;
});
- if (separatorIndex <= 0) return [];
+ if (separatorIndex <= 0) return null; // no table here — not the same as a table with no rows
const headerLine = lines[separatorIndex - 1];
const ranges = [...lines[separatorIndex].matchAll(/-+/g)].map((match, index, matches) => ({
@@ -94,6 +107,7 @@ function parseFixedWidthTable(raw) {
start: match.index,
end: matches[index + 1]?.index,
}));
+ if (!isConnectionHeader(ranges.map((range) => range.name))) return null;
return usableConnectionRows(lines
.slice(separatorIndex + 1)
@@ -109,8 +123,9 @@ function parseFixedWidthTable(raw) {
function parseWhitespaceTable(raw) {
const lines = raw.replace(/\r/g, '').split('\n').filter((line) => line.trim());
- const headerIndex = lines.findIndex((line) => /Connection Name|Connection Id|Connector|API Id/i.test(line));
- if (headerIndex === -1) return [];
+ const headerIndex = lines.findIndex((line) => /Connection Name|Connection Id|Connector|API Id/i.test(line)
+ && isConnectionHeader(line.trim().split(/\s{2,}/)));
+ if (headerIndex === -1) return null; // no table here — not the same as a table with no rows
const headers = lines[headerIndex].trim().split(/\s{2,}/);
const normalizedHeaders = headers.map(normalizeHeader);
// Current PAC builds emit:
@@ -135,7 +150,9 @@ function parseWhitespaceTable(raw) {
}
return usableConnectionRows(lines
.slice(headerIndex + 1)
- .filter((line) => !/^-+$/.test(line.trim()))
+ // A separator is dashes and the spaces between its runs ("----- -----"). Kept as a row, its dash runs read
+ // as a connection's ids and names, and an empty table became one phantom connection.
+ .filter((line) => !/^[\s-]+$/.test(line))
.map((line) => {
const values = line.trim().split(/\s{2,}/);
const row = {};
@@ -146,9 +163,31 @@ function parseWhitespaceTable(raw) {
}), 'whitespace table');
}
+// PAC's auth banner, printed before any listing, and its "nothing to list" message, e.g.
+// Connected as [email protected]
+// No connections found.
+const PAC_BANNER = /^connected as\b/i;
+const NO_CONNECTIONS_MESSAGE = /^no connections?\b.*\bfound\b/i;
+
+// Output none of the parsers recognised. It is REFUSED rather than read as "no connections": that answer
+// sends connection setup on to create a connection the maker already has — and a warning printed on a
+// zero exit ("Warning: failed to retrieve connections."), JSON cut short, or a changed format are all
+// failures to read, not an empty environment.
+function unreadableListing(raw, why) {
+ const first = String(raw).split(/\r\n|\r|\n/).map((l) => l.trim()).find((l) => l && !PAC_BANNER.test(l)) || '(no output)';
+ return `pac connection list printed output this script could not read — ${why} (first line: "${first.slice(0, 200)}"). `
+ + 'It is not reported as "no connections", which would lead connection setup to create a duplicate; run `pac connection list` to see what it printed.';
+}
+
function parsePacConnectionList(raw) {
- const jsonRows = parseJsonConnections(raw);
- if (jsonRows) return jsonRows;
+ const text = String(raw == null ? '' : raw);
+ // JSON is recognised by its first character, so JSON that does not parse — cut short, say — is an
+ // unreadable listing rather than something for the table parsers to find nothing in.
+ if (/^[[{]/.test(text.trim())) {
+ const jsonRows = parseJsonConnections(text.trim());
+ if (jsonRows) return jsonRows;
+ throw new Error(unreadableListing(text, 'it starts like JSON but is not a connection list'));
+ }
// PAC commonly emits a fixed-width table similar to:
// Connection Name Connector Id Connection Id
@@ -156,8 +195,15 @@ function parsePacConnectionList(raw) {
// Contoso SharePoint /providers/Microsoft.PowerApps/apis/shared_sharepointonline /providers/.../connections/abc
// Some older builds wrap friendly names but keep 2+ spaces between columns, so
// parse fixed-width first and fall back to a whitespace table for simpler output.
- const fixed = parseFixedWidthTable(raw);
- return fixed.length ? fixed : parseWhitespaceTable(raw);
+ const fixed = parseFixedWidthTable(text);
+ if (fixed && fixed.length) return fixed;
+ const loose = parseWhitespaceTable(text);
+ if (loose) return loose;
+ if (fixed) return fixed;
+ // No table and no JSON: only PAC's own message says there is nothing to list.
+ const lines = text.split(/\r\n|\r|\n/).map((l) => l.trim()).filter((l) => l && !PAC_BANNER.test(l));
+ if (lines.length && lines.every((l) => NO_CONNECTIONS_MESSAGE.test(l))) return [];
+ throw new Error(unreadableListing(text, lines.length ? 'no connection table, JSON list or "no connections found" message' : 'it printed no listing at all'));
}
function sameConnectionId(a, b) {
@@ -283,7 +329,7 @@ module.exports = {
// The `pac connection list` parsers are exported for unit tests. They consume loosely
// structured CLI output whose shape varies across PAC builds (JSON, fixed-width table,
// whitespace table), which is exactly the code most likely to break silently on a CLI
- // upgrade — a mis-parse yields "no connections found" rather than an error.
+ // upgrade — so output none of them recognises is refused, never read as "no connections".
parsePacConnectionList,
parseJsonConnections,
parseFixedWidthTable,
diff --git a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
index 6e12dc93f..932ded1af 100644
--- a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
+++ b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
@@ -70,10 +70,13 @@ function harness({ argv, refLookup = defaultLookup }) {
}
const ENV = 'https://contoso.crm.dynamics.com';
+const APP = '11111111-1111-4111-8111-111111111111';
+const P1 = '22222222-2222-4222-8222-222222222222';
+const P2 = '33333333-3333-4333-8333-333333333333';
test('packages appmodule, each page, and each connection reference with the right component types', async () => {
const { cli, calls, emitted } = harness({
- argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1,p2', '--connection-refs', 'new_sp'],
+ argv: [ENV, 'sol', APP, '--page-ids', `${P1},${P2}`, '--connection-refs', 'new_sp'],
});
await cli.main();
@@ -82,11 +85,11 @@ test('packages appmodule, each page, and each connection reference with the righ
// appmodule (80) with AddRequiredComponents=true pulls the sitemap + appmodulecomponent.
assert.deepEqual(
{ ComponentId: adds[0].body.ComponentId, ComponentType: adds[0].body.ComponentType, AddRequiredComponents: adds[0].body.AddRequiredComponents },
- { ComponentId: 'app-1', ComponentType: 80, AddRequiredComponents: true }
+ { ComponentId: APP, ComponentType: 80, AddRequiredComponents: true }
);
// Each GenPage is added EXPLICITLY as uxagentproject (10372) — it does not travel with the app.
assert.deepEqual(adds.slice(1, 3).map((c) => [c.body.ComponentId, c.body.ComponentType, c.body.AddRequiredComponents]),
- [['p1', 10372, true], ['p2', 10372, true]]);
+ [[P1, 10372, true], [P2, 10372, true]]);
// The connection reference resolves by logical name, then is added as 10158 WITHOUT required
// components (371 is msdyn_Connector and fails with a MetadataCache error).
assert.deepEqual([adds[3].body.ComponentId, adds[3].body.ComponentType, adds[3].body.AddRequiredComponents],
@@ -98,7 +101,7 @@ test('packages appmodule, each page, and each connection reference with the righ
test('discovers environment-specific component types for GenPages and connection references', async () => {
const { cli, calls } = harness({
- argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1', '--connection-refs', 'new_sp'],
+ argv: [ENV, 'sol', APP, '--page-ids', P1, '--connection-refs', 'new_sp'],
refLookup: (requestPath) => {
if (requestPath.includes("EntityDefinitions(LogicalName='uxagentproject')")) {
return { status: 200, data: { ObjectTypeCode: 10380 } };
@@ -120,7 +123,7 @@ test('discovers environment-specific component types for GenPages and connection
test('the appmodule is packaged BEFORE any page or connection reference', async () => {
// Order is load-bearing: adding a uxagentproject to a solution the app is not yet in produces a
// solution whose page has no owning app.
- const { cli, calls } = harness({ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1', '--connection-refs', 'new_sp'] });
+ const { cli, calls } = harness({ argv: [ENV, 'sol', APP, '--page-ids', P1, '--connection-refs', 'new_sp'] });
await cli.main();
const types = calls.filter((c) => c.path === 'AddSolutionComponent').map((c) => c.body.ComponentType);
assert.equal(types[0], 80, 'appmodule must be first');
@@ -129,7 +132,7 @@ test('the appmodule is packaged BEFORE any page or connection reference', async
test('a connection reference that does not exist fails the run instead of packaging a partial solution', async () => {
const { cli, calls, emitted } = harness({
- argv: [ENV, 'sol', 'app-1', '--connection-refs', 'new_missing'],
+ argv: [ENV, 'sol', APP, '--connection-refs', 'new_missing'],
refLookup: (requestPath) =>
requestPath.includes("EntityDefinitions(LogicalName='connectionreference')")
? { status: 200, data: { ObjectTypeCode: 10158 } }
@@ -147,7 +150,7 @@ test('a connection reference that does not exist fails the run instead of packag
test('all requested connection references are validated before adding the app or pages', async () => {
const { cli, calls, emitted } = harness({
- argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1,p2', '--connection-refs', 'new_missing'],
+ argv: [ENV, 'sol', APP, '--page-ids', `${P1},${P2}`, '--connection-refs', 'new_missing'],
refLookup: (requestPath) => {
if (requestPath.includes("EntityDefinitions(LogicalName='uxagentproject')")) {
return { status: 200, data: { ObjectTypeCode: 10372 } };
@@ -171,7 +174,7 @@ test('all requested connection references are validated before adding the app or
test('a connection reference logical name with a quote is OData-escaped, not injected', async () => {
const seen = [];
const { cli } = harness({
- argv: [ENV, 'sol', 'app-1', '--connection-refs', "new_o'brien"],
+ argv: [ENV, 'sol', APP, '--connection-refs', "new_o'brien"],
refLookup: (p) => {
if (p.includes("EntityDefinitions(LogicalName='connectionreference')")) {
return { status: 200, data: { ObjectTypeCode: 10158 } };
@@ -187,7 +190,7 @@ test('a connection reference logical name with a quote is OData-escaped, not inj
});
test('no --connection-refs packages the app and pages only', async () => {
- const { cli, calls, emitted } = harness({ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1'] });
+ const { cli, calls, emitted } = harness({ argv: [ENV, 'sol', APP, '--page-ids', P1] });
await cli.main();
assert.equal(calls.filter((c) => c.method === 'GET').length, 1, 'only the page component-type lookup runs');
assert.deepEqual(emitted[0].payload.added.map((a) => a.type), ['appmodule', 'uxagentproject']);
@@ -214,7 +217,7 @@ test('a failing AddSolutionComponent surfaces as a failure, not a silent partial
};
const cli = loadCli(scriptPath, {
requires: { './lib/dataverse-auth': authStub },
- argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1'],
+ argv: [ENV, 'sol', APP, '--page-ids', P1],
});
await cli.main();
assert.equal(emitted[0].ok, false, 'a mid-sequence failure must not report ok:true');
@@ -225,6 +228,34 @@ test('a failing AddSolutionComponent surfaces as a failure, not a silent partial
);
});
+// Ids are checked as GUIDs before ANYTHING is read or written. A malformed page id used to reach
+// Dataverse only at its own AddSolutionComponent — after the app had been added — leaving the solution
+// holding the app without its page.
+test('a malformed page or app id refuses the run before any request', async () => {
+ for (const [argv, named] of [
+ [[ENV, 'sol', APP, '--page-ids', `${P1},not-a-guid`], /page id 'not-a-guid'/],
+ [[ENV, 'sol', 'app-1', '--page-ids', P1], /app id 'app-1'/],
+ [[ENV, 'sol', APP, '--page-ids', `{${P1}}`], /page id '\{/],
+ ]) {
+ const { cli, calls, emitted } = harness({ argv });
+ await cli.main();
+ assert.equal(emitted.length, 1);
+ assert.equal(emitted[0].ok, false);
+ assert.match(emitted[0].payload.message, named);
+ assert.match(emitted[0].payload.message, /Nothing was added to sol/);
+ assert.deepEqual(calls, [], 'no metadata read and no AddSolutionComponent');
+ }
+});
+
+test('a page id or connection reference given twice is added once', async () => {
+ const { cli, calls, emitted } = harness({ argv: [ENV, 'sol', APP, '--page-ids', `${P1},${P1.toUpperCase()},${P2}`, '--connection-refs', 'new_sp,NEW_SP'] });
+ await cli.main();
+ const adds = calls.filter((c) => c.path === 'AddSolutionComponent').map((c) => [c.body.ComponentType, c.body.ComponentId]);
+ assert.deepEqual(adds, [[80, APP], [10372, P1], [10372, P2], [10158, 'cr-1']]);
+ assert.equal(calls.filter((c) => c.method === 'GET' && /connectionreferences\?/.test(c.path)).length, 1, 'one lookup per reference');
+ assert.equal(emitted[0].ok, true);
+});
+
test('the stable app component type and dynamic entity names are pinned', () => {
const {
APPMODULE_COMPONENT_TYPE,
diff --git a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js
index 1d22db4bb..b6ee1a7f5 100644
--- a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js
@@ -8,11 +8,15 @@
// `addElement` at the artifact root adds the key;
// 3. the push PATCHes `aiappdescription` only when the value is set AND differs from the draft row —
// so an equal value, or a spec that leaves it out, never touches a platform-written description;
-// 4. a 412 on that PATCH RESOLVES `{ saved:false }` with a VERSION_CONFLICT error rather than throwing,
-// which is the shape the plugin's pending-draft halt keys on;
-// 5. after such a refused push, a plain fetch refuses to discard the unpushed copy once the server has
-// moved (LOCAL_EDITS_WOULD_BE_LOST), and `{ overwrite: true }` resets it — which is why the halt
-// resets the copy before telling the operator to publish and re-run.
+// 4. a 412 on that PATCH RESOLVES `{ saved:false }` with a VERSION_CONFLICT error naming the refused row
+// rather than throwing, which is the shape the build's concurrent-edit handling keys on — and the
+// header PATCH is conditioned on the appmodule's ROW token (cds-maker-sdk 8930278f), so another
+// writer's UNPUBLISHED header change does not refuse it: only a row moved since the fetch does. The
+// plugin no longer re-explains a 412 as "publish first" because of this;
+// 5. after a refused push, a plain fetch refuses to discard the unpushed copy once the server has
+// moved (LOCAL_EDITS_WOULD_BE_LOST), and `{ overwrite: true }` resets it — which is why the
+// never-published halt resets the copy before telling the operator to publish and re-run, and why a
+// concurrent edit's kept copy stops a blind re-run.
// A re-vendor could change any of them with every plugin test still green, so each is pinned here
// against the real bundle over a fake Dataverse — the same way sitemap-icon-real-bundle.test.js pins
// the sitemap write.
@@ -48,15 +52,22 @@ test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, for
* undefined), `componentstate` its draft state, and `headerStatus` the status the appmodule PATCH answers.
* All three live on the returned `state`, which the fake reads on every call, so a test can change the
* server under the SDK — e.g. the operator publishing between two runs, which also moves the etag.
+ *
+ * `tokens: { row, content }` models the appmodule's two tokens as Dataverse serves them (LIVE-MEASURED): a
+ * plain by-id read answers the ROW version, an unpublished-aware read the CONTENT one, which runs ahead of
+ * the row while a header change is unpublished. A header PATCH then succeeds only with the current ROW
+ * token in `If-Match`, and moves the row (leaving an unpublished layer); without `tokens` every read
+ * answers `state.etag` and `headerStatus` decides the PATCH, as before.
*/
-async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapStatus = 204 } = {}) {
+async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapStatus = 204, tokens } = {}) {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ai-description-'));
tempDirs.push(dir);
const writes = [];
const reads = [];
- const state = { ai, componentstate, headerStatus, sitemapStatus, etag: 'W/"1"' };
- const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Probe', uniquename: APP_UNIQUE, description: 'Tickets', componentstate: state.componentstate, ...(state.ai !== undefined ? { aiappdescription: state.ai } : {}), '@odata.etag': state.etag });
+ const state = { ai, componentstate, headerStatus, sitemapStatus, etag: 'W/"1"', tokens, description: 'Tickets' };
+ const appEtag = (url) => (!state.tokens ? state.etag : /RetrieveUnpublished/i.test(url) ? state.tokens.content : state.tokens.row);
+ const appRow = (etag = state.etag) => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Probe', uniquename: APP_UNIQUE, description: state.description, componentstate: state.componentstate, ...(state.ai !== undefined ? { aiappdescription: state.ai } : {}), '@odata.etag': etag });
const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: SITEMAP_XML, '@odata.etag': state.etag });
const httpClient = {
get: async (url) => {
@@ -82,7 +93,8 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
return { status: 200, headers: {}, body: { value: [{ ...appRow(), componentstate: 0 }, appRow()] } };
}
const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/appmodules\?/.test(url);
- return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [appRow()] } : appRow() };
+ const etag = appEtag(url);
+ return { status: 200, headers: { etag }, body: multi ? { value: [appRow(etag)] } : appRow(etag) };
}
if (/\/roles/.test(url)) return { status: 200, headers: {}, body: { value: [{ roleid: '66666666-6666-6666-6666-666666666666' }] } };
return { status: 200, headers: {}, body: { value: [] } };
@@ -91,8 +103,19 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
writes.push({ verb: 'post', url: String(url), body });
return { status: 204, headers: { 'odata-entityid': `https://x/y(${APP_ID})` }, body: {} };
},
- patch: async (url, body) => {
- writes.push({ verb: 'patch', url: String(url), body });
+ patch: async (url, body, options) => {
+ const ifMatch = (options && options.headers && options.headers['If-Match']) || null;
+ writes.push({ verb: 'patch', url: String(url), body, ifMatch });
+ if (/\/appmodules\(/.test(url) && state.tokens) {
+ if (ifMatch !== state.tokens.row) {
+ return { status: 412, headers: {}, body: { error: { code: '0x80060882', message: 'The version of the existing record doesn\'t match the RowVersion property provided.' } } };
+ }
+ if (body && body.aiappdescription !== undefined) state.ai = body.aiappdescription;
+ const next = Number(/\d+/.exec(state.tokens.content)[0]) + 1;
+ state.tokens = { row: `W/"${next}"`, content: `W/"${next + 1}"` };
+ state.componentstate = 1;
+ return { status: 204, headers: { etag: state.tokens.row }, body: {} };
+ }
if (/\/appmodules\(/.test(url)) {
if (state.headerStatus !== 204) {
// 400 is how Dataverse refuses a header write on a never-published appmodule; the SDK recognises
@@ -174,33 +197,66 @@ test('REAL BUNDLE: an equal value, or a spec without one, never writes the heade
}
});
-test('REAL BUNDLE: a 412 on the header resolves saved:false, and only a PROVEN draft is re-explained', async () => {
- for (const [componentstate, expected] of [[1, 'app-header-unpublished'], [0, 'version-conflict']]) {
+test('REAL BUNDLE: a 412 on the header resolves saved:false naming the appmodule row, and is a concurrent edit whatever the draft state', async () => {
+ for (const componentstate of [1, 0]) {
const { sdk, reads } = await freshSdk({ ai: 'Route Q1', componentstate, headerStatus: 412 });
await sdk.fetchArtifact('app', APP_ID);
assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
const res = await sdk.pushArtifact('app', APP_ID);
- // The by-value shape the halt keys on. Were the SDK to THROW here instead, the plugin's halt would
- // never run and the operator would get a raw SDK error.
+ // The by-value shape the build's concurrent-edit handling keys on. Were the SDK to THROW here instead,
+ // the copy-keeping path would never run and the operator would get a raw SDK error.
assert.strictEqual(res.saved, false);
assert.strictEqual(res.error && res.error.code, 'VERSION_CONFLICT');
- // …and the refused request is named, which is how the halt tells the header's 412 from the sitemap's.
+ // …and the refused request is named.
assert.match(String(res.error.detail), /^Version conflict \(412\) from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v[\d.]+\/appmodules\(11111111-1111-1111-1111-111111111111\)$/);
const readsBefore = reads.length;
- let halt;
- try {
- await haltOnUnpublishedAppHeader(sdk, APP_ID, res, 'Probe');
- requireSuccessfulPush(res, 'app Probe');
- } catch (e) { halt = e; }
- assert.ok(halt, 'the refused push halts');
- assert.strictEqual(halt.code, expected, `componentstate ${componentstate}: ${halt.message}`);
- const draftRead = reads.slice(readsBefore).find((u) => /RetrieveUnpublishedMultiple/.test(u) && /componentstate/.test(u));
- assert.ok(draftRead, 'the draft state is read through the SDK\'s own Dataverse client');
- assert.match(decodeURIComponent(draftRead), /appmoduleid eq 11111111-1111-1111-1111-111111111111/);
+ await haltOnUnpublishedAppHeader(sdk, APP_ID, res, 'Probe'); // a 412 is never re-explained
+ assert.throws(() => requireSuccessfulPush(res, 'app Probe'), (e) => e.code === 'version-conflict', `componentstate ${componentstate}`);
+ assert.ok(!reads.slice(readsBefore).some((u) => /componentstate/.test(decodeURIComponent(u))), 'no draft read');
}
});
+// cds-maker-sdk 8930278f: the header PATCH carries the appmodule's ROW token, read by id, not the content token
+// of the unpublished-aware read, which runs one ahead of the row while a header change is unpublished.
+// LIVE-MEASURED: with the content token (the previous bundle) a header write over another writer's
+// unpublished header change answered 412 although nothing had changed since the fetch; with the row token
+// it saves and keeps that change. The plugin depends on this: it no longer re-explains a 412 as "publish
+// first", so a re-vendor that went back to the content token would turn such a build into a
+// concurrent-edit halt that no re-run clears.
+test('REAL BUNDLE: over another writer\u2019s UNPUBLISHED header change, the header push saves, conditioned on the ROW token', async () => {
+ const { sdk, state, writes } = await freshSdk({ ai: 'Route Q1', componentstate: 1, tokens: { row: 'W/"5"', content: 'W/"6"' } });
+ state.description = 'Saved in Maker, not published';
+ await sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
+ const res = await pushAppHeader(sdk, APP_ID, 'Probe', true);
+ assert.strictEqual(res.saved, true, JSON.stringify(res.error && res.error.message));
+ const header = headerWrites(writes).filter((w) => w.verb === 'patch');
+ assert.deepStrictEqual(header.map((w) => w.ifMatch), ['W/"5"'], 'the row token, never the content token');
+ assert.strictEqual(state.ai, WANT);
+ assert.strictEqual(header[0].body.description, 'Saved in Maker, not published', 'the other writer\u2019s change rides through');
+});
+
+test('REAL BUNDLE: a header row moved after the fetch is a concurrent edit: refused, the generic halt, and the copy kept', async () => {
+ const { sdk, state, reads } = await freshSdk({ ai: 'Route Q1', tokens: { row: 'W/"5"', content: 'W/"5"' } });
+ await sdk.fetchArtifact('app', APP_ID);
+ // Another writer saves a header change after this run's fetch (unpublished): the row moves.
+ Object.assign(state, { componentstate: 1, tokens: { row: 'W/"7"', content: 'W/"8"' }, description: 'Another writer' });
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
+ const readsBefore = reads.length;
+ const res = await pushAppHeader(sdk, APP_ID, 'Probe', true);
+ assert.strictEqual(res.saved, false);
+ assert.strictEqual(res.error && res.error.code, 'VERSION_CONFLICT');
+ assert.throws(() => requireSuccessfulPush(res, 'app Probe'), (e) => e.code === 'version-conflict');
+ assert.ok(!reads.slice(readsBefore).some((u) => /componentstate/.test(decodeURIComponent(u))), 'not re-diagnosed as a pending draft');
+ assert.strictEqual(state.ai, 'Route Q1', 'nothing written');
+ // The copy keeps this run's edit. The app is a composite artifact whose stored token is the sitemap's, and a
+ // header-only change does not move the sitemap, so a plain re-fetch keeps the copy as it is; the next run
+ // that pushes the app refuses it (refuseUnpushedAppCopy) instead of re-sending it over the other change.
+ const listed = (await sdk.listArtifacts('app')).find((a) => a.id === APP_ID);
+ assert.strictEqual(listed && listed.isDirty, true, 'the copy keeps the unpushed edit');
+});
+
// The SDK writes an app header first and its sitemap second. A 412 on the SITEMAP — someone saved a
// sitemap edit since this run's fetch — comes after this push's header write has committed, so the draft
// read finds the unpublished layer that write just left. It is still a concurrent edit: the copy is kept,
@@ -242,33 +298,6 @@ test('REAL BUNDLE: an app edit a failed push left behind is reported dirty, and
assert.strictEqual((await listed()).isDirty, false, 'a fresh fetch clears it');
});
-test('REAL BUNDLE: after the pending-draft halt, "publish, then re-run" really converges', async () => {
- // Run 1 is refused; the operator publishes, which settles the draft and MOVES the server's etag; run 2
- // does exactly what the build does — a plain fetch, then the helper, then a push.
- const run1 = async ({ halt }) => {
- const env = await freshSdk({ ai: 'Route Q1', componentstate: 1, headerStatus: 412 });
- await env.sdk.fetchArtifact('app', APP_ID);
- await applyAppAiDescription(env.sdk, spec(WANT), APP_ID);
- const res = await env.sdk.pushArtifact('app', APP_ID);
- assert.strictEqual(res.saved, false);
- if (halt) await assert.rejects(haltOnUnpublishedAppHeader(env.sdk, APP_ID, res, 'Probe'), (e) => e.code === 'app-header-unpublished' && !/\.maker-workspace/.test(e.message));
- Object.assign(env.state, { componentstate: 0, headerStatus: 204, etag: 'W/"8"' });
- return env;
- };
-
- // CONTROL — why the halt resets the copy: without it, the re-run's plain fetch refuses to discard the
- // refused push's edits now that the server has moved, and the re-run halts again.
- const control = await run1({ halt: false });
- await assert.rejects(control.sdk.fetchArtifact('app', APP_ID), (e) => e && e.code === 'LOCAL_EDITS_WOULD_BE_LOST');
-
- const { sdk, state } = await run1({ halt: true });
- const fetched = await sdk.fetchArtifact('app', APP_ID);
- assert.strictEqual(fetched.aiDescription, 'Route Q1', 'the re-run sees the server again, not the refused edit');
- assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
- assert.strictEqual((await sdk.pushArtifact('app', APP_ID)).saved, true);
- assert.strictEqual(state.ai, WANT, 'the routing description lands on the re-run');
-});
-
test('REAL BUNDLE: a never-published app THROWS its header refusal, and pushAppHeader turns it into the precise halt', async () => {
// The raw SDK throws rather than resolving saved:false — the shape pushAppHeader exists to catch.
const raw = await freshSdk({ headerStatus: 400 });
@@ -276,6 +305,10 @@ test('REAL BUNDLE: a never-published app THROWS its header refusal, and pushAppH
await applyAppAiDescription(raw.sdk, spec(WANT), APP_ID);
// sdk-async-ok: the promise is handed to assert.rejects, which awaits it.
await assert.rejects(raw.sdk.pushArtifact('app', APP_ID), (e) => e && e.code === 'APP_DRAFT_HEADER_NOT_WRITABLE');
+ // CONTROL — why the halt resets the copy: without it, once the operator publishes (the server moves), the
+ // re-run's plain fetch refuses to discard the refused push's edits, and the re-run halts again.
+ Object.assign(raw.state, { headerStatus: 204, etag: 'W/"8"' });
+ await assert.rejects(raw.sdk.fetchArtifact('app', APP_ID), (e) => e && e.code === 'LOCAL_EDITS_WOULD_BE_LOST');
const { sdk, state } = await freshSdk({ headerStatus: 400 });
await sdk.fetchArtifact('app', APP_ID);
diff --git a/plugins/model-apps/scripts/tests/app-spec.test.js b/plugins/model-apps/scripts/tests/app-spec.test.js
index 5adda76c2..f95866ff3 100644
--- a/plugins/model-apps/scripts/tests/app-spec.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec.test.js
@@ -1092,6 +1092,19 @@ test('validateAppSpec REJECTS a non-GUID pages[].pageId', () => {
assert.ok(!validateAppSpec(emptySpec, { profile: 'deploy' }).ok, 'empty pageId is rejected');
});
+// pages[].model is the id a download writes back and the build sends to pac's `--model`, so it is a short token.
+test('validateAppSpec ACCEPTS a model id and REJECTS anything that is not one', () => {
+ const withModel = (model) => v2PagesSpec([{ page: 'overview', title: 'Overview' }, { page: 'order-detail', title: 'Order Detail' }], { model });
+ for (const good of ['gpt-4.1', 'gpt-5-mini', 'org/model:v2_1', 'claude-3-5-sonnet@20240620', 'model+tuned', 'm'.repeat(100)]) {
+ const r = validateAppSpec(withModel(good), { profile: 'deploy' });
+ assert.ok(r.ok, `${good}: ${JSON.stringify(r.errors)}`);
+ }
+ for (const bad of ['', ' gpt-4.1', 'gpt 4.1', '-gpt', 'gpt"4', 'm'.repeat(101), 41, null]) {
+ const r = validateAppSpec(withModel(bad), { profile: 'deploy' });
+ assert.ok(r.errors.some((e) => /page 'overview': model must be a model id such as 'gpt-4\.1'/.test(e)), `${JSON.stringify(bad)}: ${JSON.stringify(r.errors)}`);
+ }
+});
+
// --- entities[].quickCreate (Allow quick create table flag) --------------------------------------
function quickCreateSpec(entityExtra, forms) {
return {
diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.js
index 9163d0791..64c2d73bb 100644
--- a/plugins/model-apps/scripts/tests/build-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js
@@ -318,6 +318,99 @@ test('transient auto-retry: a non-transient halt is NOT retried', async () => {
assert.strictEqual(attempts, 1, 'no retry on a non-transient error');
});
+// With --publish the build defers its default-view enrichment's publish to its final phase
+// (sdk-build.js, 4b), so a build that halts before that phase still owes it. The CLI pays it only once
+// no retry follows: a transient halt is retried at once, and the retry saves the views again and owes
+// their publish again — a publish sent into that throttling would only fail the same way.
+function owingSdk() {
+ const { sdk, calls } = mockSdk();
+ // The mock answers every query with a publisher row, which the form lookup would read as an existing
+ // (id-less) form and republish; a fresh org has none of the sample's forms.
+ const query = sdk.queryRecords;
+ sdk.queryRecords = async (entity, ...rest) => (entity === 'systemform' ? [] : query(entity, ...rest));
+ sdk.enrichDefaultViews = async (logical, cols, o = {}) => {
+ calls.push(['enrichDefaultViews', logical, o]);
+ const updated = [`defview-${logical}`];
+ if (o.publish !== false) return { updated };
+ return { updated, results: [], pendingPublish: [{ scope: { envelope: 'entity', entityLogicalName: logical }, artifacts: [{ type: 'view', id: `defview-${logical}` }] }] };
+ };
+ sdk.publishArtifacts = async (targets) => { calls.push(['publishArtifacts', targets]); return targets.map(({ type, id }) => ({ type, id, shipped: true, publish: { kind: 'verified' } })); };
+ const publishOne = sdk.publishArtifact;
+ sdk.publishArtifact = async (type, id) => { calls.push(['publishArtifact', type, id]); return publishOne(type, id); };
+ return { sdk, calls };
+}
+
+test('a build that halts before its publish phase publishes the default views it enriched, once, after the last retry', async () => {
+ const { sdk, calls } = owingSdk();
+ let retried = false;
+ const create = sdk.createArtifact;
+ sdk.createArtifact = (t, def) => {
+ if (t !== 'app') return create(t, def);
+ calls.push(['attempt']);
+ throw new Error(retried ? 'bad request' : 'CustomizationLockException: try again later');
+ };
+ const journal = { path: 'x', record: (e) => { if (e.status === 'retry') { retried = true; calls.push(['retry']); } }, close: () => {} };
+ await assert.rejects(buildModelApp(desk, { apply: true, publish: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, journal }), /bad request/);
+ const at = (name) => calls.findIndex((c) => c[0] === name);
+ const publishes = calls.filter((c) => c[0] === 'publishArtifacts' || c[0] === 'publishArtifact');
+ assert.strictEqual(calls.filter((c) => c[0] === 'attempt').length, 2, 'one transient retry, then the final halt');
+ assert.strictEqual(publishes.length, 1, `one publish, after the final halt: ${JSON.stringify(publishes)}`);
+ assert.ok(at('retry') < at('publishArtifacts'), 'nothing was published for the retried attempt');
+ const enriched = calls.slice(at('retry')).filter((c) => c[0] === 'enrichDefaultViews' && c[2].publish === false).map((c) => c[1]);
+ assert.ok(enriched.length >= 2, `the retry deferred its enrichment publishes: ${enriched}`);
+ assert.deepStrictEqual(publishes[0][1], enriched.map((l) => ({ type: 'view', id: `defview-${l}` })), 'exactly the tables the final attempt enriched');
+});
+
+test('a final halt whose owed publish fails too warns, and still reports the halt', async () => {
+ const { sdk } = owingSdk();
+ sdk.publishArtifacts = async () => { throw new Error('envelope refused'); };
+ sdk.publishArtifact = async () => { throw new Error('publish down'); };
+ const create = sdk.createArtifact;
+ sdk.createArtifact = (t, def) => { if (t === 'app') throw new Error('bad request'); return create(t, def); };
+ const warnings = [];
+ await assert.rejects(buildModelApp(desk, { apply: true, publish: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, warn: (m) => warnings.push(m) }), /bad request/);
+ const failed = warnings.filter((w) => /^the build stopped before its publish phase; publish view defview-\w+ FAILED: publish down/.test(w));
+ assert.strictEqual(failed.length, 3, `each enriched table is still attempted, and reported: ${warnings.join('\n')}`);
+});
+
+test('without --publish a halted build owes nothing: the enrichment published itself', async () => {
+ const { sdk, calls } = owingSdk();
+ const create = sdk.createArtifact;
+ sdk.createArtifact = (t, def) => { if (t === 'app') throw new Error('bad request'); return create(t, def); };
+ await assert.rejects(buildModelApp(desk, { apply: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk }), /bad request/);
+ assert.ok(calls.some((c) => c[0] === 'enrichDefaultViews'), 'the enrichment ran');
+ assert.ok(calls.filter((c) => c[0] === 'enrichDefaultViews').every((c) => c[2].publish !== false), 'not deferred');
+ assert.deepStrictEqual(calls.filter((c) => c[0] === 'publishArtifacts' || c[0] === 'publishArtifact'), []);
+});
+
+// Every attempt re-runs every phase, but a later one can halt before the enrichment an earlier one did, so
+// what each failed attempt owed is kept until a publish phase pays it, and the final halt settles all of it.
+const quietState = { collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null };
+const owing = (message, owedPublishes, owedPaid) => Object.defineProperties(new Error(message), {
+ ...(owedPublishes ? { owedPublishes: { value: owedPublishes } } : {}),
+ ...(owedPaid !== undefined ? { owedPaid: { value: owedPaid } } : {}),
+});
+const TRANSIENT = 'CustomizationLockException: try again later';
+async function haltAfter(attempts) {
+ const { sdk, calls } = owingSdk();
+ let n = 0;
+ const runBuild = async () => { throw attempts[n++]; };
+ await assert.rejects(buildModelApp(desk, { apply: true, publish: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, runBuild, discoverOpDiffState: async () => quietState }), /bad request/);
+ assert.strictEqual(n, attempts.length, 'every attempt ran');
+ return calls.filter((c) => c[0] === 'publishArtifacts' || c[0] === 'publishArtifact');
+}
+
+test('an earlier attempt\u2019s owed publishes are settled when a later attempt halts before its own enrichment', async () => {
+ const publishes = await haltAfter([owing(TRANSIENT, [['view', 'defview-a'], ['view', 'defview-b']]), owing('bad request')]);
+ assert.deepStrictEqual(publishes.map((c) => c[1].map((t) => t.id)), [['defview-a', 'defview-b']]);
+});
+
+test('a later attempt whose publish phase ran pays what an earlier one owed, and a debt owed twice is published once', async () => {
+ assert.deepStrictEqual(await haltAfter([owing(TRANSIENT, [['view', 'defview-a']]), owing('bad request', [], true)]), [], 'nothing left to settle');
+ const twice = await haltAfter([owing(TRANSIENT, [['view', 'defview-a'], ['view', 'defview-b']]), owing('bad request', [['view', 'defview-b'], ['view', 'defview-a']])]);
+ assert.deepStrictEqual(twice.map((c) => c[1].map((t) => t.id)), [['defview-a', 'defview-b']]);
+});
+
test('transient auto-retry: no retries in dry-run', async () => {
const { sdk } = mockSdk();
const r = await buildModelApp(desk, { apply: false, env: 'https://x' }, { sdk });
@@ -1907,3 +2000,282 @@ test('#587 a plain --apply calls the snapshot guard before building', () => {
assert.match(before, /if \(opts\.apply\) assertSnapshotInvalidated\(applySnapshotStore, workspaceDir\);/,
'the guard must run, gated on apply, immediately before the mutation engine');
});
+
+test('main changed-only full-fast-noop cycle uses the real flow', async () => {
+ const os = require('node:os');
+ const { loadCli } = require('./helpers/cli-harness.js');
+ const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+ const snapshotStore = require('../lib/apply-snapshot-store.js');
+ const { sha256 } = require('../lib/hash.js');
+ const { makeGenpageCli } = require('../lib/genpage-cli.js');
+ const scriptsDir = path.join(__dirname, '..');
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'main-changed-only-'));
+ const workspaceDir = path.join(appDir, '.maker-workspace');
+ const specPath = path.join(appDir, 'app-spec.json');
+ const env = 'https://contoso.crm.dynamics.com';
+ const orgId = '11111111-0000-4000-8000-000000000001';
+ const appIds = ['22222222-0000-4000-8000-000000000001', '22222222-0000-4000-8000-000000000002', '22222222-0000-4000-8000-000000000003'];
+ const appUniqueValue = '33333333-0000-4000-8000-000000000001';
+ const sitemapId = '44444444-0000-4000-8000-000000000001';
+ const pageIds = {
+ Overview: '55555555-0000-4000-8000-000000000001',
+ Detail: '55555555-0000-4000-8000-000000000002',
+ };
+ const spec = {
+ ...pageBearingSpec(),
+ solution: { uniqueName: 'ChangedOnlySln', publisherPrefix: 'contoso' },
+ app: { name: 'Renamed App', uniqueName: 'contoso_liveidentity' },
+ entities: [{ schemaName: 'contoso_item', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],
+ pages: [
+ { key: 'overview', name: 'Overview', navigatesTo: [{ targetKey: 'detail' }], source: { kind: 'tsx', codeFile: 'overview.tsx' } },
+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },
+ ],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: [{ page: 'overview' }, { page: 'detail' }] }] }] },
+ };
+ const state = { orgId, app: null, creates: 0, table: null, resources: new Map(), pages: new Map(), failDownload: false };
+ const { sdk } = makeSimpleMockSdk();
+ const writes = [];
+ const uploads = [];
+ const whoAmI = [];
+ const sdkTempDirs = [];
+ const uploadTempDirs = [];
+ const createArtifact = sdk.createArtifact;
+ sdk.createArtifact = (type, def) => {
+ if (type !== 'app') return createArtifact(type, def);
+ state.app = { ...jclone(def), id: appIds[state.creates++] };
+ return jclone(state.app);
+ };
+ sdk.initWorkspace = async () => {};
+ sdk.listArtifacts = async () => state.app ? [{ id: state.app.id, isDirty: false }] : [];
+ sdk.findArtifact = async (type, identity) => {
+ assert.strictEqual(type, 'app');
+ assert.strictEqual(identity.uniqueName, spec.app.uniqueName, 'rebuild resolves the immutable app name');
+ return state.app && state.app.id;
+ };
+ sdk.fetchArtifact = async (type, id) => {
+ assert.strictEqual(type, 'app');
+ assert.strictEqual(id, state.app.id);
+ return jclone(state.app);
+ };
+ sdk.getArtifact = async (type, id) => {
+ assert.strictEqual(type, 'app');
+ assert.strictEqual(id, state.app.id);
+ return jclone(state.app);
+ };
+ sdk.updateElement = async (type, id, pointer, value) => {
+ assert.strictEqual(type, 'app');
+ assert.strictEqual(id, state.app.id);
+ jpSet(state.app, pointer, jclone(value));
+ return jclone(state.app);
+ };
+ sdk.createTable = async (o) => {
+ state.table = { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, isCustom: true };
+ return state.table;
+ };
+ sdk.findTables = async () => state.table ? [state.table] : [];
+ sdk.findColumns = async () => [{ logicalName: 'contoso_name' }];
+ sdk.createWebResource = async (o) => {
+ const row = { webresourceid: `wr-${state.resources.size + 1}`, name: o.name, content: Buffer.from(o.content || '', 'utf8').toString('base64') };
+ state.resources.set(o.name, row);
+ return { id: row.webresourceid, name: row.name };
+ };
+ sdk.updateWebResource = async (id, o) => {
+ const row = [...state.resources.values()].find((r) => r.webresourceid === id);
+ assert.ok(row, `web resource ${id} exists`);
+ row.content = Buffer.from(o.content, 'utf8').toString('base64');
+ };
+ sdk.dataverse = { get: async (url) => {
+ assert.match(url, /^\/EntityDefinitions\(LogicalName='/);
+ return state.table && !url.includes("LogicalName='entity'")
+ ? { status: 200, body: { LogicalName: state.table.logicalName, EntitySetName: state.table.entitySetName } }
+ : { status: 404, body: {} };
+ } };
+ sdk.queryRecords = async (set, o = {}) => {
+ const filter = o.filter || '';
+ if (set === 'appmodule') {
+ if (filter) assert.strictEqual(filter, `uniquename eq '${spec.app.uniqueName}'`);
+ return state.app ? [{ appmoduleid: state.app.id, appmoduleidunique: appUniqueValue, uniquename: spec.app.uniqueName }] : [];
+ }
+ if (set === 'appmodulecomponent') {
+ assert.match(filter, new RegExp(`_appmoduleidunique_value eq ${appUniqueValue}`));
+ return /componenttype eq 62/.test(filter) ? [{ objectid: sitemapId, componenttype: 62 }] : [];
+ }
+ if (set === 'sitemap') {
+ if (/sitemapnameunique eq/.test(filter)) return [{ sitemapid: sitemapId }];
+ assert.strictEqual(filter, `sitemapid eq ${sitemapId}`);
+ // Render the page membership from the real engine's app definition, not from the desired spec.
+ const subareas = state.app.siteMap.areas.flatMap((a) => a.groups.flatMap((g) => g.subAreas || []));
+ return [{ sitemapxml: `<SiteMap><Area><Group>${subareas.filter((s) => s.genPageId).map((s) => `<SubArea GenPageId="${s.genPageId}"/>`).join('')}</Group></Area></SiteMap>` }];
+ }
+ if (set === 'webresource') {
+ const name = (filter.match(/name eq '([^']+)'/) || [])[1];
+ const row = state.resources.get(name);
+ return row ? [row] : [];
+ }
+ if (set === 'publisher') return [{ publisherid: 'publisher-1' }];
+ return [];
+ };
+ for (const method of Object.keys(sdk).filter((name) => /^(create|update|push|publish|add|remove|set|enrich|seed)/.test(name))) {
+ const original = sdk[method];
+ sdk[method] = (...args) => { writes.push({ method, args }); return original(...args); };
+ }
+ const pacRun = async (args) => {
+ const value = (flag) => args[args.indexOf(flag) + 1];
+ assert.deepStrictEqual(args.slice(0, 2), ['model', 'genpage']);
+ assert.strictEqual(value('--environment'), env);
+ if (args[2] === 'list') {
+ const pages = [...state.pages.values()];
+ return { status: 0, stdout: `Found ${pages.length} generated page(s):\nPage ID Name Published\n`
+ + pages.map((p) => `${p.pageId} ${p.name.padEnd(14)}-\n`).join(''), stderr: '' };
+ }
+ assert.strictEqual(value('--app-id'), state.app.id, 'PAC is scoped to the app resolved by main');
+ if (args[2] === 'upload') {
+ const name = value('--name');
+ const pageId = args.includes('--page-id') ? value('--page-id') : pageIds[name];
+ const code = fs.readFileSync(value('--code-file'), 'utf8');
+ uploads.push({ name, pageId, requestedId: args.includes('--page-id') ? value('--page-id') : null, code });
+ uploadTempDirs.push(path.dirname(value('--prompt-file')));
+ state.pages.set(pageId, { pageId, name, code });
+ return { status: 0, stdout: `Page ID: ${pageId}`, stderr: '' };
+ }
+ assert.strictEqual(args[2], 'download', 'no other PAC command is allowed');
+ if (state.failDownload) return { status: 1, stdout: '', stderr: 'offline verification download failed' };
+ for (const pageId of value('--page-id').split(',')) {
+ const dir = path.join(value('--output-directory'), pageId);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'page.tsx'), state.pages.get(pageId).code, 'utf8');
+ }
+ return { status: 0, stdout: '', stderr: '' };
+ };
+ const genpageModule = { ...require('../lib/genpage-cli.js'), makeGenpageCli: (url) => {
+ assert.strictEqual(url, env);
+ return makeGenpageCli(url, { run: pacRun, attempts: 1, request: async () => { throw new Error('unexpected Dataverse page request'); } });
+ } };
+ // Only transport/SDK construction is fake: main, buildModelApp, engine, verifier, flow and snapshot
+ // store remain real. Loading the engine with the PAC seam avoids replacing the build with a stub.
+ const engine = loadCli(path.join(scriptsDir, 'lib', 'sdk-build.js'), { requires: { './genpage-cli.js': genpageModule } }).exports;
+ const previousPath = process.env.PATH;
+ process.env.PATH = path.dirname(process.execPath);
+ const assertCleaned = () => {
+ for (const dir of [...sdkTempDirs, ...uploadTempDirs]) assert.strictEqual(fs.existsSync(dir), false, `temporary workspace removed: ${dir}`);
+ assert.strictEqual(fs.existsSync(snapshotStore.leasePath(workspaceDir)), false, 'snapshot lease released');
+ const staging = path.join(workspaceDir, '.pageref-deploy');
+ assert.ok(!fs.existsSync(staging) || fs.readdirSync(staging).length === 0, 'page staging removed');
+ };
+ const runMain = async (exitCode = 0) => {
+ writes.length = uploads.length = 0;
+ const authCli = loadCli(path.join(scriptsDir, 'lib', 'dataverse-auth.js'));
+ const auth = {
+ ...authCli.exports,
+ preflightAuth: async (url) => { assert.strictEqual(url, env); return { ok: true }; },
+ readOrgLanguageCode: async (url) => { assert.strictEqual(url, env); return 1033; },
+ dataverseRequest: async (...args) => {
+ assert.deepStrictEqual(args, [env, 'GET', 'WhoAmI']);
+ whoAmI.push(state.orgId);
+ return { status: 200, data: { OrganizationId: state.orgId } };
+ },
+ emitResult: (ok, result) => { assertCleaned(); authCli.exports.emitResult(ok, result); },
+ };
+ const entityProvision = loadCli(path.join(scriptsDir, 'lib', 'entity-provision.js'), { requires: { './dataverse-auth.js': auth } }).exports;
+ const cli = loadCli(path.join(scriptsDir, 'build-model-app.js'), {
+ argv: ['--env', env, '--spec', '@' + specPath, '--apply', '--changed-only'],
+ env: { PATH: path.dirname(process.execPath), POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' },
+ requires: {
+ './lib/dataverse-auth.js': auth,
+ './lib/entity-provision.js': entityProvision,
+ './lib/sdk-build.js': engine,
+ './lib/genpage-cli.js': genpageModule,
+ './lib/sdk-http-client.js': { createAzHttpClient: () => ({}), SQL_DEADLOCK_VICTIM: /Sql Number: 1205/ },
+ './vendor/cds-maker-sdk.cjs': {
+ createNodeWorkspaceStorage: (dir) => { if (dir !== workspaceDir) sdkTempDirs.push(dir); return { dir }; },
+ createMakerSdk: (o) => { assert.strictEqual(o.instanceUrl, env); assert.strictEqual(o.languageCode, 1033); return sdk; },
+ },
+ },
+ });
+ await assert.rejects(cli.main(), (e) => e.exitCode === exitCode, cli.stderrText());
+ assert.strictEqual(authCli.exitCode, exitCode, 'the real emitter uses effective build/verify success');
+ assertCleaned();
+ return JSON.parse(authCli.stdoutText());
+ };
+ try {
+ const overviewCode = 'export default function Overview(){ Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" }); return null; }';
+ fs.writeFileSync(specPath, JSON.stringify(spec), 'utf8');
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), overviewCode, 'utf8');
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), 'export default function Detail(){ return null; }', 'utf8');
+ const full = await runMain();
+ assert.strictEqual(full.ok, true);
+ assert.strictEqual(full.verify.ok, true);
+ assert.strictEqual(full.changedOnly.decision, 'full');
+ assert.deepStrictEqual(uploads.map((u) => u.name).sort(), ['Detail', 'Overview']);
+ assert.ok(writes.some((w) => w.method === 'createTable'), 'first apply runs the data model');
+ const baseline = snapshotStore.readSnapshot(workspaceDir);
+ assert.strictEqual(baseline.eligible, true, 'a verified fresh full apply establishes eligibility');
+ assert.strictEqual(baseline.orgId, orgId);
+ assert.strictEqual(baseline.envUrl, env);
+ assert.strictEqual(baseline.appUniqueName, spec.app.uniqueName);
+ assert.strictEqual(baseline.appId, appIds[0]);
+ assert.deepStrictEqual(baseline.debt, []);
+ assert.deepStrictEqual(Object.keys(baseline.artifacts.pages).sort(), ['detail', 'overview']);
+ assert.strictEqual(baseline.artifacts.pages.detail.pageId, pageIds.Detail);
+ assert.strictEqual(whoAmI.length, 2, 'main resolves fresh identity before and after the full build');
+
+ const changedCode = overviewCode.replace('return null;', 'const revised = true; return null;');
+ const deployedCode = changedCode.replace('"PAGEREF_detail"', JSON.stringify(pageIds.Detail));
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), changedCode, 'utf8');
+ const fast = await runMain();
+ assert.strictEqual(fast.ok, true);
+ assert.strictEqual(fast.changedOnly.decision, 'fast');
+ assert.strictEqual(fast.verify.ok, true);
+ assert.deepStrictEqual(fast.changedOnly.pageKeys, ['overview']);
+ assert.deepStrictEqual(uploads, [{ name: 'Overview', pageId: pageIds.Overview, requestedId: pageIds.Overview, code: deployedCode }]);
+ assert.ok(writes.every((w) => w.method === 'updateWebResource' || (w.method === 'addSolutionComponent' && w.args[0].componentType === 61)),
+ `fast apply writes only the page manifest, never the data model or sitemap: ${JSON.stringify(writes)}`);
+ const eligible = snapshotStore.readSnapshot(workspaceDir);
+ assert.strictEqual(eligible.eligible, true);
+ assert.notStrictEqual(eligible.generation, baseline.generation);
+ assert.strictEqual(eligible.artifacts.pages.overview.sourceSha, sha256(changedCode));
+ assert.strictEqual(eligible.artifacts.pages.overview.deployedSha, sha256(deployedCode), 'snapshot records the actual nav-resolved upload, not the canonical source hash');
+ assert.deepStrictEqual(eligible.artifacts.pages.detail, baseline.artifacts.pages.detail, 'unchanged page identity and hashes survive');
+
+ const snapshotBytes = fs.readFileSync(snapshotStore.snapshotPath(workspaceDir));
+ const noop = await runMain();
+ assert.strictEqual(noop.ok, true);
+ assert.strictEqual(noop.noop, true);
+ assert.strictEqual(noop.changedOnly.decision, 'noop');
+ assert.deepStrictEqual(writes, [], 'NOOP makes no SDK writes');
+ assert.deepStrictEqual(uploads, [], 'NOOP makes no PAC writes');
+ assert.deepStrictEqual(fs.readFileSync(snapshotStore.snapshotPath(workspaceDir)), snapshotBytes, 'NOOP leaves the snapshot byte-identical');
+
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), changedCode + '\n', 'utf8');
+ state.failDownload = true;
+ const failedVerify = await runMain(1);
+ assert.strictEqual(failedVerify.ok, true, 'the upload succeeded, but verification did not');
+ assert.strictEqual(failedVerify.changedOnly.decision, 'fast');
+ assert.strictEqual(failedVerify.verify.ok, false);
+ assert.ok(failedVerify.verify.missing.some((m) => /offline verification download failed/.test(m)));
+ assert.strictEqual(snapshotStore.readSnapshot(workspaceDir).eligible, false, 'failed verification cannot re-bless the baseline');
+ state.failDownload = false;
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), changedCode, 'utf8');
+
+ for (const identity of ['foreign-org', 'foreign-app', 'deleted']) {
+ snapshotStore.writeSnapshotAtomic(workspaceDir, eligible);
+ state.orgId = identity === 'foreign-org' ? '11111111-0000-4000-8000-000000000002' : orgId;
+ if (identity === 'foreign-app') state.app.id = appIds[2];
+ if (identity === 'deleted') state.app = null;
+ const fallback = await runMain();
+ assert.strictEqual(fallback.ok, true);
+ assert.strictEqual(fallback.changedOnly.decision, 'full', `${identity} identity cannot NOOP`);
+ assert.strictEqual(fallback.verify.ok, true);
+ assert.match(fallback.changedOnly.reason, identity === 'foreign-org' ? /orgId/ : identity === 'foreign-app' ? /appId/ : /app not found live/);
+ assert.deepStrictEqual(uploads.map((u) => u.name).sort(), ['Detail', 'Overview'], 'identity fallback runs all pages');
+ assert.ok(writes.some((w) => w.method === 'updateElement' && w.args[2] === '/siteMap'), 'identity fallback performs a full sitemap build');
+ assert.strictEqual(fallback.created.app, identity === 'foreign-org' ? appIds[0] : identity === 'foreign-app' ? appIds[2] : appIds[1]);
+ assert.strictEqual(snapshotStore.readSnapshot(workspaceDir).eligible, identity === 'deleted', 'only the proven fresh replacement is eligible');
+ }
+ } finally {
+ process.env.PATH = previousPath;
+ for (const dir of [...sdkTempDirs, ...uploadTempDirs]) fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(appDir, { recursive: true, force: true });
+ }
+ assert.strictEqual(fs.existsSync(appDir), false, 'the test removes its durable temporary state too');
+});
diff --git a/plugins/model-apps/scripts/tests/capture-fixture.test.js b/plugins/model-apps/scripts/tests/capture-fixture.test.js
index 8b79d092b..149d72afa 100644
--- a/plugins/model-apps/scripts/tests/capture-fixture.test.js
+++ b/plugins/model-apps/scripts/tests/capture-fixture.test.js
@@ -5,6 +5,7 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
+const { loadCli } = require('./helpers/cli-harness.js');
const script = path.join(__dirname, '..', 'capture-fixture.js');
const {
@@ -358,3 +359,155 @@ test('CLI: --force overwrites existing fixture', () => {
fs.rmSync(fixtureDir, { recursive: true, force: true });
}
});
+
+// Every other CLI success path passes --skip-verify, so a capture that never starts the runners —
+// or that prints their TAP failures as a clean pass — stays green. The runners are the real files
+// the CLI resolves from __dirname; loadCli does not inject __dirname, so the test points that free
+// variable at an isolated tree before compiling. The documented review rule is "both `failures`
+// arrays empty → good to commit", so a runner that produced no verdict (nonzero exit without a
+// failing assertion, or no assertions at all) must land in `failures`, not leave them empty.
+test('default capture executes both layers and reports runner failure', async () => {
+ const root = mkTempDir('capture-tree-');
+ const scriptsDir = path.join(root, 'plugins', 'model-apps', 'scripts');
+ const evalDir = path.join(root, 'evals', 'model-apps', 'genpage');
+ const marker = path.join(root, 'runners.log');
+ const working = mkTempDir('capture-work-');
+ const prevDirname = global.__dirname;
+ const prevLog = console.log;
+ const prevErr = console.error;
+ const logs = [];
+ const errs = [];
+ const envKeys = ['CAPTURE_MARKER', 'CAPTURE_L1_TAP', 'CAPTURE_L1_CODE', 'CAPTURE_L2_TAP', 'CAPTURE_L2_CODE'];
+ const savedEnv = Object.fromEntries(envKeys.map((k) => [k, process.env[k]]));
+
+ function runnerSource(layer) {
+ return `'use strict';
+const fs = require('node:fs');
+if (process.env.CAPTURE_MARKER) {
+ fs.appendFileSync(process.env.CAPTURE_MARKER, ${JSON.stringify(String(layer))} + ' ' + process.argv.slice(2).join(' ') + '\\n');
+}
+const tap = process.env.CAPTURE_L${layer}_TAP;
+if (tap) process.stdout.write(tap);
+process.exit(Number(process.env.CAPTURE_L${layer}_CODE || 0));
+`;
+ }
+
+ function looksVerified(layer) {
+ return Boolean(layer && layer.fail === 0 && layer.pass > 0 && (layer.failures || []).length === 0);
+ }
+
+ try {
+ writeFiles(root, {
+ 'evals/model-apps/genpage/evals.json': JSON.stringify({ evals: [{ id: 4 }] }),
+ 'evals/model-apps/genpage/run-layer-1.js': runnerSource(1),
+ 'evals/model-apps/genpage/run-layer-2.js': runnerSource(2),
+ });
+ writeFiles(working, {
+ 'page.tsx': 'export default function GeneratedComponent() { return null; }\n',
+ 'notes/ignore.md': 'not captured — subdirectories are skipped\n',
+ });
+ fs.mkdirSync(scriptsDir, { recursive: true });
+ console.log = (...args) => { logs.push(args.map(String).join(' ')); };
+ console.error = (...args) => { errs.push(args.map(String).join(' ')); };
+ global.__dirname = scriptsDir;
+ process.env.CAPTURE_MARKER = marker;
+
+ function run(extraArgs, env) {
+ logs.length = 0;
+ errs.length = 0;
+ fs.writeFileSync(marker, '');
+ for (const [k, v] of Object.entries(env)) process.env[k] = v;
+ const cli = loadCli(script, {
+ argv: ['--working-dir', working, '--eval', '4', '--slug', 'runner-gap', '--force', ...extraArgs],
+ });
+ cli.main();
+ const summary = logs.length ? JSON.parse(logs[logs.length - 1]) : null;
+ return { cli, summary, marker: fs.readFileSync(marker, 'utf8'), errs: errs.slice() };
+ }
+
+ const skipped = run(['--skip-verify'], { CAPTURE_L1_CODE: '1', CAPTURE_L2_CODE: '1' });
+ assert.equal(skipped.cli.exitCode, null);
+ assert.equal(skipped.marker, '', '--skip-verify must not start either runner');
+ assert.equal(skipped.summary.layer1, undefined);
+ assert.equal(skipped.summary.layer2, undefined);
+ assert.ok(skipped.summary.fixtureDir.startsWith(path.join(evalDir, 'fixtures')), skipped.summary.fixtureDir);
+
+ const failingTap = [
+ 'TAP version 13',
+ '# tests 3',
+ '# pass 2',
+ '# fail 1',
+ '# skip 0',
+ ' not ok 2 - runner refused the captured fixture',
+ '',
+ ].join('\n');
+ const failed = run([], {
+ CAPTURE_L1_TAP: failingTap,
+ CAPTURE_L1_CODE: '1',
+ CAPTURE_L2_TAP: '# tests 4\n# pass 4\n# fail 0\n# skip 0\n',
+ CAPTURE_L2_CODE: '0',
+ });
+ assert.equal(failed.marker, '1 --eval 4\n2 --eval 4\n', 'both layers run, scoped to the captured eval id');
+ assert.equal(failed.summary.layer1.fail, 1);
+ assert.deepEqual(failed.summary.layer1.failures, ['not ok 2 - runner refused the captured fixture']);
+ assert.equal(failed.summary.layer2.pass, 4);
+ assert.deepEqual(failed.summary.layer2.failures, []);
+ assert.equal(looksVerified(failed.summary.layer1), false);
+ // The runner's status is reported; the process still exits 0 — the files were captured, and the
+ // summary is how a capture is judged.
+ assert.equal(failed.summary.layer1.exitCode, 1);
+ assert.equal(failed.summary.layer2.exitCode, 0);
+ assert.equal(failed.cli.exitCode, null);
+
+ const empty = run([], { CAPTURE_L1_TAP: '', CAPTURE_L1_CODE: '1', CAPTURE_L2_TAP: '', CAPTURE_L2_CODE: '2' });
+ assert.deepEqual(empty.summary.layer1, { tests: 0, pass: 0, fail: 0, skip: 0, exitCode: 1,
+ failures: ['runner exited 1 without reporting a failing assertion — its result is not verified'] });
+ assert.deepEqual(empty.summary.layer2, { tests: 0, pass: 0, fail: 0, skip: 0, exitCode: 2,
+ failures: ['runner exited 2 without reporting a failing assertion — its result is not verified'] });
+ assert.equal(looksVerified(empty.summary.layer1), false, 'empty runner output is not a verified pass');
+ assert.equal(empty.cli.exitCode, null);
+
+ // A runner that exits 0 having checked nothing has verified nothing.
+ const none = run([], { CAPTURE_L1_TAP: '# tests 0\n# pass 0\n# fail 0\n# skip 0\n', CAPTURE_L1_CODE: '0',
+ CAPTURE_L2_TAP: '# tests 2\n# pass 2\n# fail 0\n# skip 0\n', CAPTURE_L2_CODE: '0' });
+ assert.deepEqual(none.summary.layer1.failures, ['runner reported no assertions for this eval — nothing was verified']);
+ assert.deepEqual(none.summary.layer2.failures, [], 'a real pass stays clean');
+
+ const malformed = run([], {
+ CAPTURE_L1_TAP: 'this is not tap\n not ok 1 - malformed runner output\n',
+ CAPTURE_L1_CODE: '3',
+ CAPTURE_L2_TAP: 'also not tap\n',
+ CAPTURE_L2_CODE: '3',
+ });
+ assert.deepEqual(malformed.summary.layer1.failures, ['not ok 1 - malformed runner output']);
+ assert.equal(malformed.summary.layer1.pass, 0);
+ assert.equal(looksVerified(malformed.summary.layer1), false, 'malformed runner output must not look verified');
+ assert.equal(looksVerified(malformed.summary.layer2), false);
+
+ // A runner that exits nonzero while printing a clean-looking TAP summary has not passed: its exit
+ // code was computed and then dropped, so this used to read as a verified capture.
+ const hidden = run([], {
+ CAPTURE_L1_TAP: '# tests 5\n# pass 5\n# fail 0\n# skip 0\n',
+ CAPTURE_L1_CODE: '1',
+ CAPTURE_L2_TAP: '# tests 1\n# pass 1\n# fail 0\n# skip 0\n',
+ CAPTURE_L2_CODE: '1',
+ });
+ assert.equal(hidden.summary.layer1.pass, 5);
+ assert.equal(hidden.summary.layer1.fail, 0);
+ assert.equal(hidden.summary.layer1.exitCode, 1);
+ assert.deepEqual(hidden.summary.layer1.failures, ['runner exited 1 without reporting a failing assertion — its result is not verified']);
+ assert.equal(hidden.cli.exitCode, null);
+ assert.equal(looksVerified(hidden.summary.layer1), false, 'a nonzero runner exit is never a verified pass');
+ } finally {
+ console.log = prevLog;
+ console.error = prevErr;
+ if (prevDirname === undefined) delete global.__dirname;
+ else global.__dirname = prevDirname;
+ for (const k of envKeys) {
+ if (savedEnv[k] === undefined) delete process.env[k];
+ else process.env[k] = savedEnv[k];
+ }
+ fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(working, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/check-auth.test.js b/plugins/model-apps/scripts/tests/check-auth.test.js
index c8f02640f..adfc0c6fd 100644
--- a/plugins/model-apps/scripts/tests/check-auth.test.js
+++ b/plugins/model-apps/scripts/tests/check-auth.test.js
@@ -12,7 +12,9 @@ test('check-auth.js enumerates all blocker codes', () => {
for (const code of [
'az_missing',
'az_not_logged_in',
+ 'az_timeout',
'pac_not_logged_in',
+ 'pac_timeout',
'no_env_url',
'whoami_403',
'whoami_401',
@@ -138,9 +140,23 @@ function makeExec({ azVersion = 'azure-cli 2.60.0', azUser = '[email protected]'
// `pac org who` runs through the async execFile so its cold start overlaps the az probes. The
// callback is deferred with setImmediate, like a real child that exits while the synchronous az
// calls hold the event loop.
-function makeExecFile({ pacOrg = null, azUser = '[email protected]', azVersion = 'azure-cli 2.60.0' }, calls) {
- return (cmd, args, _opts, cb) => {
+// What execFile hands the callback when `timeout` elapses: the child was killed, with the kill signal.
+const timedOut = (cmd) => Object.assign(new Error(`Command failed: ${cmd}`), { killed: true, signal: 'SIGTERM', code: null });
+
+function makeExecFile({ pacOrg = null, azUser = '[email protected]', azVersion = 'azure-cli 2.60.0', slow = [], notOnPath = [] }, calls) {
+ return (cmd, args, opts, cb) => {
const argv = (args || []).join(' ');
+ // Starting a CLI can also THROW instead of calling back — Node's execFile throws synchronously on some launch
+ // errors. check-auth must read that throw like any launch failure, never crash on it.
+ if (notOnPath.includes(cmd)) {
+ calls.push(`not on PATH: ${cmd} ${argv}`);
+ throw Object.assign(new Error(`spawn ${cmd} ENOENT: not found on PATH`), { code: 'ENOENT' });
+ }
+ if (slow.some((what) => `${cmd} ${argv}`.includes(what))) {
+ calls.push(`${cmd} ${argv} (timeout ${opts && opts.timeout})`);
+ process.nextTick(() => cb(timedOut(`${cmd} ${argv}`), '', ''));
+ return { stdin: { end() {} }, kill() { calls.push(`kill ${cmd} ${argv}`); } };
+ }
if (cmd === 'az' && argv.includes('account show')) {
calls.push(`az ${argv}`);
process.nextTick(() => {
@@ -216,7 +232,7 @@ function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', a
};
}
-async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows }) {
+async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows, tokenFailure = null }) {
const calls = [];
const cli = loadCli(scriptPath, {
argv,
@@ -232,8 +248,10 @@ async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows }) {
},
getAuthTokenAsync: async (url) => {
calls.push(`token ${url}`);
- return 'token-value';
+ return tokenFailure ? null : 'token-value';
},
+ tokenFailureKind: () => tokenFailure,
+ tokenFailureMessage: (url, fallback) => (tokenFailure === 'timeout' ? `token for ${url} timed out` : fallback),
dataverseRequest: async () => {
calls.push('whoami');
if (whoAmIThrows) throw new Error(whoAmIThrows);
@@ -272,6 +290,8 @@ async function runWithAsyncChildren({ argv = [], exec = {}, token, whoAmI } = {}
calls.push(`token ${url}`);
return typeof token === 'function' ? token(calls) : 'token-value';
},
+ tokenFailureKind: () => null,
+ tokenFailureMessage: (url, fallback) => fallback,
dataverseRequest: async () => {
calls.push('whoami');
return whoAmI || { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };
@@ -297,6 +317,16 @@ test('a missing az CLI blocks with az_missing, and no token or WhoAmI is attempt
assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));
});
+// A launch that THROWS instead of calling back (Node's execFile does, synchronously, for some launch errors) is a verdict
+// like any other launch failure — here az_missing — not a crash of the pre-flight.
+test('an az launch that throws synchronously still blocks with a verdict (az_missing)', async () => {
+ const r = await run({ argv: ['--env', ENVURL], exec: { notOnPath: ['az'] } });
+ assert.equal(r.ok, false);
+ assert.equal(r.blocker, 'az_missing');
+ assert.ok(r.calls.some((c) => c.startsWith('not on PATH: az ')), r.calls.join(' | '));
+ assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));
+});
+
test('az installed but logged out blocks with az_not_logged_in', async () => {
const r = await run({ argv: ['--env', ENVURL], exec: { azUser: null } });
assert.equal(r.blocker, 'az_not_logged_in');
@@ -305,6 +335,67 @@ test('az installed but logged out blocks with az_not_logged_in', async () => {
assert.ok(r.calls.includes('az --version'), r.calls.join(' | '));
});
+// A slow Azure CLI is reported as SLOW. A cached-token read was measured at 44.6 s on a busy machine,
+// past the old 30 s budget; check-auth then called the installed CLI "not installed" (az_missing), and
+// the token path said "run az login" — neither of which fixes anything.
+test('an az probe that runs out of time blocks with az_timeout — not az_missing or az_not_logged_in', async () => {
+ for (const slow of ['account show', '--version']) {
+ const exec = slow === '--version' ? { azUser: null, slow: ['az --version'] } : { slow: ['az account show'] };
+ const r = await run({ argv: ['--env', ENVURL], exec });
+ assert.equal(r.ok, false, slow);
+ assert.equal(r.blocker, 'az_timeout', slow);
+ assert.match(r.message, /did not answer within 60 s[\s\S]*POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000/, slow);
+ assert.ok(r.calls.some((c) => /\(timeout 60000\)$/.test(c)), `the az budget is 60 s: ${r.calls.join(' | ')}`);
+ assert.ok(r.calls.includes('kill pac org who'), `the pac probe is cancelled: ${r.calls.join(' | ')}`);
+ assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));
+ }
+ // An account-show timeout is not followed by `az --version`: nothing it answers changes the verdict.
+ const r = await run({ argv: ['--env', ENVURL], exec: { slow: ['az account show'] } });
+ assert.ok(!r.calls.includes('az --version'), r.calls.join(' | '));
+});
+
+test('POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS sets the az budget', async () => {
+ const saved = process.env.POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS;
+ process.env.POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS = '90000';
+ try {
+ const r = await run({ argv: ['--env', ENVURL], exec: { slow: ['az account show'] } });
+ assert.ok(r.calls.includes('az account show --query user.name -o tsv (timeout 90000)'), r.calls.join(' | '));
+ assert.match(r.message, /within 90 s[\s\S]*=180000/);
+ } finally {
+ if (saved === undefined) delete process.env.POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS;
+ else process.env.POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS = saved;
+ }
+});
+
+test('a token read that runs out of time is az_timeout, without a second wait inside WhoAmI', async () => {
+ const warmed = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' }, tokenFailure: 'timeout' });
+ assert.equal(warmed.blocker, 'az_timeout');
+ assert.match(warmed.message, /token for https:\/\/contoso\.crm\.dynamics\.com timed out/);
+ assert.ok(!warmed.calls.includes('whoami'), warmed.calls.join(' | '));
+ // With the env URL from pac nothing is warmed, and WhoAmI reads the token — a timeout there too is az_timeout.
+ const viaPac = await run({ exec: { pacOrg: `Connected as [email protected]\nOrg URL: ${ENVURL}/\n` }, whoAmIThrows: 'token timed out', tokenFailure: 'timeout' });
+ assert.equal(viaPac.blocker, 'az_timeout');
+ assert.equal(viaPac.message, 'token timed out');
+ // Any other token failure is still WhoAmI's to report.
+ const other = await run({ argv: ['--env', ENVURL], whoAmIThrows: 'getaddrinfo ENOTFOUND', tokenFailure: 'failed' });
+ assert.equal(other.blocker, 'whoami_error');
+});
+
+test('a pac probe that runs out of time says so: pac_timeout under --require-pac, a warning otherwise', async () => {
+ const required = await run({ argv: ['--env', ENVURL, '--require-pac'], exec: { slow: ['pac org who'] } });
+ assert.equal(required.blocker, 'pac_timeout');
+ assert.match(required.message, /pac org who` did not answer within 60 s/);
+ assert.ok(required.calls.includes('pac org who (timeout 60000)'), required.calls.join(' | '));
+ const optional = await run({ argv: ['--env', ENVURL], exec: { slow: ['pac org who'] } });
+ assert.equal(optional.ok, true);
+ assert.match(optional.warnings[0], /did not answer within 60 s[\s\S]*unknown, not missing/);
+ // The ready message agrees with the warning: a slow pac's login is unknown, never "not logged in".
+ assert.match(optional.message, /PAC's login is unknown/);
+ assert.doesNotMatch(optional.message, /not logged in/);
+ const signedOut = await run({ argv: ['--env', ENVURL], exec: {} });
+ assert.match(signedOut.message, /PAC is not logged in/, 'a pac that answered without a login is still "not logged in"');
+});
+
test('a working az login costs ONE az call before WhoAmI: `az --version` only classifies a failure', async () => {
const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' } });
assert.equal(r.ok, true);
diff --git a/plugins/model-apps/scripts/tests/cli-failure.test.js b/plugins/model-apps/scripts/tests/cli-failure.test.js
new file mode 100644
index 000000000..c14b5a9b3
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/cli-failure.test.js
@@ -0,0 +1,137 @@
+'use strict';
+// How a CLI child failed (lib/cli-failure.js), and what the token path makes of it.
+//
+// A slow Azure CLI used to come back as `null`, like every other failure: check-auth reported the
+// installed CLI as missing, and every token read said "run az login". The kinds are proven here on
+// Node's REAL error shapes — a fake `az` that outlives its budget, run through the process runner —
+// because a stub that throws "a timeout" only proves what the stub's author believed Node does.
+const test = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+const { AZ_TIMEOUT_ENV, MIN_AZ_TIMEOUT_MS, MAX_AZ_TIMEOUT_MS, azTimeoutMs, cliFailureKind, azTimeoutAdvice } = require('../lib/cli-failure.js');
+const runner = require('../lib/process-runner.js');
+const auth = require('../lib/dataverse-auth.js');
+
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+// A fake `az` on its own PATH that prints `print` after `delayMs`, or exits 1 when `fail` is set.
+function fakeAz({ delayMs = 0, print = 'fake-token', fail = false } = {}) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-failure-'));
+ dirs.push(dir);
+ const script = path.join(dir, 'az.js');
+ fs.writeFileSync(script, `setTimeout(() => { ${fail ? "process.stderr.write('ERROR: Please run az login'); process.exit(1);" : `process.stdout.write(${JSON.stringify(print)});`} }, ${delayMs});\n`);
+ if (process.platform === 'win32') {
+ fs.writeFileSync(path.join(dir, 'az.cmd'), `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`);
+ } else {
+ fs.writeFileSync(path.join(dir, 'az'), `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`, { mode: 0o755 });
+ }
+ const env = { ...process.env, Path: dir, PATH: dir };
+ return {
+ exec: (name, args, options) => runner.runSync(name, args, options, { env }),
+ execFile: (name, args, options, cb) => runner.execFileAsync(name, args, options, cb, { env }),
+ };
+}
+
+const withBudget = async (ms, fn) => {
+ const saved = process.env[AZ_TIMEOUT_ENV];
+ process.env[AZ_TIMEOUT_ENV] = String(ms);
+ try { return await fn(); } finally {
+ if (saved === undefined) delete process.env[AZ_TIMEOUT_ENV];
+ else process.env[AZ_TIMEOUT_ENV] = saved;
+ }
+};
+
+test('azTimeoutMs: 60 s by default, or the environment override within 1 s..15 min', () => {
+ assert.strictEqual(azTimeoutMs({}), 60000);
+ assert.strictEqual(azTimeoutMs({ [AZ_TIMEOUT_ENV]: '120000' }), 120000);
+ for (const bad of ['', 'abc', '999', '900001', '1.5', '-5000']) assert.strictEqual(azTimeoutMs({ [AZ_TIMEOUT_ENV]: bad }), 60000, bad);
+});
+
+test('cliFailureKind reads each shape Node gives a failed child', () => {
+ assert.strictEqual(cliFailureKind(null), null);
+ assert.strictEqual(cliFailureKind(Object.assign(new Error('spawnSync az ETIMEDOUT'), { code: 'ETIMEDOUT' })), 'timeout');
+ assert.strictEqual(cliFailureKind(Object.assign(new Error('Command failed'), { killed: true, signal: 'SIGTERM', code: null })), 'timeout');
+ assert.strictEqual(cliFailureKind(Object.assign(new Error('spawn az ENOENT: not found on PATH'), { code: 'ENOENT' })), 'missing');
+ assert.strictEqual(cliFailureKind(new Error('spawn az ENOENT')), 'missing');
+ // Output past maxBuffer also kills the child — but that is not the CLI being slow.
+ assert.strictEqual(cliFailureKind(Object.assign(new Error('maxBuffer'), { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER', killed: true, signal: 'SIGTERM' })), 'failed');
+ assert.strictEqual(cliFailureKind(Object.assign(new Error('Command failed: az'), { code: 1 })), 'failed');
+ assert.match(azTimeoutAdvice('az account show', 60000), /`az account show` did not answer within 60 s[\s\S]*POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000/);
+});
+
+// The advice names a budget to set. Doubling the 15-minute maximum suggested 1800000, which azTimeoutMs rejects — so
+// following the advice put the budget back to 60 s. Every suggestion must be one the parser accepts and longer than the
+// budget that ran out; at the maximum, the advice must stop suggesting more time.
+test('azTimeoutAdvice suggests only a budget azTimeoutMs accepts, and none once the budget is the maximum', () => {
+ for (const ms of [1000, 60000, 120000, 449999, 450000, 600000, 899999]) {
+ const m = /POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=(\d+)/.exec(azTimeoutAdvice('az account show', ms));
+ assert.ok(m, `${ms}: a budget is suggested`);
+ const suggested = Number(m[1]);
+ assert.ok(suggested > ms && suggested <= MAX_AZ_TIMEOUT_MS, `${ms} -> ${suggested}`);
+ assert.strictEqual(azTimeoutMs({ [AZ_TIMEOUT_ENV]: m[1] }), suggested, `${ms}: the suggested ${suggested} is accepted, not replaced by the default`);
+ }
+ assert.match(azTimeoutAdvice('az account show', 450000), /=900000\./, 'capped at the maximum');
+ const atMax = azTimeoutAdvice('az account show', MAX_AZ_TIMEOUT_MS);
+ assert.doesNotMatch(atMax, /POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=\d/, 'no larger budget to suggest');
+ assert.match(atMax, /did not answer within 900 s\. That is already the longest POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS allows \(15 min\)[\s\S]*run `az account show` yourself/);
+ assert.strictEqual(azTimeoutMs({ [AZ_TIMEOUT_ENV]: String(MAX_AZ_TIMEOUT_MS) }), MAX_AZ_TIMEOUT_MS);
+ assert.strictEqual(azTimeoutMs({ [AZ_TIMEOUT_ENV]: String(MIN_AZ_TIMEOUT_MS) }), MIN_AZ_TIMEOUT_MS);
+});
+
+test('a token read that outlives its budget is recorded as a timeout, and the message says so', async () => {
+ await withBudget(1000, async () => {
+ const origin = 'https://contoso-slow-sync.crm.dynamics.com';
+ const slow = fakeAz({ delayMs: 4000 });
+ assert.strictEqual(auth.getAuthToken(origin, { exec: slow.exec, fresh: true }), null);
+ assert.strictEqual(auth.tokenFailureKind(origin), 'timeout');
+ assert.match(auth.tokenFailureMessage(origin, 'run az login'), /Could not get an Azure CLI token for https:\/\/contoso-slow-sync\.crm\.dynamics\.com: `az account get-access-token` did not answer within 1 s/);
+
+ const asyncOrigin = 'https://contoso-slow-async.crm.dynamics.com';
+ assert.strictEqual(await auth.getAuthTokenAsync(asyncOrigin, { execFile: slow.execFile, fresh: true }), null);
+ assert.strictEqual(auth.tokenFailureKind(asyncOrigin), 'timeout');
+
+ // Every caller that throws on a missing token words it from the same record.
+ await assert.rejects(
+ auth.dataverseRequest(origin, 'GET', 'WhoAmI', null, { getToken: () => null, request: async () => { throw new Error('no request expected'); } }),
+ /did not answer within 1 s/,
+ );
+ const pre = await auth.preflightAuth(origin, { getToken: () => null, request: async () => { throw new Error('no request expected'); } });
+ assert.strictEqual(pre.ok, false);
+ assert.match(pre.error, /did not answer within 1 s/);
+ assert.doesNotMatch(pre.error, /sign-in problem/);
+ });
+});
+
+test('a CLI that answers, refuses, or is absent is not called slow', async () => {
+ await withBudget(30000, async () => {
+ const origin = 'https://contoso-quick.crm.dynamics.com';
+ assert.strictEqual(auth.getAuthToken(origin, { exec: fakeAz({ fail: true }).exec, fresh: true }), null);
+ assert.strictEqual(auth.tokenFailureKind(origin), 'failed');
+ assert.strictEqual(auth.tokenFailureMessage(origin, 'run az login'), 'run az login', 'a refusal keeps the sign-in advice');
+
+ const missingEnv = { ...process.env, Path: os.tmpdir(), PATH: os.tmpdir() };
+ assert.strictEqual(auth.getAuthToken(origin, { exec: (n, a, o) => runner.runSync(n, a, o, { env: missingEnv }), fresh: true }), null);
+ assert.strictEqual(auth.tokenFailureKind(origin), 'missing');
+ assert.match(auth.tokenFailureMessage(origin, 'x'), /not on PATH/);
+
+ // An answer clears the record, so an earlier failure never colours a later message.
+ assert.strictEqual(auth.getAuthToken(origin, { exec: fakeAz({ print: 'token-1' }).exec, fresh: true }), 'token-1');
+ assert.strictEqual(auth.tokenFailureKind(origin), null);
+ assert.strictEqual(await auth.getAuthTokenAsync('https://contoso-quick-async.crm.dynamics.com', { execFile: fakeAz({ print: 'token-2' }).execFile, fresh: true }), 'token-2');
+ assert.strictEqual(auth.tokenFailureKind('https://contoso-quick-async.crm.dynamics.com'), null);
+
+ // An az that answers with no token is a failure, not a timeout; so is a launch that throws instead of calling back
+ // (Node's execFile can, synchronously) — read by the same rule as a launch failure reported through the callback.
+ const empty = 'https://contoso-empty-async.crm.dynamics.com';
+ assert.strictEqual(await auth.getAuthTokenAsync(empty, { execFile: fakeAz({ print: '' }).execFile, fresh: true }), null);
+ assert.strictEqual(auth.tokenFailureKind(empty), 'failed');
+ const thrown = 'https://contoso-thrown-async.crm.dynamics.com';
+ const throwing = () => { throw Object.assign(new Error('spawn az ENOENT'), { code: 'ENOENT' }); };
+ assert.strictEqual(await auth.getAuthTokenAsync(thrown, { execFile: throwing, fresh: true }), null);
+ assert.strictEqual(auth.tokenFailureKind(thrown), 'missing');
+ });
+});
diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.js
index b33406345..3811287a1 100644
--- a/plugins/model-apps/scripts/tests/download-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js
@@ -1190,6 +1190,89 @@ test('ROUND-TRIP: manifest → download → reverse → hydrate → validate →
// ── Task 6: sitemap-membership + download-by-id + keep pageId + env-wide names + injectable seam ─
+test('lexical navigation variants survive deploy-download-rebuild', async () => {
+ const overviewId = 'aaaaaaaa-0000-4000-8000-000000000001';
+ const detailId = 'bbbbbbbb-0000-4000-8000-000000000002';
+ const appId = 'cccccccc-0000-4000-8000-000000000003';
+ const appUniqueId = 'cccccccc-0000-4000-8000-000000000004';
+ const sitemapId = 'cccccccc-0000-4000-8000-000000000005';
+ const appUnique = 'contoso_lexical';
+ const manifest = buildManifest({ pages: [
+ { key: 'overview', name: 'Overview', navigatesTo: [{ targetKey: 'detail' }] },
+ { key: 'detail', name: 'Detail' },
+ ] }, new Map([['overview', overviewId], ['detail', detailId]]));
+ const manifestB64 = Buffer.from(JSON.stringify(manifest), 'utf8').toString('base64');
+ // Only the target arguments depend on this parameter; comments, escapes and Unicode are the oracle.
+ const overviewCode = (target) => [
+ 'export default function Overview() {',
+ ` const idText = "${detailId}"; const token = "PAGEREF_detail";`,
+ ' const text = "left\u2028middle\u2029right";',
+ ` // navigateTo({pageType:"generative",pageId:"${detailId}"})\u2028 Xrm.Navigation.navigateTo?.(/* pageType and pageId */{pageType:"generative",pageId:"${target}"});`,
+ ` // another inert pageId\u2029 Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"${target}"});`,
+ String.raw` Xrm?.Navigation?.navigateTo({"page\u0054ype":"generative","page\u{49}d":"` + target + '"});',
+ ` Xrm.Navigation.navigateTo({pageType:"generative",pageId:"${target}",// keep pageId\u2029data:{}});`,
+ String.raw` Xrm.Navigation.navigate\u0054o?.({"pageType":"generative",'page\x49d':"` + target + '"});',
+ ` Xrm.Navigation.navigateTo({pageType:"entityrecord",entityName:"contoso_item",entityId:"${detailId}"});`,
+ ' return null;',
+ '}',
+ '',
+ ].join('\r\n');
+ const deployed = overviewCode(detailId);
+ const canonical = overviewCode('PAGEREF_detail');
+ const detailCode = 'export default function Detail() { const text = "left\u2028right\u2029"; return null; }\r\n';
+ const xml = `<SiteMap><Area><Group><SubArea GenPageId="${overviewId}" Title="Navigation A"/><SubArea GenPageId="${detailId}" Title="Navigation B"/></Group></Area></SiteMap>`;
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'download-lexical-'));
+ try {
+ const sdk = {
+ fetchArtifact: async () => ({
+ name: 'Lexical App', description: '',
+ siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Pages', subAreas: [
+ { type: 'GenPage', genPageId: overviewId, title: 'Navigation A' },
+ { type: 'GenPage', genPageId: detailId, title: 'Navigation B' },
+ { type: 'Entity', entity: 'contoso_item' },
+ ] }] }] },
+ }),
+ queryRecords: async (logical, opts = {}) => {
+ if (logical === 'appmodule') return [{ appmoduleid: appId, appmoduleidunique: appUniqueId, uniquename: appUnique }];
+ if (logical === 'appmodulecomponent') return [{ objectid: sitemapId, componenttype: 62 }];
+ if (logical === 'sitemap') return [{ sitemapxml: xml }];
+ if (logical === 'webresource') return /_pagemanifest'/.test(opts.filter || '') ? [{ content: manifestB64 }] : [];
+ return [];
+ },
+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Item', primaryNameAttribute: 'contoso_name', attributes: [], relationships: [] }),
+ dataverse: { get: async () => ({ status: 200, body: { value: [] } }) },
+ };
+ const genpageCli = {
+ enumerateEnv: async () => ({ ok: true, ids: [overviewId, detailId], pages: [{ pageId: overviewId, name: 'Overview' }, { pageId: detailId, name: 'Detail' }] }),
+ download: async ({ outputDir, pageIds }) => {
+ assert.deepStrictEqual([...pageIds].sort(), [overviewId, detailId].sort());
+ for (const id of pageIds) {
+ const dir = path.join(outputDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'page.tsx'), id === overviewId ? deployed : detailCode, 'utf8');
+ fs.writeFileSync(path.join(dir, 'config.json'), '\uFEFF{"dataSources":["contoso_item"]}', 'utf8');
+ }
+ return true;
+ },
+ };
+ const downloaded = await runDownload({ sdk, genpageCli, outDir: out, appId, appUnique });
+ assert.ok(downloaded.ok, JSON.stringify(downloaded));
+ const validation = validateAppSpec(downloaded.spec);
+ assert.ok(validation.ok, validation.errors.join('; '));
+ const overview = downloaded.spec.pages.find((p) => p.key === 'overview');
+ const detail = downloaded.spec.pages.find((p) => p.key === 'detail');
+ const downloadedOverview = fs.readFileSync(path.join(out, overview.source.codeFile));
+ assert.deepStrictEqual(downloadedOverview, Buffer.from(canonical, 'utf8'), 'reverse normalization changes only effective target literals');
+ assert.deepStrictEqual(fs.readFileSync(path.join(out, detail.source.codeFile)), Buffer.from(detailCode, 'utf8'), 'a page without navigation is byte-identical');
+ assert.deepStrictEqual(overview.navigatesTo, [{ targetKey: 'detail' }]);
+ assert.deepStrictEqual(overview.dataSources, ['contoso_item']);
+ const { deployment, unresolved } = resolvePageRefs(new Map([['overview', { code: downloadedOverview.toString('utf8') }]]),
+ new Map(downloaded.spec.pages.map((p) => [p.key, p.pageId])));
+ assert.deepStrictEqual(unresolved, []);
+ assert.strictEqual(deployment.get('overview'), deployed, 're-resolution reproduces every deployed byte, including inert IDs and LS/PS');
+ } finally { fs.rmSync(out, { recursive: true, force: true }); }
+});
+
test('Task-6: Maker-added page (sitemap, not in manifest) gets a minted key, keeps pageId (C3)', () => {
const GP_O = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
const GP_MAKER = '9f2b1a3c-77de-4a10-8b6e-2c4d5e6f7a8b';
@@ -1333,6 +1416,101 @@ test('Task-6: full round-trip via runDownload → hydrateSpec → validateAppSpe
}
});
+// pac stores each ASCII `"` in a page name as `\"` — in the row name the env-wide listing shows, and in a navigation
+// title it writes (live-measured). The spec's name is what a rebuild sends to pac, which would escape it again, so a
+// download must write the name pac was given: kept as read, every round trip added a backslash.
+test('download writes page names without pac\'s \\" escaping, from the env-wide listing and from a title fallback', async () => {
+ const GP_A = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
+ const GP_B = '5c0a4889-45fd-46ea-91a8-ff876914d644';
+ const APP_ID = 'a1b2c3d4-0000-4000-8000-000000000001';
+ const SM_XML = `<SiteMap><Area><Group><SubArea GenPageId="${GP_A}" Title="Plain A"/>`
+ + `<SubArea GenPageId="${GP_B}" Title="Title \\&quot;B\\&quot; \\\\path"/></Group></Area></SiteMap>`;
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-esc-'));
+ try {
+ const sdk = {
+ fetchArtifact: async () => ({
+ name: 'Test App', description: '',
+ siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [
+ { type: 'GenPage', genPageId: GP_A, title: 'Plain A' },
+ { type: 'GenPage', genPageId: GP_B, title: 'Title \\"B\\" \\\\path' },
+ { type: 'Entity', entity: 'contoso_item' },
+ ] }] }] },
+ }),
+ queryRecords: async (logical, opts) => {
+ const filter = (opts && opts.filter) || '';
+ if (logical === 'appmodule') {
+ const m = filter.match(/uniquename eq '([^']+)'/);
+ if (m) return m[1] === 'test_roundtrip' ? [{ appmoduleid: APP_ID, appmoduleidunique: 'c0ffee00-0000-4000-8000-00000000dddd' }] : [];
+ return [{ appmoduleid: APP_ID, appmoduleidunique: 'c0ffee00-0000-4000-8000-00000000dddd', uniquename: 'test_roundtrip' }];
+ }
+ if (logical === 'appmodulecomponent') return [{ objectid: '5111e0f2-0000-4000-8000-0000000000aa', componenttype: 62 }];
+ if (logical === 'sitemap') return [{ sitemapxml: SM_XML }];
+ return [];
+ },
+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Item', primaryNameAttribute: `${String(logical).split('_')[0]}_name` }),
+ };
+ const genpageCli = {
+ // Page B is missing from the env-wide listing, so its name falls back to the (pac-written) navigation title.
+ enumerateEnv: async () => ({ ok: true, ids: [GP_A.toLowerCase()], pages: [{ pageId: GP_A, name: 'Say \\"hi\\" now' }] }),
+ download: async ({ outputDir, pageIds }) => {
+ for (const pid of (pageIds || [])) {
+ fs.mkdirSync(path.join(outputDir, pid), { recursive: true });
+ fs.writeFileSync(path.join(outputDir, pid, 'page.tsx'), 'export default function P() { return null; }');
+ // A's model is one the spec can hold; B's is not, so it is left out — and said so.
+ fs.writeFileSync(path.join(outputDir, pid, 'config.json'), '\uFEFF' + JSON.stringify({ dataSources: [], model: pid === GP_A ? 'gpt-4.1' : 'has space' }));
+ }
+ return true;
+ },
+ };
+ const warned = [];
+ const write = process.stderr.write;
+ process.stderr.write = (chunk, ...rest) => { warned.push(String(chunk)); return true; };
+ let result;
+ try {
+ result = await runDownload({ sdk, genpageCli, outDir: out, appId: APP_ID, appUnique: 'test_roundtrip' });
+ } finally {
+ process.stderr.write = write;
+ }
+ assert.ok(result.ok, JSON.stringify(result));
+ const nameOf = (id) => result.spec.pages.find((p) => p.pageId === id).name;
+ assert.strictEqual(nameOf(GP_A), 'Say "hi" now', 'the env-wide (row) name, unescaped');
+ assert.strictEqual(nameOf(GP_B), 'Title "B" \\\\path', 'the title fallback, unescaped — a backslash pac did not add is kept');
+ const modelOf = (id) => result.spec.pages.find((p) => p.pageId === id).model;
+ assert.deepStrictEqual([modelOf(GP_A), modelOf(GP_B)], ['gpt-4.1', undefined]);
+ assert.ok(warned.some((w) => /WARNING: 1 page model id\(s\) the App Spec cannot hold were left out/.test(w) && w.includes(GP_B) && w.includes('"has space"')), warned.join(''));
+ } finally {
+ fs.rmSync(out, { recursive: true, force: true });
+ }
+});
+
+// A download carries each page's model from config.json, so a rebuild sends it back — pac stored "" for an upload
+// without one. An id the App Spec cannot hold would make the downloaded spec fail its own validation, so it is left
+// out and reported; a page with no model gets none.
+test('parseDownloadedPages carries a page model the spec can hold, and reports one it cannot', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-model-'));
+ try {
+ const page = (id, config) => {
+ fs.mkdirSync(path.join(root, id), { recursive: true });
+ fs.writeFileSync(path.join(root, id, 'page.tsx'), 'export default () => null;', 'utf8');
+ fs.writeFileSync(path.join(root, id, 'config.json'), '\uFEFF' + JSON.stringify(config), 'utf8');
+ };
+ const [KEPT, SPACED, NONE, EMPTY] = ['11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222',
+ '33333333-3333-4333-8333-333333333333', '44444444-4444-4444-8444-444444444444'];
+ page(KEPT, { dataSources: [], model: ' claude-3-5-sonnet@20240620 ' });
+ page(SPACED, { dataSources: [], model: 'has space' });
+ page(NONE, { dataSources: [] });
+ page(EMPTY, { dataSources: [], model: '' });
+ const unkept = [];
+ const pages = parseDownloadedPages(root, root, null, [], unkept);
+ const pageOf = (id) => pages.find((p) => p.pageId === id);
+ assert.strictEqual(pageOf(KEPT).model, 'claude-3-5-sonnet@20240620');
+ for (const id of [SPACED, NONE, EMPTY]) assert.ok(!('model' in pageOf(id)), id);
+ assert.deepStrictEqual(unkept, [{ pageId: SPACED, model: 'has space' }], 'only a recorded id the spec cannot hold is reported');
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
// ── recoverAppSolution: recover an app's REAL unmanaged solution (fixes the download→teardown
// round-trip). An app module is a solutioncomponent of EVERY solution it belongs to — the built-in
// system solutions (Active/Default/Basic) AND the real one it was created in. The old code took
diff --git a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
new file mode 100644
index 000000000..3ce6a711e
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
@@ -0,0 +1,389 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { runDownload } = require('../download-model-app.js');
+const { migrateAppSpec, validateAppSpec } = require('../lib/app-spec.js');
+const { runSdkBuild, appUniqueName } = require('../lib/sdk-build.js');
+const { planTeardown } = require('../lib/sdk-teardown.js');
+const { teardownModelApp } = require('../teardown-model-app.js');
+const snapshot = require('../lib/apply-snapshot.js');
+const snapshotStore = require('../lib/apply-snapshot-store.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const APP_ID = '11111111-0000-4000-8000-000000000001';
+const FOREIGN_APP_ID = '11111111-0000-4000-8000-000000000002';
+const APP_LOOKUP = '22222222-0000-4000-8000-000000000001';
+const FOREIGN_LOOKUP = '22222222-0000-4000-8000-000000000002';
+const SITEMAP_ID = '33333333-0000-4000-8000-000000000001';
+const FOREIGN_SITEMAP_ID = '33333333-0000-4000-8000-000000000002';
+const OVERVIEW_ID = '44444444-0000-4000-8000-000000000001';
+const DETAIL_ID = '44444444-0000-4000-8000-000000000002';
+const FOREIGN_PAGE_ID = '44444444-0000-4000-8000-000000000003';
+const SOLUTION_ID = '55555555-0000-4000-8000-000000000001';
+const APP_UNIQUE = 'contoso_originalapp';
+const RELATIONSHIP = 'contoso_project_task';
+const MANIFEST = `${APP_UNIQUE}_pagemanifest`;
+const SHARED_ICON = `${APP_UNIQUE}_icon`;
+const SHARED_HTML = 'contoso_shared.html';
+const OWNED_ICON = 'contoso_owned.png';
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+function recordingLifecycleSdk({ systemOnly = false } = {}) {
+ const { sdk } = makeSimpleMockSdk();
+ const calls = [];
+ const state = {
+ failure: null,
+ beforeDelete: () => {},
+ tables: new Set(['contoso_project', 'contoso_task']),
+ pages: new Set([OVERVIEW_ID, DETAIL_ID, FOREIGN_PAGE_ID]),
+ resources: new Map(),
+ apps: new Map(),
+ solutions: new Map([
+ ['Default', { solutionid: '55555555-0000-4000-8000-000000000002', uniquename: 'Default', ismanaged: false }],
+ ['Active', { solutionid: '55555555-0000-4000-8000-000000000003', uniquename: 'Active', ismanaged: false }],
+ ['Basic', { solutionid: '55555555-0000-4000-8000-000000000004', uniquename: 'Basic', ismanaged: false }],
+ ...(!systemOnly ? [['ContosoOwnership', { solutionid: SOLUTION_ID, uniquename: 'ContosoOwnership', ismanaged: false }]] : []),
+ ]),
+ };
+ state.apps.set(APP_UNIQUE, {
+ id: APP_ID, name: 'Renamed Customer Console', uniquename: APP_UNIQUE, lookup: APP_LOOKUP, sitemapId: SITEMAP_ID,
+ siteMap: { areas: [{ title: 'Main', icon: `/WebResources/${SHARED_ICON}`, groups: [{ title: 'Work', subAreas: [
+ { type: 'Entity', entity: 'contoso_project', title: 'Projects', icon: SHARED_ICON },
+ { type: 'Entity', entity: 'contoso_task', title: 'Tasks', icon: OWNED_ICON },
+ { type: 'GenPage', genPageId: OVERVIEW_ID, title: 'Overview navigation' },
+ { type: 'GenPage', genPageId: DETAIL_ID, title: 'Detail navigation' },
+ { type: 'URL', url: `$webresource:${SHARED_HTML}`, title: 'Shared content' },
+ ] }] }] },
+ });
+ // A display-name-derived identity would hit this unrelated app after a rename.
+ state.apps.set('contoso_renamedcustomerconsole', {
+ id: FOREIGN_APP_ID, name: 'Renamed Customer Console', uniquename: 'contoso_renamedcustomerconsole',
+ lookup: FOREIGN_LOOKUP, sitemapId: FOREIGN_SITEMAP_ID,
+ siteMap: { areas: [{ title: 'Other', groups: [{ title: 'Pages', subAreas: [{ type: 'GenPage', genPageId: FOREIGN_PAGE_ID }] }] }] },
+ });
+ const resource = (name, type, content, n) => state.resources.set(name, {
+ name, webresourceid: `66666666-0000-4000-8000-${String(n).padStart(12, '0')}`,
+ webresourcetype: type, content: Buffer.from(content, 'utf8').toString('base64'), ismanaged: false,
+ });
+ resource(SHARED_ICON, 11, '<svg/>', 1);
+ resource(SHARED_HTML, 1, '<html>Shared</html>', 2);
+ resource(OWNED_ICON, 5, 'synthetic image', 3);
+ resource(MANIFEST, 3, JSON.stringify({ schemaVersion: 1, pages: [
+ { key: 'overview', name: 'Overview', pageId: OVERVIEW_ID },
+ { key: 'detail', name: 'Detail', pageId: DETAIL_ID },
+ ] }), 4);
+ resource('contoso_foreign.svg', 11, '<svg/>', 5);
+ const appById = (id) => [...state.apps.values()].find((a) => a.id === id);
+ sdk.initWorkspace = async () => {};
+ sdk.listArtifacts = async () => [...state.apps.values()].map((a) => ({ id: a.id, isDirty: false }));
+ sdk.findArtifact = async (kind, identity) => kind === 'app' ? state.apps.get(identity.uniqueName)?.id || null : null;
+ sdk.fetchArtifact = async (kind, id) => { assert.strictEqual(kind, 'app'); return clone(appById(id)); };
+ sdk.getArtifact = async (kind, id) => { assert.strictEqual(kind, 'app'); return clone(appById(id)); };
+ sdk.updateElement = async (kind, id, pointer, value) => {
+ assert.strictEqual(kind, 'app');
+ assert.strictEqual(pointer, '/siteMap');
+ appById(id).siteMap = clone(value);
+ return clone(appById(id));
+ };
+ sdk.findTables = async (logical) => state.tables.has(String(logical).toLowerCase())
+ ? [{ logicalName: String(logical).toLowerCase(), entitySetName: `${String(logical).toLowerCase()}s`, isCustom: true }] : [];
+ sdk.findColumns = async () => [{ logicalName: 'contoso_name' }, { logicalName: 'contoso_projectid' }];
+ sdk.fetchEntityMetadata = async (logical) => ({
+ logicalName: logical, schemaName: logical, displayName: logical, primaryNameAttribute: 'contoso_name',
+ entitySetName: `${logical}s`, attributes: [], relationships: [{ schemaName: RELATIONSHIP }],
+ });
+ sdk.getSolution = async (uniqueName) => ({ uniqueName, publisherPrefix: 'contoso' });
+ sdk.dataverse = { get: async (url) => {
+ const logical = (url.match(/LogicalName='([^']+)'/) || [])[1];
+ if (url.includes('/ManyToOneRelationships')) return { status: 200, body: { value: logical === 'contoso_task' ? [{
+ SchemaName: RELATIONSHIP, ReferencedEntity: 'contoso_project', ReferencingEntity: 'contoso_task',
+ ReferencingAttribute: 'contoso_projectid', IsCustomRelationship: true,
+ }] : [] } };
+ if (url.includes('/LookupAttributeMetadata')) return { status: 200, body: { value: [] } };
+ if (/\/(?:Attributes|ManyToManyRelationships)/.test(url)) return { status: 200, body: { value: [] } };
+ assert.ok(state.tables.has(logical), `only declared table metadata may be read: ${url}`);
+ return { status: 200, body: { LogicalName: logical, EntitySetName: `${logical}s` } };
+ } };
+ sdk.queryRecords = async (set, opts = {}) => {
+ const filter = opts.filter || '';
+ if (set === 'appmodule') {
+ const uniqueName = (filter.match(/uniquename eq '([^']+)'/) || [])[1];
+ const id = (filter.match(/appmoduleid eq (\S+)/) || [])[1];
+ return [...state.apps.values()].filter((a) => (!uniqueName || a.uniquename === uniqueName) && (!id || a.id === id))
+ .map((a) => ({ appmoduleid: a.id, appmoduleidunique: a.lookup, uniquename: a.uniquename }));
+ }
+ if (set === 'appmodulecomponent') {
+ const app = [...state.apps.values()].find((a) => filter.includes(`_appmoduleidunique_value eq ${a.lookup}`));
+ return app && /componenttype eq 62/.test(filter) ? [{ objectid: app.sitemapId, componenttype: 62 }] : [];
+ }
+ if (set === 'sitemap') {
+ const app = [...state.apps.values()].find((a) => filter === `sitemapid eq ${a.sitemapId}` || filter === `sitemapnameunique eq '${a.uniquename}'`);
+ if (!app) return [];
+ const entries = app.siteMap.areas.flatMap((a) => a.groups.flatMap((g) => g.subAreas || []));
+ return [{ sitemapid: app.sitemapId, sitemapxml: `<SiteMap><Area><Group>${entries.map((s) =>
+ s.genPageId ? `<SubArea GenPageId="${s.genPageId}"/>` : s.entity ? `<SubArea Entity="${s.entity}"/>` : '').join('')}</Group></Area></SiteMap>` }];
+ }
+ if (set === 'solutioncomponent') {
+ if (!filter.startsWith('objectid eq ')) return [];
+ assert.strictEqual(filter, `objectid eq ${APP_ID}`, 'download scopes solution membership to this app');
+ assert.strictEqual(opts.paginate, true);
+ return [...state.solutions.values()].map((s) => ({ _solutionid_value: s.solutionid }));
+ }
+ if (set === 'solution') {
+ const uniqueName = (filter.match(/uniquename eq '([^']+)'/) || [])[1];
+ return [...state.solutions.values()].filter((s) => !uniqueName || s.uniquename === uniqueName);
+ }
+ if (set === 'webresource') {
+ const name = (filter.match(/name eq '([^']+)'/) || [])[1];
+ return state.resources.has(name) ? [state.resources.get(name)] : [];
+ }
+ if (set === 'uxagentproject') return [...state.pages].filter((id) => filter.includes(`uxagentprojectid eq ${id}`)).map((uxagentprojectid) => ({ uxagentprojectid }));
+ return [];
+ };
+ sdk.createWebResource = async (o) => {
+ resource(o.name, 3, o.content || '', state.resources.size + 1);
+ return { id: state.resources.get(o.name).webresourceid, name: o.name };
+ };
+ sdk.updateWebResource = async (id, o) => {
+ const row = [...state.resources.values()].find((r) => r.webresourceid === id);
+ row.content = Buffer.from(o.content, 'utf8').toString('base64');
+ };
+ sdk.resolveArtifact = async (kind, identity) => {
+ if (kind === 'app') {
+ const app = state.apps.get(identity.uniqueName);
+ return app ? [{ id: app.id, name: app.name, appModuleIdUnique: app.lookup }] : [];
+ }
+ if (kind === 'webResource') {
+ const row = state.resources.get(identity.name);
+ return row ? [{ id: row.webresourceid, name: row.name }] : [];
+ }
+ if (kind === 'solution') {
+ const row = state.solutions.get(identity.uniqueName);
+ return row ? [{ id: row.solutionid, name: row.uniquename }] : [];
+ }
+ return [];
+ };
+ sdk.deleteAppCascade = async (id, uniqueValue) => {
+ state.beforeDelete();
+ if (state.failure === 'app') throw new Error('offline atomic app delete failed');
+ const app = appById(id);
+ assert.strictEqual(app.lookup, uniqueValue);
+ state.apps.delete(app.uniquename);
+ return { success: true, deleted: [], failures: [] };
+ };
+ sdk.deleteRecord = async (set, id) => {
+ state.beforeDelete();
+ assert.strictEqual(set, 'uxagentproject', 'project files must never be deleted separately');
+ if (state.failure === 'page') throw new Error('offline page delete failed');
+ if (id === DETAIL_ID) throw new Error('The component cannot be deleted because it is referenced by 1 other components.');
+ state.pages.delete(id);
+ };
+ sdk.deleteTable = async (logical) => { state.beforeDelete(); state.tables.delete(logical); };
+ sdk.deleteRelationship = async () => { state.beforeDelete(); };
+ sdk.deleteWebResource = async (id) => {
+ state.beforeDelete();
+ for (const [name, row] of state.resources) if (row.webresourceid === id) state.resources.delete(name);
+ };
+ sdk.deleteSolution = async (id) => {
+ state.beforeDelete();
+ for (const [name, row] of state.solutions) if (row.solutionid === id) state.solutions.delete(name);
+ };
+ for (const method of Object.keys(sdk)) {
+ if (typeof sdk[method] !== 'function') continue;
+ const original = sdk[method];
+ sdk[method] = (...args) => { calls.push({ method, args }); return original(...args); };
+ }
+ const genpageCli = {
+ enumerateEnv: async () => ({ ok: true, ids: [...state.pages], pages: [
+ { pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }, { pageId: FOREIGN_PAGE_ID, name: 'Detail' },
+ ] }),
+ download: async ({ appId, outputDir, pageIds }) => {
+ assert.strictEqual(appId, APP_ID);
+ assert.deepStrictEqual(pageIds.slice().sort(), [OVERVIEW_ID, DETAIL_ID]);
+ for (const id of pageIds) {
+ const dir = path.join(outputDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'page.tsx'), 'export default function Page(){ return null; }', 'utf8');
+ fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify({ dataSources: ['contoso_project'] }), 'utf8');
+ }
+ },
+ upload: async (o) => {
+ calls.push({ method: 'upload', args: [o] });
+ assert.strictEqual(o.appId, APP_ID);
+ assert.ok([OVERVIEW_ID, DETAIL_ID].includes(o.pageId), 'rebuild updates only downloaded page IDs');
+ return { pageId: o.pageId };
+ },
+ };
+ return { sdk, genpageCli, calls, state };
+}
+
+test('downloaded ownership survives rebuild and teardown planning', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'download-rebuild-teardown-'));
+ const previousPath = process.env.PATH;
+ process.env.PATH = path.dirname(process.execPath);
+ const prepare = async (systemOnly = false) => {
+ const outDir = fs.mkdtempSync(path.join(root, 'app-'));
+ const workspaceDir = path.join(outDir, '.maker-workspace');
+ const fixture = recordingLifecycleSdk({ systemOnly });
+ // runDownload invokes the real hydrateSpec. Serialize and migrate that output exactly as a
+ // subsequent build loads it, so ownership cannot be rescued by a separately hand-authored spec.
+ const downloaded = await runDownload({ sdk: fixture.sdk, genpageCli: fixture.genpageCli, outDir, appId: APP_ID, appUnique: APP_UNIQUE });
+ assert.strictEqual(downloaded.ok, true, JSON.stringify(downloaded));
+ assert.deepStrictEqual(downloaded.relationshipsSkipped, []);
+ const specFile = path.join(outDir, 'app-spec.json');
+ fs.writeFileSync(specFile, JSON.stringify(downloaded.spec), 'utf8');
+ const spec = migrateAppSpec(JSON.parse(fs.readFileSync(specFile, 'utf8')));
+ assert.strictEqual(validateAppSpec(spec, { profile: 'deploy' }).ok, true);
+ assert.strictEqual(spec.solution.uniqueName, systemOnly ? 'Default' : 'ContosoOwnership');
+ const rebuild = await runSdkBuild(spec, {
+ sdk: fixture.sdk, apply: true, env: ENV, appDir: outDir, workspaceDir,
+ preResolvedLanguageCode: 1033, genpageCli: fixture.genpageCli,
+ });
+ assert.strictEqual(rebuild.ok, true);
+ assert.strictEqual(rebuild.created.app, APP_ID, 'a display-name rename cannot redirect the rebuild');
+ assert.deepStrictEqual(rebuild.created.pages, { overview: OVERVIEW_ID, detail: DETAIL_ID });
+ assert.ok(!fixture.calls.some((c) => ['createTable', 'createRelationship', 'enrichDefaultViews'].includes(c.method)),
+ `reused tables and relationships are not recreated or enriched: ${JSON.stringify(fixture.calls.filter((c) => ['createTable', 'createRelationship', 'enrichDefaultViews'].includes(c.method)))}`);
+ assert.strictEqual(spec.entities.every((e) => e.existing === true), true);
+ assert.strictEqual(spec.relationships[0].existing, true);
+ assert.deepStrictEqual(spec.webResources.filter((w) => w.external).map((w) => w.name).sort(), [SHARED_HTML, SHARED_ICON].sort());
+ assert.strictEqual(appUniqueName(spec), APP_UNIQUE);
+ const baseline = snapshot.makeEnvelope({
+ orgId: '77777777-0000-4000-8000-000000000001', envUrl: ENV, appUniqueName: APP_UNIQUE, appId: APP_ID,
+ }, { generation: 'download-baseline', priorSpec: spec });
+ snapshot.markEligible(baseline);
+ snapshotStore.writeSnapshotAtomic(workspaceDir, baseline);
+ fixture.state.beforeDelete = () => {
+ const disk = snapshotStore.readSnapshot(workspaceDir);
+ assert.ok(snapshot.isTombstoned(disk), 'every remote delete must follow the real tombstone write');
+ assert.strictEqual(disk.eligible, false);
+ assert.notStrictEqual(disk.generation, baseline.generation, 'teardown fences any pending baseline CAS');
+ assert.strictEqual(snapshotStore.teardownsInFlight(disk).length, 1);
+ };
+ fixture.calls.length = 0;
+ return { ...fixture, spec, workspaceDir };
+ };
+ const assertReusedRetained = ({ calls, state }) => {
+ assert.ok(!calls.some((c) => ['deleteTable', 'deleteRelationship', 'enrichDefaultViews'].includes(c.method)), 'retained tables and their lookups are never touched');
+ assert.deepStrictEqual([...state.tables].sort(), ['contoso_project', 'contoso_task']);
+ assert.ok(state.resources.has(SHARED_ICON), 'shared icon survives, including its generated-app-icon name collision');
+ assert.ok(state.resources.has(SHARED_HTML), 'shared HTML resource survives');
+ assert.ok(state.resources.has('contoso_foreign.svg'), 'undeclared resource survives');
+ assert.ok(state.apps.has('contoso_renamedcustomerconsole'), 'namesake foreign app survives');
+ assert.ok(state.pages.has(FOREIGN_PAGE_ID), 'foreign page outside the manifest survives');
+ };
+ try {
+ const fixture = await prepare();
+ const { sdk, spec, workspaceDir, calls, state } = fixture;
+ const plan = planTeardown(spec);
+ assert.deepStrictEqual(plan.filter((s) => s.kind === 'table').map((s) => s.target), [
+ { logical: 'contoso_task', schemaName: 'contoso_task', existing: true },
+ { logical: 'contoso_project', schemaName: 'contoso_project', existing: true },
+ ], 'downloaded ownership survives child-first teardown planning');
+ assert.strictEqual(plan[0].target.uniqueName, APP_UNIQUE);
+ assert.strictEqual(plan[1].target.manifestName, MANIFEST);
+ assert.deepStrictEqual(plan.filter((s) => s.kind === 'webResource').map((s) => s.target.name), [OWNED_ICON, MANIFEST], 'only app-owned resources are planned');
+ assert.strictEqual(plan[plan.length - 1].kind, 'solution');
+ const before = fs.readFileSync(snapshotStore.snapshotPath(workspaceDir));
+ const dry = await teardownModelApp(spec, { apply: false, workspaceDir }, { sdk });
+ assert.strictEqual(dry.ok, true);
+ assert.strictEqual(dry.dryRun, true);
+ assert.deepStrictEqual(calls, [], 'dry-run makes no SDK calls');
+ const refused = await teardownModelApp(spec, { apply: true, workspaceDir }, { sdk });
+ assert.strictEqual(refused.ok, false);
+ assert.match(refused.errors.join(' '), /requires --allow-destructive/);
+ assert.deepStrictEqual(calls, [], 'absence of destructive approval prevents every remote call');
+ assert.deepStrictEqual(fs.readFileSync(snapshotStore.snapshotPath(workspaceDir)), before, 'approval refusal leaves eligibility untouched');
+
+ const lease = snapshotStore.acquireLease(workspaceDir);
+ assert.strictEqual(lease.ok, true);
+ try {
+ const blocked = await teardownModelApp(spec, { apply: true, allowDestructive: true, workspaceDir }, { sdk });
+ assert.strictEqual(blocked.ok, false);
+ assert.match(blocked.errors.join(' '), /could not fence.*nothing was deleted/);
+ assert.deepStrictEqual(calls, [], 'tombstone contention prevents every remote call');
+ assert.deepStrictEqual(fs.readFileSync(snapshotStore.snapshotPath(workspaceDir)), before);
+ } finally { snapshotStore.releaseLease(lease); }
+
+ const events = [];
+ const clean = await teardownModelApp(spec, { apply: true, allowDestructive: true, workspaceDir }, { sdk, emit: (e) => events.push(e) });
+ assert.strictEqual(clean.ok, true, JSON.stringify(clean.errors));
+ assert.deepStrictEqual(clean.deleted.app, [APP_ID]);
+ assert.deepStrictEqual(clean.deleted.genpage, [OVERVIEW_ID]);
+ assert.ok(clean.skipped.some((s) => /still referenced/.test(s)), 'platform-held shared page is reported as retained, not deleted');
+ assert.ok(clean.skipped.some((s) => /table contoso_task.*existing: true/.test(s)));
+ assert.ok(clean.skipped.some((s) => /relationship contoso_project_task.*existing: true/.test(s)));
+ const deletes = calls.filter((c) => c.method.startsWith('delete'));
+ assert.deepStrictEqual(deletes.map((c) => c.method), ['deleteAppCascade', 'deleteRecord', 'deleteRecord', 'deleteWebResource', 'deleteWebResource', 'deleteSolution']);
+ assert.deepStrictEqual(deletes[0].args, [APP_ID, APP_LOOKUP], 'atomic delete uses the resolved app and its unique lookup');
+ assert.deepStrictEqual(deletes.filter((c) => c.method === 'deleteRecord').map((c) => c.args), [['uxagentproject', OVERVIEW_ID], ['uxagentproject', DETAIL_ID]]);
+ assert.deepStrictEqual(events.filter((e) => e.status === 'start').map((e) => e.label), plan.map((s) => s.label), 'execution preserves the dependency-safe plan order');
+ assertReusedRetained(fixture);
+ assert.strictEqual(state.resources.has(OWNED_ICON), false, 'owned-icon positive control is deleted');
+ assert.strictEqual(state.solutions.has('ContosoOwnership'), false, 'real solution positive control is deleted last');
+ assert.strictEqual(snapshotStore.readSnapshot(workspaceDir), null, 'clean teardown removes the baseline');
+ assert.strictEqual(fs.existsSync(snapshotStore.leasePath(workspaceDir)), false);
+
+ for (const failure of ['app', 'page']) {
+ const failedFixture = await prepare();
+ failedFixture.state.failure = failure;
+ const failedEvents = [];
+ const failed = await teardownModelApp(failedFixture.spec, { apply: true, allowDestructive: true, workspaceDir: failedFixture.workspaceDir },
+ { sdk: failedFixture.sdk, emit: (e) => failedEvents.push(e) });
+ assert.strictEqual(failed.ok, false);
+ assert.ok(failed.errors.some((e) => e.message.includes(failure === 'app' ? 'offline atomic app delete failed' : 'offline page delete failed')), JSON.stringify(failed.errors));
+ assert.ok(failedEvents.some((e) => e.status === 'error' && e.detail.includes('offline')));
+ assertReusedRetained(failedFixture);
+ assert.ok(failedFixture.state.solutions.has('ContosoOwnership'), 'failure preserves the solution needed for a retry');
+ const disk = snapshotStore.readSnapshot(failedFixture.workspaceDir);
+ assert.ok(disk, 'a failed teardown leaves the snapshot present');
+ assert.strictEqual(disk.eligible, false);
+ assert.ok(snapshot.isTombstoned(disk), 'partial failure must retain the tombstone');
+ assert.deepStrictEqual(snapshotStore.teardownsInFlight(disk), [], 'finished failures release their in-flight registration');
+ if (failure === 'app') {
+ assert.deepStrictEqual(failedFixture.calls.filter((c) => c.method.startsWith('delete')).map((c) => c.method), ['deleteAppCascade'], 'live app deletion failure aborts dependent deletes');
+ assert.ok(failed.skipped.some((s) => /not attempted.*app was not deleted/.test(s)));
+ } else {
+ assert.ok(failedFixture.calls.some((c) => c.method === 'deleteWebResource'), 'page failure still cleans later app-owned resources');
+ assert.ok(failed.skipped.some((s) => /solution.*earlier step\(s\) failed/.test(s)));
+ assert.ok(failedFixture.state.resources.has(MANIFEST), 'page failure keeps the manifest a retry needs to find the pages');
+ assert.ok(failed.skipped.some((s) => /page manifest.*kept — the generative pages step failed/.test(s)), JSON.stringify(failed.skipped));
+ assert.ok(failedFixture.state.pages.has(OVERVIEW_ID));
+ }
+ failedFixture.state.failure = null;
+ failedFixture.state.beforeDelete = () => {
+ const current = snapshotStore.readSnapshot(failedFixture.workspaceDir);
+ assert.ok(snapshot.isTombstoned(current));
+ assert.strictEqual(current.eligible, false);
+ };
+ const retry = await teardownModelApp(failedFixture.spec, { apply: true, allowDestructive: true, workspaceDir: failedFixture.workspaceDir }, { sdk: failedFixture.sdk });
+ assert.strictEqual(retry.ok, true, JSON.stringify(retry.errors));
+ assert.strictEqual(failedFixture.state.pages.has(OVERVIEW_ID), false, `${failure} failure: the retry deletes the authored page`);
+ assert.ok(failedFixture.state.pages.has(DETAIL_ID), 'the page another app still references is left to it');
+ assert.ok(failedFixture.state.pages.has(FOREIGN_PAGE_ID), 'a page outside the manifest is never touched');
+ assert.strictEqual(failedFixture.state.resources.has(MANIFEST), false, 'the manifest goes once its pages are handled');
+ assert.strictEqual(failedFixture.state.solutions.has('ContosoOwnership'), false, 'and the solution last');
+ assert.strictEqual(snapshotStore.readSnapshot(failedFixture.workspaceDir), null, 'clean retry releases the retained tombstone');
+ }
+
+ const systemFixture = await prepare(true);
+ assert.strictEqual(systemFixture.spec.solution.uniqueName, 'Default', 'download excludes every built-in solution instead of claiming ownership');
+ for (const uniqueName of ['Default', 'Active', 'Basic']) {
+ systemFixture.calls.length = 0;
+ const systemSpec = { ...systemFixture.spec, solution: { ...systemFixture.spec.solution, uniqueName } };
+ const result = await teardownModelApp(systemSpec, { apply: true, allowDestructive: true, workspaceDir: systemFixture.workspaceDir }, { sdk: systemFixture.sdk });
+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));
+ assert.ok(result.skipped.includes(`solution ${uniqueName} (restricted system solution)`));
+ assert.ok(!systemFixture.calls.some((c) => c.method === 'deleteSolution' || (c.method === 'resolveArtifact' && c.args[0] === 'solution')), 'system solutions are protected before discovery');
+ assertReusedRetained(systemFixture);
+ }
+ } finally {
+ process.env.PATH = previousPath;
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ assert.strictEqual(fs.existsSync(root), false, 'all downloaded specs, pages and workspaces are removed');
+});
diff --git a/plugins/model-apps/scripts/tests/fixtures/stub-pac/install.js b/plugins/model-apps/scripts/tests/fixtures/stub-pac/install.js
new file mode 100644
index 000000000..605e2d1d6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/fixtures/stub-pac/install.js
@@ -0,0 +1,146 @@
+"use strict";
+
+// Builds a native `pac` the telemetry hooks will actually start.
+//
+// native-exec resolves `pac` to an absolute path and only accepts a native
+// executable (.exe/.com on Windows, an executable file elsewhere). It deliberately
+// ignores .cmd/.bat, so the az.cmd shim used by cli-failure.test.js would never
+// run here — the enrichment parser would stay dark, and a leaked PATH could still
+// reach a real pac.exe further down the path. The stub is therefore a real
+// executable that prints a fixed banner. It also touches started.txt beside itself
+// so a test can prove which binary ran.
+
+const fs = require("node:fs");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+
+const STUB_BANNER = {
+ orgId: "11111111-1111-4111-8111-111111111111",
+ tenantId: "22222222-2222-4222-8222-222222222222",
+ objectId: "33333333-3333-4333-8333-333333333333",
+ user: "[email protected]",
+ version: "9.9.9",
+ cloud: "Public",
+};
+
+// Distinct from the stub so a leaked PATH (trap is placed first) cannot be
+// mistaken for a successful stub read.
+const TRAP_BANNER = {
+ orgId: "99999999-9999-4999-8999-999999999999",
+ tenantId: "88888888-8888-4888-8888-888888888888",
+ objectId: "77777777-7777-4777-8777-777777777777",
+ user: "[email protected]",
+ version: "0.0.1",
+ cloud: "Trap",
+};
+
+function startedMarker(dir) {
+ return path.join(dir, "started.txt");
+}
+
+// Writes a native `pac` into `dir` and returns true, or returns false when this machine
+// cannot build one: on Windows the stub is compiled with the .NET Framework C# compiler,
+// which a minimal image may lack. A caller that needs the stub's banner skips then; a
+// caller that only needs PATH isolated is unaffected — an isolated PATH holding no pac is
+// still hermetic.
+function writePacExecutable(dir, banner) {
+ fs.mkdirSync(dir, { recursive: true });
+ if (process.platform === "win32") {
+ return writeWindowsExe(dir, banner);
+ }
+ writePosixScript(dir, banner);
+ return true;
+}
+
+// Drop every PATH spelling, then set one isolated value. On Windows Node forwards
+// the lexicographically first of Path/PATH, so leaving the inherited spelling in
+// place would still find an ambient pac.
+function isolatePath(env, stubDir) {
+ const isolated = { ...env };
+ for (const key of Object.keys(isolated)) {
+ if (key.toUpperCase() === "PATH") delete isolated[key];
+ }
+ isolated.PATH = stubDir;
+ return isolated;
+}
+
+function writePosixScript(dir, banner) {
+ // Shell builtins only. The hooks start this stub with PATH set to its own directory
+ // (isolatePath), so an external command such as `dirname` is not found there: the
+ // directory came back empty and the marker went to "/started.txt" (permission
+ // denied), failing every marker assertion off Windows. `$0` is the absolute path
+ // native-exec resolved, so stripping the last component gives the stub's directory.
+ const script = [
+ "#!/bin/sh",
+ 'case "$0" in */*) dir=${0%/*} ;; *) dir=. ;; esac',
+ "printf '%s\\n' started > \"$dir/started.txt\"",
+ 'case " $* " in',
+ " *' --version '*)",
+ " printf '%s\\n' 'Version: " + banner.version + "'",
+ " ;;",
+ " *)",
+ " printf '%s\\n' 'Tenant Id: " + banner.tenantId + "'",
+ " printf '%s\\n' 'Organization Id: " + banner.orgId + "'",
+ " printf '%s\\n' 'Cloud: " + banner.cloud + "'",
+ " printf '%s\\n' 'Entra ID Object Id: " + banner.objectId + "'",
+ " printf '%s\\n' 'User: " + banner.user + "'",
+ " ;;",
+ "esac",
+ "exit 0",
+ "",
+ ].join("\n");
+ const file = path.join(dir, "pac");
+ fs.writeFileSync(file, script, { mode: 0o755 });
+ try {
+ fs.chmodSync(file, 0o755);
+ } catch {
+ // Windows has no execute bit; this helper is the POSIX path.
+ }
+}
+
+function writeWindowsExe(dir, banner) {
+ const csc = [
+ "C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe",
+ "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe",
+ ].find((candidate) => fs.existsSync(candidate));
+ if (!csc) return false;
+ const source = [
+ "using System;",
+ "using System.IO;",
+ "using System.Reflection;",
+ "class PacStub {",
+ " static int Main(string[] args) {",
+ " string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);",
+ " File.WriteAllText(Path.Combine(dir, \"started.txt\"), \"started\");",
+ " string joined = string.Join(\" \", args);",
+ " if (joined.IndexOf(\"--version\", StringComparison.OrdinalIgnoreCase) >= 0) {",
+ " Console.WriteLine(\"Version: " + banner.version + "\");",
+ " return 0;",
+ " }",
+ " Console.WriteLine(\"Tenant Id: " + banner.tenantId + "\");",
+ " Console.WriteLine(\"Organization Id: " + banner.orgId + "\");",
+ " Console.WriteLine(\"Cloud: " + banner.cloud + "\");",
+ " Console.WriteLine(\"Entra ID Object Id: " + banner.objectId + "\");",
+ " Console.WriteLine(\"User: " + banner.user + "\");",
+ " return 0;",
+ " }",
+ "}",
+ "",
+ ].join("\r\n");
+ const cs = path.join(dir, "pac.cs");
+ const exe = path.join(dir, "pac.exe");
+ fs.writeFileSync(cs, source);
+ const compiled = spawnSync(csc, ["/nologo", "/t:exe", "/out:" + exe, cs], { encoding: "utf8" });
+ if (compiled.status !== 0 || !fs.existsSync(exe)) {
+ throw new Error("csc failed: " + (compiled.stderr || compiled.stdout || compiled.error));
+ }
+ return true;
+}
+
+module.exports = {
+ STUB_BANNER,
+ TRAP_BANNER,
+ startedMarker,
+ writePacExecutable,
+ isolatePath,
+};
diff --git a/plugins/model-apps/scripts/tests/form-container-order.test.js b/plugins/model-apps/scripts/tests/form-container-order.test.js
new file mode 100644
index 000000000..bf4070ad0
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-container-order.test.js
@@ -0,0 +1,106 @@
+'use strict';
+// planOrderMoves — the plan the build follows to put a form's tabs, and the sections of each
+// form-column, into the layout's order (verify then requires that order).
+//
+// Proven exhaustively rather than by example: every arrangement of up to five ordered containers
+// among up to two a layout does not mention, with each move applied exactly as the SDK's moveElement
+// applies it (remove the source, THEN splice at the index), because a plan that is right against the
+// pre-removal array is off by one against the real one.
+const test = require('node:test');
+const assert = require('node:assert');
+const { planOrderMoves, matchContainer, claimedByAuthoredName } = require('../lib/form-container-match.js');
+
+// The SDK's moveElement on one array: remove first, then insert at `to` in the shortened array.
+const applyMove = (list, { from, to }) => {
+ const [item] = list.splice(from, 1);
+ list.splice(to, 0, item);
+};
+
+const permutations = (items) => {
+ if (items.length <= 1) return [items.slice()];
+ const out = [];
+ items.forEach((item, i) => {
+ for (const rest of permutations(items.slice(0, i).concat(items.slice(i + 1)))) out.push([item].concat(rest));
+ });
+ return out;
+};
+
+const longestIncreasing = (seq) => {
+ const len = seq.map(() => 1);
+ for (let i = 0; i < seq.length; i += 1) for (let j = 0; j < i; j += 1) if (seq[j] < seq[i]) len[i] = Math.max(len[i], len[j] + 1);
+ return seq.length ? Math.max(...len) : 0;
+};
+
+test('planOrderMoves puts every arrangement in the layout\'s order, with the fewest moves', () => {
+ let arrangements = 0;
+ for (let wanted = 0; wanted <= 5; wanted += 1) {
+ for (let extras = 0; extras <= 2; extras += 1) {
+ const items = [];
+ for (let w = 0; w < wanted; w += 1) items.push(`W${w}`);
+ for (let x = 0; x < extras; x += 1) items.push(`X${x}`);
+ for (const arrangement of permutations(items)) {
+ arrangements += 1;
+ const layout = items.filter((i) => i.startsWith('W'));
+ const positions = layout.map((w) => arrangement.indexOf(w));
+ const plan = planOrderMoves(positions);
+ const list = arrangement.slice();
+ for (const move of plan.moves) {
+ assert.notStrictEqual(move.from, move.to, `a move that changes nothing is never planned: ${arrangement}`);
+ applyMove(list, move);
+ }
+ const where = `${arrangement.join(',')} -> ${list.join(',')}`;
+ assert.deepStrictEqual(list.filter((i) => i.startsWith('W')), layout, `the layout's order: ${where}`);
+ assert.deepStrictEqual(plan.positions, layout.map((w) => list.indexOf(w)), `the reported final indices: ${where}`);
+ assert.strictEqual(plan.moves.length, layout.length - longestIncreasing(positions), `only the containers out of the longest ordered run move: ${where}`);
+ // A container the layout does not mention is never moved for its own sake, so the others'
+ // relative order is untouched.
+ assert.deepStrictEqual(list.filter((i) => i.startsWith('X')), arrangement.filter((i) => i.startsWith('X')), `extras keep their order: ${where}`);
+ assert.deepStrictEqual(planOrderMoves(plan.positions).moves, [], `an ordered layout plans nothing: ${where}`);
+ }
+ }
+ }
+ assert.ok(arrangements > 5000, `the exhaustive sweep ran (${arrangements} arrangements)`);
+});
+
+test('planOrderMoves: examples, in the SDK\'s post-removal index space', () => {
+ assert.deepStrictEqual(planOrderMoves([]), { moves: [], positions: [] });
+ assert.deepStrictEqual(planOrderMoves([3]), { moves: [], positions: [3] });
+ assert.deepStrictEqual(planOrderMoves([0, 2, 5]), { moves: [], positions: [0, 2, 5] }, 'gaps are a maker\'s own containers, not disorder');
+ // [c, a, b] laid out as a, b, c: c moves once, after b.
+ assert.deepStrictEqual(planOrderMoves([1, 2, 0]), { moves: [{ from: 0, to: 2 }], positions: [0, 1, 2] });
+ // [b, c, a] laid out as a, b, c: a moves once, before b — the first container goes before the run.
+ assert.deepStrictEqual(planOrderMoves([2, 0, 1]), { moves: [{ from: 2, to: 0 }], positions: [0, 1, 2] });
+ // A swap across a maker's container: [b, x, a] laid out as a, b. The run keeps the first container,
+ // so b moves after a and the maker's x keeps its place before them.
+ assert.deepStrictEqual(planOrderMoves([2, 0]), { moves: [{ from: 0, to: 2 }], positions: [1, 2] });
+});
+
+test('claimedByAuthoredName reserves only non-empty authored names, case-insensitively', () => {
+ const reserved = claimedByAuthoredName(new Set(['tab_reserved', 'sec_reserved']));
+ for (const name of ['tab_reserved', 'TAB_RESERVED', 'TaB_ReSeRvEd', 'SEC_RESERVED']) {
+ assert.strictEqual(reserved({ name }), true, name);
+ }
+ for (const item of [null, undefined, {}, { name: '' }, { name: null }, { name: 'maker_tab', label: 'tab_reserved' }]) {
+ assert.strictEqual(reserved(item), false, `not reserved by its name: ${JSON.stringify(item)}`);
+ }
+ assert.strictEqual(claimedByAuthoredName(new Set(['']))({ name: '' }), false, 'an absent name is never an identity claim');
+});
+
+test('matchContainer skips reserved siblings for label and position but permits their name match', () => {
+ for (const [name, label] of [['tab_reserved', 'Shared'], ['TAB_RESERVED', 'sHaReD']]) {
+ const sibling = { id: 'reserved', name, label };
+ const maker = { id: 'maker', name: 'maker_tab', label: 'Maker' };
+ const list = [sibling, maker];
+ const skip = claimedByAuthoredName(new Set(['tab_reserved']));
+ assert.deepStrictEqual(matchContainer(list, { name: 'tab_new', label: 'SHARED' }, 1, { skip }),
+ { index: 1, item: maker }, 'a reserved label cannot outrank the unreserved positional fallback');
+ assert.strictEqual(matchContainer([sibling], { name: 'tab_new', label: 'SHARED' }, 1, { skip }), null,
+ 'a reserved label without another candidate requires a new container');
+ assert.strictEqual(matchContainer(list, { name: 'tab_new', label: 'New' }, 0, { skip }), null,
+ 'the positional fallback cannot take a named sibling either');
+ assert.deepStrictEqual(matchContainer(list, { name: 'TaB_ReSeRvEd', label: 'Renamed' }, 1, { skip }),
+ { index: 0, item: sibling }, 'its own name match is allowed despite reservation from the other passes');
+ assert.strictEqual(matchContainer([sibling], { name: 'tab_reserved', label: 'SHARED' }, 0,
+ { skip, claimed: new Set([0]) }), null, 'a container already consumed by an earlier want cannot be matched twice');
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js
new file mode 100644
index 000000000..1d074472c
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js
@@ -0,0 +1,235 @@
+'use strict';
+// Reconciliation must survive the real adapter's move indices, serialization and subsequent fetch,
+// not merely agree with an in-memory SDK mock or a freshly compiled form.
+const test = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
+const ai = require('../lib/artifact-intent.js');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { verifySpec } = require('../lib/verify-spec.js');
+const { readerFor } = require('../verify-model-app.js');
+
+const guid = (n) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
+const FORM_ID = guid(1);
+const NOTES_CLASS_ID = '06375649-C143-495E-A496-C962E5B4488E';
+const SUBGRID_CLASS_ID = 'E7A81278-8635-4D9E-8D4D-59480B391C5B';
+const META = { new_name: 'String', new_code: 'String', new_notes: 'Memo', new_area: 'String' };
+const clone = (v) => JSON.parse(JSON.stringify(v));
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const specFor = () => ({
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'Reconcile', displayName: 'Reconcile', publisherPrefix: 'new' },
+ app: { name: 'Reconcile', uniqueName: 'new_reconcile' },
+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', existing: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [
+ { schemaName: 'new_code', displayName: 'Code', type: 'Text' },
+ { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' },
+ { schemaName: 'new_area', displayName: 'Area', type: 'Text' },
+ ] }],
+ forms: [{ entity: 'new_ticket', name: 'Main', notes: true, prune: false, tabs: [
+ { name: 'tab_a', label: 'A', columns: [
+ { width: '70%', sections: [
+ { name: 'sec_dest', label: 'Destination', visible: false, showLabel: false, columns: 1, fields: ['new_name'] },
+ { name: 'sec_src', label: 'Source', columns: 2, fields: ['new_code'] },
+ { name: 'sec_extra', label: 'Extra', columns: 1, fields: ['new_notes'] },
+ ] },
+ { width: '30%', sections: [{ name: 'sec_right', label: 'Right', fields: [] }] },
+ ] },
+ { name: 'tab_b', label: 'B', expanded: false, sections: [
+ { name: 'sec_b', label: 'B', fields: ['new_area'] },
+ ] },
+ ] }],
+});
+
+function existingTabs(spec) {
+ const tabs = ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID }).tabs;
+ const sections = tabs[0].columns[0].sections;
+ const byName = (name) => sections.find((s) => s.name === name);
+ const source = byName('sec_src');
+ const destination = byName('sec_dest');
+ const cell = destination.rows[0].cells[0];
+ cell.colspan = 2;
+ // Maker-set state has no authored flag to reassert on every apply, so it must travel with the
+ // moved cell without obscuring the width/order no-op check with deliberate flag reassertions.
+ cell.visible = false;
+ cell.control.isReadOnly = true;
+ source.rows.unshift({ cells: [cell] });
+ destination.rows = [];
+ const grid = ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_task',
+ relationshipName: 'new_ticket_tasks', viewId: guid(2), label: 'Tasks' });
+ tabs[0].columns[0].sections = [source, grid, byName('sec_extra'), destination];
+ // The timeline is deliberately outside the compiler's first tab. It belongs to the engine, not
+ // to the authored container order, and must not be dragged back or recreated during reconciliation.
+ tabs[1].columns[0].sections.push(byName('section_notes'));
+ let next = 10;
+ for (const tab of tabs) {
+ tab.id = guid(next++);
+ for (const col of tab.columns) for (const section of col.sections) {
+ section.id = guid(next++);
+ for (const row of section.rows) for (const c of row.cells) {
+ c.id = guid(next++);
+ if (c.control) c.control.id = guid(next++);
+ }
+ }
+ }
+ return tabs.reverse();
+}
+
+async function harness() {
+ const store = { row: { formid: FORM_ID, name: 'Main', objecttypecode: 'new_ticket', type: 2, isdefault: true } };
+ const writes = [];
+ const reads = [];
+ let revision = 1;
+ const response = (body, status = 200) => ({ status, headers: { etag: `W/"${revision}"` }, body });
+ const httpClient = {
+ get: async (url) => {
+ reads.push(url);
+ const decoded = decodeURIComponent(url);
+ if (/EntityDefinitions\(LogicalName='new_ticket'\)/.test(decoded)) {
+ return response({ LogicalName: 'new_ticket', EntitySetName: 'new_tickets',
+ Attributes: Object.entries(META).map(([LogicalName, AttributeType]) => ({ LogicalName, AttributeType })) });
+ }
+ if (/EntityDefinitions\(LogicalName='systemform'\)/.test(decoded)) return response({ EntitySetName: 'systemforms' });
+ if (/systemforms\(/i.test(url)) {
+ assert.ok(store.row.formxml, 'a fetch reads the previously serialized form');
+ return response(clone(store.row));
+ }
+ if (/\/systemforms(?:\?|$)/i.test(url)) return response({ value: [clone(store.row)] });
+ assert.fail(`unexpected GET: ${url}`);
+ },
+ post: async (url, body) => {
+ writes.push({ method: 'post', url, body: clone(body) });
+ if (/\/systemforms(?:\?|$)/i.test(url)) {
+ assert.ok(!store.row.formxml, 'only the fixture may create a form; reconciliation must reuse it');
+ store.row = { ...store.row, ...body, formid: FORM_ID };
+ return { ...response({}, 204), headers: { 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.2/systemforms(${FORM_ID})` } };
+ }
+ if (/\/(?:PublishXml|AddSolutionComponent)(?:\?|$)/.test(url)) return response({}, 204);
+ assert.fail(`unexpected POST: ${url}`);
+ },
+ patch: async (url, body) => {
+ assert.match(url, /\/systemforms\(/i);
+ writes.push({ method: 'patch', url, body: clone(body) });
+ store.row = { ...store.row, ...body };
+ revision += 1;
+ return response({}, 204);
+ },
+ put: async (url) => assert.fail(`unexpected PUT: ${url}`),
+ delete: async (url) => assert.fail(`unexpected DELETE: ${url}`),
+ };
+ const freshSdk = async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'form-reconcile-rt-'));
+ dirs.push(dir);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir),
+ instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ const mutations = [];
+ // These wrappers record calls but delegate every operation to the real bundle. A fresh workspace
+ // for each apply prevents an idempotency assertion from relying on the first apply's local cache.
+ for (const method of ['createArtifact', 'addElement', 'updateElement', 'moveElement', 'removeElement', 'updateRecord', 'setFormSecurityRoles']) {
+ const original = sdk[method].bind(sdk);
+ sdk[method] = async (...args) => { mutations.push({ method, args: clone(args) }); return original(...args); };
+ }
+ return { sdk, mutations };
+ };
+ return { store, writes, reads, freshSdk };
+}
+
+const sectionsOf = (form) => form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections));
+const sectionOf = (form, name) => sectionsOf(form).find((s) => s.name === name);
+const cellsOf = (section) => section.rows.flatMap((r) => r.cells);
+const identities = (form) => ({
+ tabs: form.tabs.map((t) => [t.name, t.id]).sort(),
+ sections: sectionsOf(form).map((s) => [s.name, s.id]).sort(),
+ cells: sectionsOf(form).flatMap((s) => cellsOf(s).map((c) => [c.id, c.control && c.control.id])).sort(),
+});
+
+test('reconcile narrowed field and reordered containers survives serialize-fetch-verify', async () => {
+ const spec = specFor();
+ const { store, writes, reads, freshSdk } = await harness();
+ const seed = await freshSdk();
+ const art = await seed.sdk.createArtifact('form', { name: 'Main', entityLogicalName: 'new_ticket', formType: 'Main' });
+ for (const tab of existingTabs(spec)) await seed.sdk.addElement('form', art.id, '/tabs', tab);
+ await seed.sdk.removeElement('form', art.id, '/tabs/0');
+ await seed.sdk.pushArtifact('form', art.id);
+ const beforeXml = store.row.formxml;
+ const first = await freshSdk();
+ const before = clone(await first.sdk.fetchArtifact('form', FORM_ID));
+ assert.deepStrictEqual(before.tabs.map((t) => t.name), ['tab_b', 'tab_a'], 'the deployed tabs really start out of order');
+ const originalCell = cellsOf(sectionOf(before, 'sec_src')).find((c) => c.control.fieldName === 'new_name');
+ assert.strictEqual(originalCell.colspan, 2, 'the deployed cell is wider than its destination');
+ const beforeIds = identities(before);
+ for (const entry of [...beforeIds.tabs, ...beforeIds.sections]) assert.ok(entry[1], `a container has a real identity: ${entry}`);
+ for (const entry of beforeIds.cells) assert.ok(entry[0] && entry[1], `a cell and its control have real identities: ${entry}`);
+ const start = writes.length;
+ const warnings = [];
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(built.ok, true);
+ assert.strictEqual(built.created.forms.new_ticket, FORM_ID, 'the existing form is reused');
+ assert.ok(writes.slice(start).some((w) => w.method === 'patch' && typeof w.body.formxml === 'string'),
+ 'the real reconciliation must push FormXML, not just mutate a local tree');
+ for (const kind of ['tabs', 'sections', 'cells']) {
+ assert.ok(first.mutations.some((m) => m.method === 'moveElement' && new RegExp(`/${kind}/\\d+$`).test(m.args[2])),
+ `the real reconciliation moves existing ${kind}`);
+ }
+ const xml = store.row.formxml;
+ assert.notStrictEqual(xml, beforeXml);
+
+ const fetched = await freshSdk();
+ const after = await fetched.sdk.fetchArtifact('form', FORM_ID);
+ assert.deepStrictEqual(after.tabs.map((t) => t.name), ['tab_a', 'tab_b']);
+ assert.deepStrictEqual(after.tabs[0].columns[0].sections.filter((s) => !s.name.startsWith('section_')).map((s) => s.name),
+ ['sec_dest', 'sec_src', 'sec_extra'], 'the authored sections have their authored relative order');
+ assert.deepStrictEqual(identities(after), identities(before), 'tabs, sections, cells and controls are moved, not recreated');
+ const moved = cellsOf(sectionOf(after, 'sec_dest')).find((c) => c.control.fieldName === 'new_name');
+ assert.ok(moved, 'the field is fetched in its destination section');
+ assert.strictEqual(moved.id, originalCell.id);
+ assert.strictEqual(moved.colspan, 1, 'an undeclared span is narrowed to the destination grid');
+ assert.strictEqual(moved.visible, originalCell.visible, 'the move preserves maker-set visibility');
+ assert.deepStrictEqual(moved.control, originalCell.control, 'the same control retains its maker-set state');
+ for (const section of sectionsOf(after)) for (const row of section.rows) {
+ assert.ok(row.cells.reduce((sum, c) => sum + (Number(c.colspan) || 1), 0) <= section.columns,
+ `no row overflows section ${section.name}: ${JSON.stringify(row)}`);
+ }
+ for (const name of ['section_grid_new_ticket_tasks', 'section_notes']) {
+ assert.deepStrictEqual(sectionOf(after, name), sectionOf(before, name), `${name} is untouched, including its control and identities`);
+ const hostTab = (form) => form.tabs.find((t) => t.columns.some((c) => c.sections.some((s) => s.name === name))).id;
+ assert.strictEqual(hostTab(after), hostTab(before), `${name} stays in its deployed tab`);
+ }
+ assert.strictEqual(warnings.filter((w) => /new_name.*spanned 2 columns/.test(w)).length, 1, 'the narrowing is reported once');
+
+ const liveReader = readerFor(fetched.sdk, spec.app.uniqueName);
+ const read = { findTable: async () => ({ logicalName: 'new_ticket' }),
+ findColumns: async () => Object.keys(META).map((logicalName) => ({ logicalName })),
+ sitemapXml: async () => '', queryRecords: liveReader.queryRecords, formTopology: liveReader.formTopology };
+ const verified = await verifySpec(spec, read);
+ assert.ok(verified.checks.some((c) => c.kind === 'form-topology'), 'verification actually checks the layout');
+ assert.strictEqual(verified.ok, true, JSON.stringify(verified.missing));
+ assert.ok(reads.some((url) => /systemforms.*formxml/i.test(decodeURIComponent(url))), 'the real reader queries the recorded server XML');
+
+ const controlAt = xml.search(/<control\b[^>]*\bdatafieldname="new_name"/);
+ assert.ok(controlAt > 0);
+ const cellAt = xml.lastIndexOf('<cell', controlAt);
+ const cellEnd = xml.indexOf('>', cellAt) + 1;
+ const wide = xml.slice(cellAt, cellEnd).replace(/colspan="1"/, 'colspan="2"');
+ store.row.formxml = xml.slice(0, cellAt) + wide + xml.slice(cellEnd);
+ assert.notStrictEqual(store.row.formxml, xml, 'the negative control changes only the moved cell width');
+ const rejected = await verifySpec(spec, read);
+ assert.strictEqual(rejected.ok, false, 'an overflowing serialized form must not verify');
+ assert.match(rejected.checks.find((c) => c.kind === 'form-topology').detail,
+ /section 'sec_dest' row 1 carries 2 columns of content in a 1-column section/);
+ store.row.formxml = xml;
+
+ const second = await freshSdk();
+ const again = await runSdkBuild(spec, { sdk: second.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(again.ok, true);
+ assert.deepStrictEqual(second.mutations, [], 'a second apply of the fetched serialized form makes no form mutation');
+ assert.strictEqual(store.row.formxml, xml, 'the serialized form is stable across the second apply');
+ assert.strictEqual(warnings.filter((w) => /new_name.*spanned 2 columns/.test(w)).length, 1, 'the second apply reports no further narrowing');
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-cli.test.js b/plugins/model-apps/scripts/tests/genpage-cli.test.js
index abb9e7f13..b30532ac8 100644
--- a/plugins/model-apps/scripts/tests/genpage-cli.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-cli.test.js
@@ -77,6 +77,19 @@ test('buildPacInvocation starts pac.exe directly with every argument unchanged,
assert.strictEqual(inv.options.shell, false);
});
+// An update sends a page's CURRENT name on the user's behalf. Whether pac can be handed it is decided without
+// starting anything, so an update can leave out a name a pac.cmd shim would refuse instead of failing on it.
+test('argumentRefusal says why a pac.cmd shim cannot receive a value, and is null when pac can', () => {
+ const shim = makeGenpageCli('https://contoso.crm.dynamics.com', { pacInvocation: PAC_CMD });
+ for (const value of ['Revenue 100%', 'Say "hi"']) assert.match(shim.argumentRefusal(value), /cannot pass .* to pac\.cmd/, value);
+ assert.strictEqual(shim.argumentRefusal('Plain name — “curly” it\'s 東京'), null);
+ const exe = makeGenpageCli('https://contoso.crm.dynamics.com', { pacInvocation: PAC_EXE });
+ for (const value of ['Revenue 100%', 'Say "hi"']) assert.strictEqual(exe.argumentRefusal(value), null, value);
+ // pac not installed at all is the upload's own error to report, not a refusal of the value.
+ const none = makeGenpageCli('https://contoso.crm.dynamics.com', { pacInvocation: { ...PAC_EXE, exists: () => false } });
+ assert.strictEqual(none.argumentRefusal('Revenue 100%'), null);
+});
+
test('buildPacInvocation runs a pac.cmd shim through cmd.exe and refuses what cmd.exe would reinterpret', () => {
const inv = buildPacInvocation(['model', 'genpage', 'list', '--name', 'Order Detail'], PAC_CMD);
assert.strictEqual(inv.file, 'C:\\Windows\\System32\\cmd.exe');
diff --git a/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js b/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
new file mode 100644
index 000000000..89e227fde
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
@@ -0,0 +1,210 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const vm = require('node:vm');
+const path = require('node:path');
+const { performance } = require('node:perf_hooks');
+const { blankNonCodePreservingTemplateExpressions, hasDefaultExport } = require(path.join(__dirname, '..', 'lib', 'source-literals.js'));
+const { pageStructureProblems } = require(path.join(__dirname, '..', 'lib', 'page-structure.js'));
+const { extractNavTargets, navReferencedKeys } = require(path.join(__dirname, '..', 'lib', 'pageref-resolver.js'));
+
+function runNavigationSnippet(code) {
+ const calls = [];
+ const record = (name) => (arg) => calls.push({ name, pageType: arg && arg.pageType, pageId: arg && arg.pageId, pageIdType: typeof (arg && arg.pageId) });
+ const sandbox = {
+ calls,
+ navigateTo: record('navigateTo'),
+ notnavigateTo: record('notnavigateTo'),
+ $navigateTo: record('$navigateTo'),
+ αnavigateTo: record('αnavigateTo'),
+ Xrm: { Navigation: { navigateTo: record('Xrm.Navigation.navigateTo') } },
+ base: {},
+ name: 'pageId',
+ pageId: 'runtime',
+ pageType: 'entityrecord',
+ };
+ vm.runInNewContext(code, sandbox, { timeout: 1000 });
+ return calls;
+}
+
+function canonicalCalls(calls) {
+ return calls.filter((call) => /(?:^|\.)navigateTo$/.test(call.name) && call.pageType === 'generative' && call.pageIdType === 'string' && /^PAGEREF_[A-Za-z0-9_-]+$/.test(call.pageId));
+}
+
+test('execution oracle: resolver agrees with JavaScript calls and object-literal runtime values', () => {
+ const cases = [
+ ['bare', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})', true],
+ ['member', 'Xrm.Navigation.navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})', true],
+ ['member optional', 'Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"PAGEREF_detail"})', true],
+ ['chain optional', 'Xrm?.Navigation?.navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})', true],
+ ['escaped navigateTo', 'navigate\\u0054o({pageType:"generative",pageId:"PAGEREF_detail"})', true],
+ ['not same identifier', 'notnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})', false],
+ ['dollar prefix', '$navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})', false],
+ ['unicode prefix', 'αnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})', false],
+ ['method override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",pageId(){return "runtime";}})', false],
+ ['getter override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",get pageId(){return "runtime";}})', false],
+ ['setter override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",set pageId(v){}})', false],
+ ['shorthand override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",pageId})', false],
+ ['computed override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",[name]:"runtime"})', false],
+ ['spread override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",...{pageId:"runtime"}})', false],
+ ['later literal wins', 'navigateTo({pageType:"generative",pageId(){return "runtime";},pageId:"PAGEREF_detail"})', true],
+ ['pageType method override', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",pageType(){return "entityrecord";}})', false],
+ ['pageType later literal wins', 'navigateTo({pageType(){return "entityrecord";},pageType:"generative",pageId:"PAGEREF_detail"})', true],
+ ['comment decoy', '// navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})\nnavigateTo({pageType:"generative",pageId:"PAGEREF_real"})', true],
+ ['comment naming the key', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",/* keep pageId */data:"x"})', true],
+ ['line comment naming the key', 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail", // pageId stays\n data:"x"})', true],
+ ['comment naming pageType', 'navigateTo({pageId:"PAGEREF_detail",pageType:"generative",/* pageType */ data:1})', true],
+ ['string decoy', 'const s = "navigateTo({pageType:\\"generative\\",pageId:\\"PAGEREF_detail\\"})"; navigateTo({pageType:"generative",pageId:"PAGEREF_real"})', true],
+ ];
+ for (const [label, code, expectCanonical] of cases) {
+ const executed = canonicalCalls(runNavigationSnippet(code));
+ const targets = extractNavTargets(code).filter((target) => target.kind === 'pageref');
+ assert.strictEqual(targets.length > 0, expectCanonical, label);
+ assert.strictEqual(executed.length > 0, expectCanonical, label);
+ if (expectCanonical) assert.deepStrictEqual(targets.map((target) => `PAGEREF_${target.key}`), executed.map((call) => call.pageId), label);
+ }
+});
+
+// A quoted key is the string JavaScript reads, escapes included: `"page\u{49}d"` IS `pageId` at runtime, and `"page\tId"`
+// is not. Each case runs in JavaScript too, so the resolver is judged against the real object.
+test('execution oracle: quoted keys are read with JavaScript escape semantics', () => {
+ const cases = [
+ ['unicode escapes', 'navigateTo({"page\\u0054ype":"generative","page\\u{49}d":"PAGEREF_detail"})', true],
+ ['hex escape', 'navigateTo({"pageType":"generative",\'page\\x49d\':"PAGEREF_detail"})', true],
+ ['identity escape', 'navigateTo({"pageType":"generative","pageI\\d":"PAGEREF_detail"})', true],
+ ['astral code point', 'navigateTo({"pageType":"generative","pageId":"PAGEREF_detail","\\u{1F600}":1})', true],
+ ['tab in the key', 'navigateTo({"pageType":"generative","page\\tId":"PAGEREF_detail"})', false],
+ ['NUL in the key', 'navigateTo({"pageType":"generative","pageId\\0":"PAGEREF_detail"})', false],
+ ['escaped quote', 'navigateTo({"pageType":"generative","pageId\\"":"PAGEREF_detail"})', false],
+ ['escaped backslash', 'navigateTo({"pageType":"generative","pageId\\\\":"PAGEREF_detail"})', false],
+ ];
+ for (const [label, code, expectCanonical] of cases) {
+ const executed = canonicalCalls(runNavigationSnippet(code));
+ const targets = extractNavTargets(code).filter((target) => target.kind === 'pageref');
+ assert.strictEqual(executed.length > 0, expectCanonical, `${label}: JavaScript`);
+ assert.strictEqual(targets.length > 0, expectCanonical, `${label}: resolver`);
+ }
+ // A malformed escape, which JavaScript refuses to compile, never names a key — and neither does an unclosed
+ // computed key, which leaves the literal before it unresolvable.
+ for (const code of [
+ 'navigateTo({"pageType":"generative","page\\u{110000}Id":"PAGEREF_detail"})',
+ 'navigateTo({"pageType":"generative","page\\u{zz}Id":"PAGEREF_detail"})',
+ 'navigateTo({"pageType":"generative","page\\u00GId":"PAGEREF_detail"})',
+ 'navigateTo({"pageType":"generative","page\\u{49":"PAGEREF_detail"})',
+ 'navigateTo({"pageType":"generative","page\\x4":"PAGEREF_detail"})',
+ 'navigateTo({"pageType":"generative","pageId\\',
+ 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail",[name})',
+ ]) {
+ assert.throws(() => runNavigationSnippet(code), { name: 'SyntaxError' }, code);
+ assert.deepStrictEqual(extractNavTargets(code).filter((target) => target.kind === 'pageref'), [], code);
+ }
+});
+
+test('lexer and resolver handle ECMAScript line terminators in comments and structure gate', () => {
+ for (const term of ['\r', '\n', '\r\n', '\u2028', '\u2029']) {
+ const code = `// inert${term}navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})`;
+ assert.deepStrictEqual(navReferencedKeys(code), ['detail'], `navigation after ${JSON.stringify(term)}`);
+ assert.deepStrictEqual(pageStructureProblems(`// header${term}export default function Page() { return null; }\n`), [], `structure after ${JSON.stringify(term)}`);
+ }
+});
+
+function nestedTemplate(depth) {
+ return 'export default ()=>null;\nconst x=' + '`${'.repeat(depth) + '1' + '}`'.repeat(depth) + ';';
+}
+
+function measure(fn) {
+ const start = performance.now();
+ fn();
+ return performance.now() - start;
+}
+
+test('performance: nested templates are linear and stack-safe', () => {
+ const code = nestedTemplate(1000);
+ assert.ok(measure(() => blankNonCodePreservingTemplateExpressions(code)) < 500, 'mask depth 1000');
+ assert.ok(measure(() => extractNavTargets(code)) < 500, 'nav extraction depth 1000');
+ assert.ok(measure(() => pageStructureProblems(code)) < 500, 'structure gate depth 1000');
+ assert.doesNotThrow(() => blankNonCodePreservingTemplateExpressions(nestedTemplate(10000)));
+});
+
+test('performance: malformed and dense navigation scans remain linear', () => {
+ const malformed = 'export default ()=>null;\n' + 'navigateTo({'.repeat(Math.ceil((64 * 1024) / 'navigateTo({'.length));
+ assert.ok(measure(() => extractNavTargets(malformed)) < 300, '64 KiB unclosed navigateTo calls');
+ const denseCall = 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail"});';
+ const dense = denseCall.repeat(Math.ceil((512 * 1024) / denseCall.length));
+ const ms = measure(() => extractNavTargets(dense));
+ assert.ok(ms < 1500, `512 KiB dense valid calls took ${ms.toFixed(1)} ms`);
+});
+
+// A comment inside a navigation call is blank in the mask, and the property scan once looked back across the whole
+// blank run from every character of it: 2,000 / 4,000 / 8,000 / 16,000 characters took about 0.4 / 1.3 / 4.4 / 19 s.
+test('performance: a long comment inside a navigation call stays linear', () => {
+ const call = (n) => `navigateTo({pageType:"generative",/* ${'c'.repeat(n)} */pageId:"PAGEREF_detail"});`;
+ const best = (code) => Math.min(measure(() => extractNavTargets(code)), measure(() => extractNavTargets(code)), measure(() => extractNavTargets(code)));
+ extractNavTargets(call(1000)); // warm up
+ const [tSmall, tLarge] = [best(call(16000)), best(call(64000))];
+ assert.deepStrictEqual(extractNavTargets(call(64000)).map((t) => [t.kind, t.key]), [['pageref', 'detail']]);
+ assert.ok(tLarge < 500, `a 64,000-character comment took ${tLarge.toFixed(1)} ms`);
+ assert.ok(tLarge / Math.max(tSmall, 1) < 9, `4x the comment took ${(tLarge / Math.max(tSmall, 1)).toFixed(1)}x the time (${tSmall.toFixed(1)} -> ${tLarge.toFixed(1)} ms)`);
+});
+test('lexer keeps LS and PS legal inside string literals while comments still terminate on them', () => {
+ assert.equal(hasDefaultExport('const s = "a\u2028b";\nexport default function Page() { return null; }\n'), true);
+ assert.equal(hasDefaultExport('const s = "a\u2029b";\nexport default function Page() { return null; }\n'), true);
+ assert.deepStrictEqual(navReferencedKeys('const s = "a\u2028navigateTo({pageType:\"generative\",pageId:\"PAGEREF_detail\"})";'), []);
+ assert.deepStrictEqual(navReferencedKeys('const s = "a\u2029navigateTo({pageType:\"generative\",pageId:\"PAGEREF_detail\"})";'), []);
+});
+
+function nestedFamily(kind, depth) {
+ if (kind === 'digit') return 'export default ()=>null;\nconst x=' + '`${'.repeat(depth) + '1' + '}`'.repeat(depth) + ';';
+ if (kind === 'ident') return 'export default ()=>null;\nconst x=' + '`${'.repeat(depth) + 'y' + '}`'.repeat(depth) + ';';
+ if (kind === 'text') return 'export default ()=>null;\nconst x=' + '`a${'.repeat(depth) + 'y' + '}b`'.repeat(depth) + ';';
+ if (kind === 'call') return 'export default ()=>null;\nconst x=' + '`${f('.repeat(depth) + 'y' + ')}`'.repeat(depth) + ';';
+ if (kind === 'jsx') return 'export default ()=>null;\nconst x=' + '`${'.repeat(depth) + '<span>{y}</span>' + '}`'.repeat(depth) + ';';
+ if (kind === 'arrow-object') return 'export default ()=>null;\nconst x=' + '`${'.repeat(depth) + '(() => ({ y }))()' + '}`'.repeat(depth) + ';';
+ if (kind === 'object-braces') return 'export default ()=>null;\nconst x=' + '`${'.repeat(depth) + '({ a: { b: y } }).a.b' + '}`'.repeat(depth) + ';';
+ throw new Error(kind);
+}
+
+test('performance: nested template families scale through the general scanner', () => {
+ for (const kind of ['digit', 'ident', 'text', 'call', 'jsx', 'arrow-object', 'object-braces']) {
+ const code = nestedFamily(kind, 1000);
+ assert.ok(measure(() => blankNonCodePreservingTemplateExpressions(code)) < 250, `${kind}: template-preserving mask`);
+ assert.ok(measure(() => extractNavTargets(code)) < 250, `${kind}: nav extraction`);
+ assert.ok(measure(() => pageStructureProblems(code)) < 250, `${kind}: structure gate`);
+ }
+});
+
+// Ordinary pages hold MANY shallow templates rather than one deep one, and a fix for depth must not tax
+// them: an earlier attempt re-walked every template seen so far for each `${…}` body, and a 154 KB page
+// of plain one-line templates took 18 seconds. Both views now come from one lexing pass, so time grows
+// with size — about 4x for 4x the source; quadratic growth would be about 16x.
+function shallowPage(lines) {
+ return 'import * as React from "react";\n'
+ + Array.from({ length: lines }, (_, i) => `const v${i} = \`a\${b(${i})}c\${\`d\${e}\`}\`; const s${i} = "t" + f(${i});`).join('\n')
+ + '\nexport default function Page() { return <div className={`x ${v0}`}>{s0}</div>; }\n';
+}
+
+test('performance: many shallow templates stay linear', () => {
+ const all = (code) => {
+ blankNonCodePreservingTemplateExpressions(code);
+ extractNavTargets(code);
+ pageStructureProblems(code);
+ };
+ const best = (code) => Math.min(measure(() => all(code)), measure(() => all(code)), measure(() => all(code)));
+ const small = shallowPage(1000);
+ const large = shallowPage(4000);
+ all(small); // warm up
+ const [tSmall, tLarge] = [best(small), best(large)];
+ assert.ok(tLarge < 1500, `${(large.length / 1024).toFixed(0)} KB of shallow templates took ${tLarge.toFixed(1)} ms`);
+ assert.ok(tLarge / Math.max(tSmall, 1) < 9, `4x the source took ${(tLarge / Math.max(tSmall, 1)).toFixed(1)}x the time (${tSmall.toFixed(1)} -> ${tLarge.toFixed(1)} ms)`);
+});
+
+// Page source is untrusted, so its nesting may not decide whether the lexer finishes: the lexer keeps
+// its frames on the heap, and a template nested 50,000 deep is read like any other.
+test('lexer finishes at any template nesting depth', () => {
+ const code = nestedFamily('ident', 50000);
+ const mask = blankNonCodePreservingTemplateExpressions(code);
+ assert.strictEqual(mask.length, code.length);
+ assert.strictEqual(hasDefaultExport(code), true);
+ assert.deepStrictEqual(pageStructureProblems(code), []);
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.js
index fd978d7c9..5dfa660b6 100644
--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js
@@ -43,19 +43,32 @@ const TRANSCRIPT = 'Conversation with 3 prompts:\r\n1. Build a list of inspectio
function capturingCli(opts = {}) {
const calls = [];
+ const downloads = [];
+ const nameReads = [];
return {
calls,
+ downloads,
+ nameReads,
factory: () => ({
upload: async (o) => { calls.push(o); return { pageId: '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8' }; },
// Default: the requested page exists. Tests that care override this.
enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),
enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),
+ // An update without a name re-sends the page's CURRENT name, read from its Dataverse row.
+ pageName: async (pid) => {
+ nameReads.push(pid);
+ if (opts.liveNameError) throw new Error(opts.liveNameError);
+ return opts.liveName !== undefined ? opts.liveName : 'Current Page';
+ },
+ // A pac.cmd shim cannot receive `%` or `"`; `opts.shim` makes this fake installation one.
+ argumentRefusal: (value) => (opts.shim && /[%"]/.test(value) ? `cannot pass ${JSON.stringify(value)} to pac.cmd: a Windows batch file cannot receive a double quote, %, a control character unchanged` : null),
// An update reads the page's CURRENT bindings so omitting `--data-sources` preserves them
// instead of persisting `[]`. pac writes this config UTF-8 with a BOM, so the fixture does too.
download: async ({ outputDir, pageIds }) => {
+ downloads.push(pageIds);
for (const pid of (pageIds || [])) {
fs.mkdirSync(path.join(outputDir, pid), { recursive: true });
- const body = JSON.stringify({ dataSources: opts.liveDataSources || ['contoso_ticket'] });
+ const body = JSON.stringify({ dataSources: opts.liveDataSources || ['contoso_ticket'], ...(opts.liveModel !== undefined ? { model: opts.liveModel } : {}) });
fs.writeFileSync(path.join(outputDir, pid, 'config.json'), Buffer.from('\uFEFF' + body, 'utf8'));
}
return true;
@@ -164,7 +177,7 @@ test('a display name passed by file reaches upload() intact, and a blank or doub
const nf = path.join(d, 'page-name.txt');
fs.writeFileSync(pf, 'Build the revenue page', 'utf8');
fs.writeFileSync(af, 'Initial deploy', 'utf8');
- const NAME = 'Revenue $100 \u2014 "Q3" $(whoami) `x` 100% & more';
+ const NAME = 'Revenue $100 \u2014 \u201cQ3\u201d $(whoami) `x` 100% & it\'s more';
fs.writeFileSync(nf, `\uFEFF${NAME}\r\n`, 'utf8');
const base = ['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'page.tsx', '--prompt-file', pf, '--agent-message-file', af];
const cli = capturingCli();
@@ -540,8 +553,7 @@ test('an /app-builder-shaped upload sends none of the standalone flags', async (
// pac's env-wide listing, in the LIVE shape (auto-sized fixed-width columns) — an invented format is
// correctly rejected as 'unrecognized', so a fixture that only LOOKS plausible tests the wrong path.
-const envListing = (ids) => {
- const names = ids.map((_, i) => `Page${i}`);
+const envListing = (ids, names = ids.map((_, i) => `Page${i}`)) => {
const nameW = Math.max(4, ...names.map((n) => n.length));
const header = 'Page ID'.padEnd(37) + 'Name'.padEnd(nameW + 1) + 'Published';
const body = ids.map((id, i) => `${id} ${names[i].padEnd(nameW)} -`).join('\n');
@@ -549,6 +561,118 @@ const envListing = (ids) => {
+ `Found ${ids.length} generated page(s):\n\n${header}\n${body}\n`;
};
+test('implicit update metadata reaches real wrapper argv', async () => {
+ const id = 'aaaaaaaa-0000-4000-8000-000000000001';
+ const appId = 'bbbbbbbb-0000-4000-8000-000000000002';
+ const env = 'https://contoso.crm.dynamics.com';
+ const navigationTitle = 'Navigation title';
+ const d = tmp();
+ const codeFile = path.join(d, 'page.tsx');
+ fs.writeFileSync(codeFile, 'export default function Page() { return null; }', 'utf8');
+ // No executable is started: both PAC installation shapes use the real invocation constructor.
+ const winPac = (file) => ({
+ platform: 'win32', env: { Path: 'C:\\pac', PATHEXT: '.EXE;.CMD', SystemRoot: 'C:\\Windows' },
+ exists: (p) => p === file, readFile: () => '@"%~dp0tools\\pac.exe" %*\r\n',
+ });
+ for (const [installation, storedName, expectedName] of [
+ ['pac.exe', 'Say \\"hi\\"', 'Say "hi"'],
+ ['pac.exe', 'Revenue 100%', 'Revenue 100%'],
+ ['pac.cmd', 'Revenue 100%', undefined],
+ ]) {
+ const seen = [];
+ const requests = [];
+ const probeDirs = [];
+ const uploadDirs = [];
+ const pacInvocation = winPac(`C:\\pac\\${installation}`);
+ const factory = (url) => makeGenpageCli(url, {
+ pacInvocation,
+ request: async (...args) => {
+ requests.push(args);
+ return { status: 200, data: { name: storedName } };
+ },
+ run: async (args) => {
+ const invocation = buildPacInvocation(args, pacInvocation);
+ seen.push({ args: [...args], invocation });
+ const valueOf = (flag) => args[args.indexOf(flag) + 1];
+ if (args[2] === 'list') {
+ const name = args.includes('--app-id') ? navigationTitle : storedName;
+ return { status: 0, stdout: envListing([id], [name]), stderr: '' };
+ }
+ if (args[2] === 'download') {
+ assert.strictEqual(valueOf('--page-id'), id);
+ const outputDir = valueOf('--output-directory');
+ probeDirs.push(outputDir);
+ dirs.push(outputDir);
+ const pageDir = path.join(outputDir, id.toUpperCase());
+ fs.mkdirSync(pageDir, { recursive: true });
+ const config = Buffer.from('\uFEFF' + JSON.stringify({ model: ' gpt-4.1 ', dataSources: ['contoso_ticket', 'contoso_asset'] }), 'utf8');
+ fs.writeFileSync(path.join(pageDir, 'config.json'), config);
+ assert.deepStrictEqual([...config.subarray(0, 3)], [0xef, 0xbb, 0xbf]);
+ return { status: 0, stdout: 'Downloaded 1 page(s)', stderr: '' };
+ }
+ assert.strictEqual(args[2], 'upload', 'only fake list/download/upload operations are permitted');
+ uploadDirs.push(path.dirname(valueOf('--prompt-file')));
+ dirs.push(uploadDirs[uploadDirs.length - 1]);
+ assert.strictEqual(fs.readFileSync(valueOf('--prompt-file'), 'utf8'), 'Fix the sort handler');
+ assert.strictEqual(fs.readFileSync(valueOf('--agent-message-file'), 'utf8'), 'Preserve page metadata');
+ return { status: 0, stdout: `Page ID: ${id}`, stderr: '' };
+ },
+ sleep: async () => {},
+ });
+ let result;
+ let cleanupAtEmit;
+ await main(['--env', env, '--app-id', appId, '--code-file', codeFile, '--page-id', id,
+ '--prompt', 'Fix the sort handler', '--agent-message', 'Preserve page metadata'], {
+ makeGenpageCli: factory,
+ emit: (ok, payload) => {
+ cleanupAtEmit = [...probeDirs, ...uploadDirs].map((dir) => fs.existsSync(dir));
+ result = { ok, payload };
+ },
+ });
+ assert.strictEqual(result.ok, true, `${installation}: ${JSON.stringify(result.payload)}`);
+ assert.deepStrictEqual([result.payload.pageId, result.payload.appId, result.payload.updated], [id, appId, true]);
+ assert.deepStrictEqual(requests, [[env, 'GET', `uxagentprojects(${id})?$select=name`]], 'the page row, not its navigation title, supplies the implicit name');
+ const listings = seen.filter((call) => call.args[2] === 'list');
+ assert.strictEqual(listings.length, 2);
+ assert.ok(listings.some((call) => !call.args.includes('--app-id') && call.args.includes('--include-unpublished')), 'existence is checked environment-wide');
+ assert.ok(listings.some((call) => call.args.includes('--app-id')), 'app membership is also checked');
+ const uploads = seen.filter((call) => call.args[2] === 'upload');
+ assert.strictEqual(uploads.length, 1);
+ const { args, invocation } = uploads[0];
+ const valueOf = (flag) => {
+ assert.strictEqual(args.filter((a) => a === flag).length, 1, `${installation}: ${flag} appears exactly once`);
+ return args[args.indexOf(flag) + 1];
+ };
+ assert.strictEqual(valueOf('--environment'), env);
+ assert.strictEqual(valueOf('--app-id'), appId);
+ assert.strictEqual(valueOf('--page-id'), id);
+ assert.strictEqual(valueOf('--code-file'), codeFile);
+ assert.strictEqual(valueOf('--model'), 'gpt-4.1');
+ assert.strictEqual(valueOf('--data-sources'), 'contoso_ticket,contoso_asset');
+ for (const flag of ['--connectors', '--actions', '--add-to-sitemap']) assert.ok(!args.includes(flag), flag);
+ if (expectedName !== undefined) {
+ assert.strictEqual(valueOf('--name'), expectedName);
+ assert.notStrictEqual(valueOf('--name'), navigationTitle);
+ assert.strictEqual(result.payload.warnings, undefined, 'metadata that reaches native PAC intact produces no warning');
+ assert.strictEqual(invocation.file, 'C:\\pac\\pac.exe');
+ assert.deepStrictEqual(invocation.args, args, 'native PAC receives every argument verbatim');
+ assert.strictEqual(invocation.options.shell, false);
+ } else {
+ assert.ok(!args.includes('--name'), 'an implicit name containing % must never reach a batch shim');
+ assert.strictEqual(result.payload.warnings.length, 1);
+ assert.match(result.payload.warnings[0], /name "Revenue 100%" could not be sent to keep it \(cannot pass .* to pac\.cmd/);
+ assert.match(result.payload.warnings[0], /pac may have renamed the page to its navigation title/);
+ assert.strictEqual(invocation.file, 'C:\\Windows\\System32\\cmd.exe');
+ assert.ok(!invocation.args[4].includes('Revenue 100%'));
+ assert.ok(invocation.args[4].includes('--model gpt-4.1'));
+ assert.ok(invocation.args[4].includes('--data-sources contoso_ticket,contoso_asset'));
+ assert.strictEqual(invocation.options.windowsVerbatimArguments, true);
+ }
+ assert.deepStrictEqual([probeDirs.length, uploadDirs.length], [1, 1]);
+ assert.deepStrictEqual(cleanupAtEmit, [false, false], 'both temp directories are gone before the emitter can exit');
+ }
+});
+
test('REAL wrapper: updating an id absent from the environment is refused and never uploads', async () => {
const seen = [];
const factory = (env) => makeGenpageCli(env, {
@@ -692,11 +816,13 @@ test('an explicit --data-sources still WINS over the preserved list', async () =
assert.strictEqual(cli.calls[0].dataSources, 'contoso_other', 'an explicit value is the caller\'s intent');
});
-test('--clear-data-sources really unbinds, and does not read the old list first', async () => {
+test('--clear-data-sources really unbinds, and does not depend on reading the old list first', async () => {
let probed = false;
const factory = () => ({
enumerateEnvironment: async () => ({ ok: true, ids: ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'] }),
enumeratePages: async () => ({ ok: true, pages: [{ pageId: '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', name: 'Current Page' }] }),
+ // The page is read for its MODEL (the update omits --model) — and here that read fails, which must
+ // not stop a deliberate unbind: the model is metadata, reported, never a reason to refuse.
download: async () => { probed = true; return true; },
upload: async (o) => { probed = probed || false; return { pageId: o.pageId, _ds: o.dataSources }; },
});
@@ -712,7 +838,166 @@ test('--clear-data-sources really unbinds, and does not read the old list first'
});
assert.strictEqual(r.ok, true, `a deliberate unbind must be allowed; got ${JSON.stringify(r.payload)}`);
assert.strictEqual(seen[0].dataSources, undefined, 'nothing is sent, so pac clears the bindings');
- assert.strictEqual(probed, false, 'a deliberate clear need not read the list it is discarding');
+ assert.strictEqual(probed, true, 'the page is read for its model');
+ assert.match(r.payload.warnings[0], /could not read page 9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d's current model \(pac wrote no directory for this page\)/);
+ assert.strictEqual(seen[0].model, undefined);
+});
+
+// pac stores whatever `--model` an upload sends, so an update without one wiped the deployed model id to
+// "" (live-measured). Absence is "no opinion", as for the bindings: the current model is re-sent.
+test('an update that omits --model re-sends the page\'s current model; an explicit one wins', async () => {
+ const run = (cli, extra) => new Promise((resolve) => {
+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx',
+ '--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt', 'p', ...extra],
+ { makeGenpageCli: cli.factory, emit: (ok, payload) => resolve({ ok, payload }) });
+ });
+ const kept = capturingCli({ liveModel: ' gpt-4.1 ' });
+ assert.strictEqual((await run(kept, [])).ok, true);
+ assert.strictEqual(kept.calls[0].model, 'gpt-4.1');
+
+ // Named bindings do not stop the model being read: the download is then for the model alone.
+ const withBindings = capturingCli({ liveModel: 'gpt-4.1' });
+ assert.strictEqual((await run(withBindings, ['--data-sources', 'contoso_other'])).ok, true);
+ assert.deepStrictEqual([withBindings.downloads.length, withBindings.calls[0].model, withBindings.calls[0].dataSources], [1, 'gpt-4.1', 'contoso_other']);
+
+ const explicit = capturingCli({ liveModel: 'gpt-4.1' });
+ assert.strictEqual((await run(explicit, ['--model', 'gpt-5', '--data-sources', 'contoso_other'])).ok, true);
+ assert.deepStrictEqual([explicit.downloads.length, explicit.calls[0].model], [0, 'gpt-5'], 'nothing to read when both are named');
+
+ // A page with no model has nothing to re-send — and a model that is not a string is reported, not sent.
+ const none = capturingCli({});
+ const noneRun = await run(none, []);
+ assert.deepStrictEqual([noneRun.ok, none.calls[0].model, noneRun.payload.warnings], [true, undefined, undefined]);
+ const odd = capturingCli({ liveModel: 42 });
+ const oddRun = await run(odd, []);
+ assert.strictEqual(oddRun.ok, true);
+ assert.strictEqual(odd.calls[0].model, undefined);
+ assert.match(oddRun.payload.warnings[0], /config\.json model is number, not a string/);
+
+ // A create has no current model to keep.
+ const created = capturingCli({ liveModel: 'gpt-4.1' });
+ const createRun = await new Promise((resolve) => {
+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx', '--prompt', 'p', '--agent-message', 'm'],
+ { makeGenpageCli: created.factory, emit: (ok, payload) => resolve({ ok, payload }) });
+ });
+ assert.deepStrictEqual([createRun.ok, created.downloads.length, created.calls[0].model], [true, 0, undefined]);
+});
+
+// pac stores every ASCII `"` in a page name as `\"` — in the page row and in the navigation title it writes —
+// and nothing else (live-measured). Such a name is refused before anything is read or deployed.
+test('a page name with an ASCII double quote is refused before anything is deployed', async () => {
+ const d = tmp();
+ const nf = path.join(d, 'page-name.txt');
+ fs.writeFileSync(nf, 'Say "hi" now\n', 'utf8');
+ const base = ['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx', '--prompt', 'p', '--agent-message', 'm'];
+ for (const [label, extra] of [
+ ['create, by file', ['--name-file', nf]],
+ ['create, inline', ['--name', 'Say "hi" now']],
+ ['update, by file', ['--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--name-file', nf]],
+ ]) {
+ const cli = capturingCli();
+ const r = await runMain([...base, ...extra], cli);
+ assert.strictEqual(r.ok, false, label);
+ assert.match(r.payload.error, /the page name "Say \\"hi\\" now" contains an ASCII double quote/, label);
+ assert.match(r.payload.error, /typographic quotes \(“ ”\) or an apostrophe/, label);
+ assert.deepStrictEqual([cli.calls.length, cli.downloads.length, cli.nameReads.length], [0, 0, 0], `${label}: nothing read or deployed`);
+ }
+ // CONTROL — the characters pac keeps as they are still deploy.
+ const ok = capturingCli();
+ const kept = await runMain([...base, '--name', 'Back\\slash “curly” \'single\' 東京'], ok);
+ assert.strictEqual(kept.ok, true, JSON.stringify(kept.payload));
+ assert.strictEqual(ok.calls[0].name, 'Back\\slash “curly” \'single\' 東京');
+});
+
+// An update without a name renamed the page to its navigation title (live-reproduced after an earlier rename), so the
+// update re-sends the page's current name, read from its row. pac stores `"` as `\"`, so a stored `\"` is sent back as
+// `"` — pac's escaping then stores the same value again.
+test('an update without a name re-sends the page\'s current name; a named update or a create reads nothing', async () => {
+ const PID = '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d';
+ const update = ['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx', '--page-id', PID, '--prompt', 'p'];
+ const renamed = capturingCli({ liveName: 'Renamed Alpha' });
+ const r = await runMain(update, renamed);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.deepStrictEqual([renamed.nameReads, renamed.calls[0].name, r.payload.warnings], [[PID], 'Renamed Alpha', undefined]);
+
+ // What pac stored for `Say "hi" \"x\"` — every quote escaped once — goes back exactly one escape shorter.
+ const escaped = capturingCli({ liveName: 'Say \\"hi\\" \\\\"x\\\\"' });
+ const e = await runMain(update, escaped);
+ assert.strictEqual(e.ok, true);
+ assert.strictEqual(escaped.calls[0].name, 'Say "hi" \\"x\\"');
+ assert.strictEqual(e.payload.warnings, undefined, 'a name pac wrote is kept exactly, so there is nothing to report');
+
+ // A `"` pac did not write cannot be stored as it is. The update still goes ahead, and says what changed.
+ for (const raw of ['Say "hi"', '"Quoted', 'Mixed \\"a\\" and "b"']) {
+ const cli = capturingCli({ liveName: raw });
+ const run = await runMain(update, cli);
+ assert.strictEqual(run.ok, true, raw);
+ assert.strictEqual(cli.calls[0].name, raw.replace(/\\"/g, '"'), raw);
+ assert.strictEqual(run.payload.warnings.length, 1, raw);
+ assert.match(run.payload.warnings[0], /has a double quote \(\"\) pac cannot store as it is, so the page now shows \\" there/, raw);
+ }
+
+ // Not knowing the name never blocks the update: it is reported, and pac is left to its default.
+ const unread = capturingCli({ liveNameError: 'Request failed: socket hang up' });
+ const u = await runMain(update, unread);
+ assert.strictEqual(u.ok, true);
+ assert.strictEqual(unread.calls[0].name, undefined);
+ assert.match(u.payload.warnings[0], new RegExp(`could not read page ${PID}'s current name \\(Request failed: socket hang up\\), so pac may have renamed it to its navigation title`));
+ const noMethod = capturingCli();
+ const plain = noMethod.factory;
+ noMethod.factory = () => { const f = plain(); delete f.pageName; return f; };
+ const m = await runMain(update, noMethod);
+ assert.strictEqual(m.ok, true);
+ assert.match(m.payload.warnings[0], /cannot read a page name/);
+ // A blank stored name has nothing to keep.
+ const blank = capturingCli({ liveName: ' ' });
+ const b = await runMain(update, blank);
+ assert.deepStrictEqual([b.ok, blank.calls[0].name, b.payload.warnings], [true, undefined, undefined]);
+
+ // A name pac cannot be handed here — a pac.cmd shim cannot receive `%` or `"` — is not sent: the update goes ahead
+ // as it did before names were kept (pac may rename the page to its title), and says so. Refusing it would block an
+ // ordinary content edit on the page's name.
+ for (const stored of ['Revenue 100%', 'Say \\"hi\\"']) {
+ const shim = capturingCli({ liveName: stored, shim: true });
+ const s = await runMain(update, shim);
+ assert.strictEqual(s.ok, true, stored);
+ assert.strictEqual(shim.calls[0].name, undefined, `${stored}: not sent`);
+ assert.strictEqual(s.payload.warnings.length, 1, stored);
+ assert.match(s.payload.warnings[0], /could not be sent to keep it \(cannot pass .* to pac\.cmd/, stored);
+ assert.match(s.payload.warnings[0], /pac may have renamed the page to its navigation title/, stored);
+ }
+ const shimPlain = capturingCli({ liveName: 'Renamed Alpha', shim: true });
+ const sp = await runMain(update, shimPlain);
+ assert.deepStrictEqual([sp.ok, shimPlain.calls[0].name, sp.payload.warnings], [true, 'Renamed Alpha', undefined], 'a name the shim can receive is still kept');
+
+ // A named update and a create read nothing: the caller's name is the one deployed.
+ const named = capturingCli({ liveName: 'Renamed Alpha' });
+ assert.strictEqual((await runMain([...update, '--name', 'New Title'], named)).ok, true);
+ assert.deepStrictEqual([named.nameReads.length, named.calls[0].name], [0, 'New Title']);
+ const created = capturingCli({ liveName: 'Renamed Alpha' });
+ const c = await runMain(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx', '--prompt', 'p', '--agent-message', 'm'], created);
+ assert.deepStrictEqual([c.ok, created.nameReads.length, created.calls[0].name], [true, 0, undefined]);
+});
+
+// The row is read over the Web API with the az token — pac cannot read it: its listing shows each page's navigation
+// title. The id goes into a key segment, so anything but a bare GUID is refused before a request is made.
+test('pageName() reads the page row\'s name, and refuses an id that is not a GUID', async () => {
+ const seen = [];
+ const request = async (env, method, apiPath) => {
+ seen.push([env, method, apiPath]);
+ if (apiPath.startsWith('uxagentprojects(0')) return { status: 404, data: { error: { message: 'Does Not Exist' } } };
+ if (apiPath.startsWith('uxagentprojects(1')) return { status: 200, data: {} };
+ return { status: 200, data: { name: 'Renamed Alpha' } };
+ };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { request });
+ assert.strictEqual(await cli.pageName('9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'), 'Renamed Alpha');
+ assert.deepStrictEqual(seen[0], ['https://contoso.crm.dynamics.com', 'GET', 'uxagentprojects(9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d)?$select=name']);
+ assert.strictEqual(await cli.pageName('1f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'), null, 'a row without a name');
+ await assert.rejects(cli.pageName('0f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d'), /name returned HTTP 404/);
+ for (const bad of ['9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d)?$select=name,prompt&x=(', ' 9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '', undefined]) {
+ await assert.rejects(cli.pageName(bad), /is not a page id/, String(bad));
+ }
+ assert.strictEqual(seen.length, 3, 'no request for an id that is not a GUID');
});
test('an unreadable current binding list refuses the update rather than unbinding the page', async () => {
diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.js
index 3f8489951..2c03f11ea 100644
--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js
+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js
@@ -210,6 +210,26 @@ test('hydrateSpec emits the v2 shape when pages carry keys (schemaVersion 2, sou
assert.strictEqual(spec.appShell.areas[0].groups[0].subAreas[0].page, 'overview', 'GenPage subarea resolved by KEY');
});
+// A page's model rides the spec from download to rebuild, in either page shape; a page without one gets no key.
+test('hydrateSpec carries each page\'s model, in the v2 and the legacy shape', async () => {
+ const siteMap = { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [
+ { type: 'GenPage', genPageId: 'gp-o', title: 'Overview' }, { type: 'GenPage', genPageId: 'gp-d', title: 'Detail' }] }] }] };
+ const base = { app: async () => ({ name: 'A', description: '', siteMap }), entities: async () => [], webResources: async () => [],
+ solution: async () => ({ uniqueName: 'S', publisherPrefix: 'new' }) };
+ const v2 = await hydrateSpec({ ...base, pages: async () => [
+ { pageId: 'gp-o', key: 'overview', name: 'Overview', model: 'gpt-4.1', dataSources: [], codeFile: 'overview.tsx' },
+ { pageId: 'gp-d', key: 'detail', name: 'Detail', dataSources: [], codeFile: 'detail.tsx' }] });
+ assert.strictEqual(v2.schemaVersion, 2);
+ assert.deepStrictEqual(v2.pages.map((p) => [p.key, p.model]), [['overview', 'gpt-4.1'], ['detail', undefined]]);
+ assert.ok(!('model' in v2.pages[1]));
+ const legacy = await hydrateSpec({ ...base, pages: async () => [
+ { pageId: 'gp-o', name: 'Overview', model: 'gpt-4.1', dataSources: [], codeFile: 'overview.tsx' },
+ { pageId: 'gp-d', name: 'Detail', dataSources: [], codeFile: 'detail.tsx' }] });
+ assert.strictEqual(legacy.schemaVersion, undefined);
+ assert.deepStrictEqual(legacy.pages.map((p) => [p.name, p.model]), [['Overview', 'gpt-4.1'], ['Detail', undefined]]);
+ assert.ok(!('model' in legacy.pages[1]));
+});
+
test('hydrateSpec keeps the legacy name-based shape when pages carry no key (back-compat)', async () => {
const read = {
app: async () => ({ name: 'A', description: '', siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ type: 'GenPage', genPageId: 'gp-o', title: 'Overview' }] }] }] } }),
diff --git a/plugins/model-apps/scripts/tests/list-connections.test.js b/plugins/model-apps/scripts/tests/list-connections.test.js
index 573540687..6edaac443 100644
--- a/plugins/model-apps/scripts/tests/list-connections.test.js
+++ b/plugins/model-apps/scripts/tests/list-connections.test.js
@@ -4,6 +4,7 @@ const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
const { spawnSync } = require('node:child_process');
+const { loadCli } = require('./helpers/cli-harness.js');
const scriptPath = path.join(__dirname, '..', 'list-connections.js');
const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
@@ -199,13 +200,39 @@ test('extractConnectorId returns the api path, or empty string when there is non
assert.equal(extractConnectorId('garbage'), '');
});
-test('unparseable output yields no rows rather than throwing', () => {
- // The caller reports "no connections found"; a throw here would abort a /genpage run that could
- // still proceed with mock data.
- assert.deepEqual(parsePacConnectionList('no table here'), []);
- assert.deepEqual(parsePacConnectionList(''), []);
- assert.equal(parseJsonConnections('{not json'), null, 'invalid JSON defers to the table parsers');
- assert.equal(parseJsonConnections('"a string"'), null, 'non-array JSON defers too');
+// Output no parser recognises is REFUSED, never read as "no connections". That answer sends the connector
+// agent on to CREATE a connection (genpage-connector-builder.md, "No suitable connection exists"), so an
+// unreadable listing — a warning printed on a zero exit, JSON cut short, a changed format — would make a
+// duplicate of a connection the maker already has.
+test('unreadable output is refused, never read as "no connections"', () => {
+ for (const raw of ['Warning: failed to retrieve connections.', 'not JSON', '[{"Id":', '{"unexpected":true}', 'no table here', '', 'Connected as [email protected]\r\n', 'null',
+ // Prose that only MENTIONS a connector or an id column is not a table header — nor is prose over a run of dashes.
+ 'Warning: failed to retrieve connector metadata.', 'Connection Id could not be read.',
+ 'Status of connector refresh\n------ -------\n', 'Connector Status\nshared_sql Connected\n']) {
+ assert.throws(() => parsePacConnectionList(raw), /could not read[\s\S]*not reported as "no connections"/, JSON.stringify(raw));
+ }
+ assert.throws(() => parsePacConnectionList('Warning: failed to retrieve connections.'), /first line: "Warning: failed to retrieve connections\."/);
+ // The helper itself still answers "not JSON" with null, for the caller to judge.
+ assert.equal(parseJsonConnections('{not json'), null);
+ assert.equal(parseJsonConnections('"a string"'), null);
+});
+
+test('an empty listing is one PAC itself reports as empty', () => {
+ for (const raw of ['[]', '{"value":[]}', 'No connections found.', 'Connected as [email protected]\r\nNo connections found.\r\n',
+ 'Connected as [email protected]\r\nId Name API Id Status\r\n',
+ 'Connection Name Connector Id Connection Id\n--------------- ------------ -------------\n']) {
+ assert.deepEqual(parsePacConnectionList(raw), [], JSON.stringify(raw));
+ }
+});
+
+// An identifier is a non-empty string. Whitespace, a number, an object or an array in an id column made a
+// row with "both ids" that nothing could ever bind — offered to the maker as a real connection.
+test('identifiers must be non-empty strings, trimmed', () => {
+ for (const [Id, ConnectorId] of [[' ', '\t'], [42, 27], [{ nested: 'x' }, { nested: 'y' }], [['a'], ['b']]]) {
+ assert.throws(() => parsePacConnectionList(JSON.stringify([{ Id, ConnectorId }])), /no usable connection rows/, JSON.stringify({ Id, ConnectorId }));
+ }
+ assert.deepEqual(parsePacConnectionList(JSON.stringify([{ Id: ' connection-a ', ConnectorId: ` ${SP_API}\t` }])),
+ [{ connectorId: SP_API, connectionId: 'connection-a', displayName: SP_API }]);
});
test('rows with no identifying field at all are dropped', () => {
@@ -241,3 +268,146 @@ test('a row without both ids is dropped beside usable rows, never offered as a p
].join('\n');
assert.deepEqual(parsePacConnectionList(table).map((r) => r.connectionId), [SP_CONN]);
});
+
+// main() is the only place a PAC result becomes a connection-reference query and then a structured
+// result. Parser unit tests never see a zero exit with a warning turned into `{ ok: true, connections: [] }`,
+// which is the answer that sends connection setup on to create a duplicate.
+const ENV_URL = 'https://contoso.crm.dynamics.com';
+const SQL_API = '/providers/Microsoft.PowerApps/apis/shared_sql';
+const SQL_CONN = '/providers/Microsoft.PowerApps/apis/shared_sql/connections/sql1';
+
+function driveDiscovery({ pac, refs, refsError }) {
+ const spawned = [];
+ const queries = [];
+ const emitted = [];
+ const real = require('../lib/dataverse-auth.js');
+ const cli = loadCli(scriptPath, {
+ argv: [ENV_URL],
+ requires: {
+ './lib/process-runner.js': {
+ spawnResultSync: (cmd, args, opts) => {
+ spawned.push({ cmd, args, opts });
+ return pac;
+ },
+ },
+ // Required without the `.js` suffix. emitResult sits inside main's try, so a throwing stand-in
+ // would be caught and re-reported as a discovery failure — hiding the payload under test.
+ // The real printer exits instead of throwing, which is what this recording stands in for.
+ './lib/dataverse-auth': {
+ parseArgs: real.parseArgs,
+ validateFlags: real.validateFlags,
+ ensureOk: real.ensureOk,
+ dataverseRequest: async (envUrl, method, apiPath) => {
+ queries.push({ envUrl, method, apiPath });
+ if (refsError) throw refsError;
+ return refs;
+ },
+ emitResult: (ok, payload) => { emitted.push({ ok, payload }); },
+ },
+ },
+ });
+ return cli.main().then(() => ({ spawned, queries, emitted }));
+}
+
+test('CLI discovery failure is not an empty success', async () => {
+ const warning = 'Warning: failed to retrieve connections.';
+ const warningMessage = 'pac connection list printed output this script could not read — no connection table, JSON list or "no connections found" message '
+ + `(first line: "${warning}"). It is not reported as "no connections", which would lead connection setup to create a duplicate; run \`pac connection list\` to see what it printed.`;
+ const malformed = '[{"Id":';
+ const malformedMessage = 'pac connection list printed output this script could not read — it starts like JSON but is not a connection list '
+ + `(first line: "${malformed}"). It is not reported as "no connections", which would lead connection setup to create a duplicate; run \`pac connection list\` to see what it printed.`;
+
+ const refused = await driveDiscovery({ pac: { status: 0, stdout: warning, stderr: '' } });
+ assert.deepEqual(refused.spawned.map((s) => [s.cmd, s.args]), [['pac', ['connection', 'list']]]);
+ assert.deepEqual(refused.queries, [], 'a warning on exit 0 must not query connection references');
+ assert.equal(refused.emitted.length, 1);
+ assert.equal(refused.emitted[0].ok, false);
+ assert.equal(refused.emitted[0].payload.message, warningMessage);
+
+ const badTable = await driveDiscovery({ pac: { status: 0, stdout: malformed, stderr: '' } });
+ assert.deepEqual(badTable.queries, []);
+ assert.equal(badTable.emitted[0].ok, false);
+ assert.equal(badTable.emitted[0].payload.message, malformedMessage);
+
+ const nonzero = await driveDiscovery({ pac: { status: 2, stdout: '', stderr: 'Access denied' } });
+ assert.deepEqual(nonzero.queries, []);
+ assert.equal(nonzero.emitted[0].ok, false);
+ assert.equal(nonzero.emitted[0].payload.message, 'pac connection list failed (exit 2): Access denied');
+
+ const missing = await driveDiscovery({ pac: { error: new Error('spawn pac ENOENT'), status: null, stdout: '', stderr: '' } });
+ assert.deepEqual(missing.queries, []);
+ assert.equal(missing.emitted[0].ok, false);
+ assert.equal(
+ missing.emitted[0].payload.message,
+ 'pac connection list could not run: spawn pac ENOENT. Ensure the PAC CLI is installed and on PATH (dotnet tool install -g Microsoft.PowerApps.CLI.Tool).'
+ );
+
+ const empty = await driveDiscovery({
+ pac: { status: 0, stdout: 'No connections found.', stderr: '' },
+ refs: { status: 200, data: { value: [] } },
+ });
+ assert.deepEqual(empty.queries, [{
+ envUrl: ENV_URL,
+ method: 'GET',
+ apiPath: 'connectionreferences?$select=connectionreferencelogicalname,connectorid,connectionid',
+ }]);
+ assert.deepEqual(empty.emitted, [{
+ ok: true,
+ payload: { ok: true, connections: [], connectionReferences: [] },
+ }]);
+
+ const listed = await driveDiscovery({
+ pac: {
+ status: 0,
+ stdout: JSON.stringify([
+ { 'Connection Name': 'Zulu SQL', 'Connector Id': SQL_API, 'Connection Id': SQL_CONN },
+ { 'Connection Name': 'Alpha SharePoint', 'Connector Id': SP_API, 'Connection Id': SP_CONN },
+ ]),
+ stderr: '',
+ },
+ refs: {
+ status: 200,
+ data: {
+ value: [
+ { connectionreferencelogicalname: 'new_sql_unbound', connectorid: SQL_API, connectionid: null },
+ { connectionreferencelogicalname: 'new_sp_bound', connectorid: SP_API, connectionid: SP_CONN },
+ ],
+ },
+ },
+ });
+ assert.equal(listed.queries[0].envUrl, ENV_URL);
+ assert.deepEqual(listed.emitted, [{
+ ok: true,
+ payload: {
+ ok: true,
+ connections: [
+ {
+ connectorId: SP_API,
+ connectionId: SP_CONN,
+ displayName: 'Alpha SharePoint',
+ readyToBind: true,
+ connectionReferences: ['new_sp_bound'],
+ },
+ {
+ connectorId: SQL_API,
+ connectionId: SQL_CONN,
+ displayName: 'Zulu SQL',
+ readyToBind: false,
+ connectionReferences: ['new_sql_unbound'],
+ },
+ ],
+ connectionReferences: [
+ { logicalName: 'new_sp_bound', connectorId: SP_API, connectionId: SP_CONN },
+ { logicalName: 'new_sql_unbound', connectorId: SQL_API, connectionId: null },
+ ],
+ },
+ }]);
+
+ const refsDown = await driveDiscovery({
+ pac: { status: 0, stdout: 'No connections found.', stderr: '' },
+ refs: { status: 500, data: { error: { message: 'refs unavailable' } } },
+ });
+ assert.equal(refsDown.queries.length, 1, 'the reference read is attempted only after a readable listing');
+ assert.equal(refsDown.emitted[0].ok, false);
+ assert.equal(refsDown.emitted[0].payload.message, 'List connection references failed: HTTP 500 — refs unavailable');
+});
diff --git a/plugins/model-apps/scripts/tests/page-download-rebuild.test.js b/plugins/model-apps/scripts/tests/page-download-rebuild.test.js
new file mode 100644
index 000000000..cf02a3e6f
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/page-download-rebuild.test.js
@@ -0,0 +1,182 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { runDownload } = require('../download-model-app.js');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { makeGenpageCli } = require('../lib/genpage-cli.js');
+const { buildManifest } = require('../lib/page-manifest.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const APP_ID = 'aaaaaaaa-0000-4000-8000-000000000001';
+const APP_UNIQUE = 'contoso_roundtrip';
+const APP_UNIQUE_ID = 'aaaaaaaa-0000-4000-8000-000000000002';
+const SITEMAP_ID = 'aaaaaaaa-0000-4000-8000-000000000003';
+const SOLUTION_ID = 'aaaaaaaa-0000-4000-8000-000000000004';
+const OVERVIEW_ID = 'bbbbbbbb-0000-4000-8000-000000000001';
+const DETAIL_ID = 'bbbbbbbb-0000-4000-8000-000000000002';
+
+function listing(pages) {
+ const width = Math.max(4, ...pages.map((p) => p.name.length));
+ const header = 'Page ID'.padEnd(37) + 'Name'.padEnd(width + 1) + 'Published';
+ const rows = pages.map((p) => `${p.pageId} ${p.name.padEnd(width)} -`).join('\n');
+ return `Connected as [email protected]\nRetrieving generated pages...\nFound ${pages.length} generated page(s):\n\n${header}\n${rows}\n`;
+}
+
+test('download-hydrate-rebuild preserves page identity name model and bindings', async () => {
+ for (const secondModel of ['has space', undefined]) {
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-download-rebuild-'));
+ try {
+ const canonical = 'export default function Overview() { Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", data: {} }); return null; }\r\n';
+ const deployed = canonical.replace('"PAGEREF_detail"', `"${DETAIL_ID}"`);
+ const detailCode = 'export default function Detail() { return null; }\r\n';
+ const pages = new Map([
+ [OVERVIEW_ID, { name: 'Say \\"hi\\"', code: deployed, dataSources: ['contoso_item', 'account'], model: 'gpt-4.1' }],
+ [DETAIL_ID, { name: 'Item Detail', code: detailCode, dataSources: ['contoso_item'], ...(secondModel === undefined ? {} : { model: secondModel }) }],
+ ]);
+ const app = {
+ name: 'Roundtrip App', uniquename: APP_UNIQUE, description: '',
+ siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Pages', subAreas: [
+ { type: 'GenPage', genPageId: OVERVIEW_ID, title: 'Overview navigation' },
+ { type: 'GenPage', genPageId: DETAIL_ID, title: 'Detail navigation' },
+ { type: 'Entity', entity: 'contoso_item' },
+ ] }] }] },
+ };
+ const sitemapXml = `<SiteMap><Area><Group><SubArea GenPageId="${OVERVIEW_ID}" Title="Overview navigation"/><SubArea GenPageId="${DETAIL_ID}" Title="Detail navigation"/></Group></Area></SiteMap>`;
+ const manifest = buildManifest({ pages: [
+ { key: 'overview', name: 'Old overview name', navigatesTo: [{ targetKey: 'detail' }] },
+ { key: 'detail', name: 'Old detail name' },
+ ] }, new Map([['overview', OVERVIEW_ID], ['detail', DETAIL_ID]]));
+ let manifestContent = Buffer.from(JSON.stringify(manifest), 'utf8').toString('base64');
+ const { sdk, calls: sdkCalls } = makeSimpleMockSdk();
+ const fetchArtifact = sdk.fetchArtifact;
+ sdk.fetchArtifact = async (kind, id) => {
+ const artifact = await fetchArtifact(kind, id);
+ return kind === 'app' ? Object.assign(artifact, JSON.parse(JSON.stringify(app))) : artifact;
+ };
+ sdk.findArtifact = async (kind) => kind === 'app' ? APP_ID : null;
+ sdk.listArtifacts = async (kind) => kind === 'app' ? [{ id: APP_ID, isDirty: false }] : [];
+ sdk.findTables = async () => [{ logicalName: 'contoso_item', entitySetName: 'contoso_items' }];
+ sdk.fetchEntityMetadata = async (logical) => ({
+ logicalName: logical, schemaName: logical, displayName: 'Item',
+ primaryNameAttribute: 'contoso_name', entitySetName: 'contoso_items', attributes: [], relationships: [],
+ });
+ sdk.dataverse = { get: async () => ({ status: 200, body: { value: [] } }) };
+ sdk.queryRecords = async (logical, opts = {}) => {
+ if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: APP_UNIQUE }];
+ if (logical === 'appmodulecomponent') return /componenttype eq 62/.test(opts.filter || '') ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [];
+ if (logical === 'sitemap') return [{ sitemapid: SITEMAP_ID, sitemapxml: sitemapXml }];
+ if (logical === 'webresource') return /_pagemanifest'/.test(opts.filter || '') ? [{ webresourceid: 'manifest', content: manifestContent }] : [];
+ if (logical === 'solutioncomponent') return [{ _solutionid_value: SOLUTION_ID }];
+ if (logical === 'solution') return [{ solutionid: SOLUTION_ID, uniquename: 'ContosoRoundtrip', ismanaged: false }];
+ return [];
+ };
+ sdk.updateWebResource = async (id, value) => {
+ assert.strictEqual(id, 'manifest');
+ manifestContent = Buffer.from(value.content, 'utf8').toString('base64');
+ };
+
+ const calls = [];
+ const uploads = [];
+ const cli = makeGenpageCli(ENV, {
+ run: async (args) => {
+ calls.push([...args]);
+ const valueOf = (flag) => args[args.indexOf(flag) + 1];
+ assert.strictEqual(valueOf('--environment'), ENV);
+ if (args[2] === 'list') return { status: 0, stdout: listing([...pages].map(([pageId, p]) => ({ pageId, name: p.name }))), stderr: '' };
+ assert.strictEqual(valueOf('--app-id'), APP_ID);
+ if (args[2] === 'download') {
+ assert.deepStrictEqual(valueOf('--page-id').split(',').sort(), [OVERVIEW_ID, DETAIL_ID].sort());
+ for (const [id, p] of pages) {
+ const dir = path.join(valueOf('--output-directory'), id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'page.tsx'), p.code, 'utf8');
+ fs.writeFileSync(path.join(dir, 'config.json'), '\uFEFF' + JSON.stringify({ dataSources: p.dataSources, ...(p.model === undefined ? {} : { model: p.model }) }), 'utf8');
+ assert.deepStrictEqual([...fs.readFileSync(path.join(dir, 'config.json')).subarray(0, 3)], [0xef, 0xbb, 0xbf]);
+ }
+ return { status: 0, stdout: 'Downloaded 2 page(s)', stderr: '' };
+ }
+ assert.strictEqual(args[2], 'upload', 'only fake list/download/upload operations are permitted');
+ assert.ok(args.includes('--page-id'), 'a downloaded page must be updated, never created');
+ const id = valueOf('--page-id');
+ const content = fs.readFileSync(valueOf('--code-file'), 'utf8');
+ uploads.push({ args: [...args], content });
+ // Model PAC's stored escaping so a second round-trip catches accumulating backslashes.
+ Object.assign(pages.get(id), {
+ name: valueOf('--name').replace(/"/g, '\\"'), code: content,
+ dataSources: valueOf('--data-sources').split(','),
+ model: args.includes('--model') ? valueOf('--model') : '',
+ });
+ return { status: 0, stdout: `Page ID: ${id}`, stderr: '' };
+ },
+ request: async () => { throw new Error('unexpected Dataverse request: all page I/O must be fake'); },
+ sleep: async () => {},
+ });
+
+ for (let round = 0; round < 2; round++) {
+ const warnings = [];
+ const write = process.stderr.write;
+ let downloaded;
+ process.stderr.write = (chunk) => { warnings.push(String(chunk)); return true; };
+ try {
+ downloaded = await runDownload({ sdk, genpageCli: cli, outDir: appDir, appId: APP_ID, appUnique: APP_UNIQUE });
+ } finally { process.stderr.write = write; }
+ assert.ok(downloaded.ok, JSON.stringify(downloaded));
+ // Persisted JSON drops transient diagnostics, just as the download CLI's app-spec.json does.
+ const spec = JSON.parse(JSON.stringify(downloaded.spec));
+ const validation = validateAppSpec(spec);
+ assert.ok(validation.ok, validation.errors.join('; '));
+ const overview = spec.pages.find((p) => p.key === 'overview');
+ const detail = spec.pages.find((p) => p.key === 'detail');
+ assert.deepStrictEqual([overview.pageId, overview.name, overview.model, overview.dataSources],
+ [OVERVIEW_ID, 'Say "hi"', 'gpt-4.1', ['contoso_item', 'account']]);
+ assert.deepStrictEqual([detail.pageId, detail.name, detail.model, detail.dataSources],
+ [DETAIL_ID, 'Item Detail', undefined, ['contoso_item']]);
+ assert.deepStrictEqual(overview.navigatesTo, [{ targetKey: 'detail' }]);
+ assert.deepStrictEqual(spec.appShell.areas[0].groups[0].subAreas.slice(0, 2),
+ [{ page: 'overview', title: 'Overview navigation' }, { page: 'detail', title: 'Detail navigation' }]);
+ const canonicalPath = path.join(appDir, overview.source.codeFile);
+ assert.strictEqual(fs.readFileSync(canonicalPath, 'utf8'), canonical);
+ const modelWarnings = warnings.filter((w) => /page model id\(s\).*left out/.test(w));
+ assert.strictEqual(modelWarnings.length, round === 0 && secondModel ? 1 : 0, warnings.join(''));
+ if (modelWarnings.length) {
+ assert.match(modelWarnings[0], /WARNING: 1 page model id\(s\) the App Spec cannot hold were left out, so a rebuild stores them empty/);
+ assert.ok(modelWarnings[0].includes(`${DETAIL_ID} ("has space")`), modelWarnings[0]);
+ }
+
+ const start = uploads.length;
+ const rebuilt = await runSdkBuild(spec, { sdk, genpageCli: cli, appDir, env: ENV, apply: true, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ assert.ok(rebuilt.ok);
+ assert.strictEqual(rebuilt.created.app, APP_ID);
+ assert.deepStrictEqual(rebuilt.created.pages, { overview: OVERVIEW_ID, detail: DETAIL_ID });
+ const updates = uploads.slice(start);
+ assert.strictEqual(updates.length, 2, 'exactly one update per page');
+ for (const [id, name, model, dataSources, content] of [
+ [OVERVIEW_ID, 'Say "hi"', 'gpt-4.1', 'contoso_item,account', deployed],
+ [DETAIL_ID, 'Item Detail', undefined, 'contoso_item', detailCode],
+ ]) {
+ const upload = updates.find((u) => u.args[u.args.indexOf('--page-id') + 1] === id);
+ assert.ok(upload, id);
+ const { args } = upload;
+ assert.strictEqual(args.filter((a) => a === '--name').length, 1);
+ assert.strictEqual(args[args.indexOf('--name') + 1], name);
+ assert.strictEqual(args[args.indexOf('--data-sources') + 1], dataSources);
+ assert.strictEqual(args.includes('--model'), model !== undefined);
+ if (model !== undefined) assert.strictEqual(args[args.indexOf('--model') + 1], model);
+ assert.strictEqual(upload.content, content);
+ for (const flag of ['--connectors', '--actions', '--add-to-sitemap']) assert.ok(!args.includes(flag), flag);
+ assert.ok(!fs.existsSync(path.dirname(args[args.indexOf('--prompt-file') + 1])), 'wrapper temp directory cleaned');
+ }
+ assert.strictEqual(fs.readFileSync(canonicalPath, 'utf8'), canonical, 'rebuild never writes resolved IDs into canonical source');
+ const staging = path.join(appDir, '.maker-workspace', '.pageref-deploy');
+ assert.ok(!fs.existsSync(staging) || fs.readdirSync(staging).length === 0, 'deployment staging cleaned');
+ }
+ assert.strictEqual(calls.filter((args) => args[2] === 'upload').length, 4);
+ assert.ok(!sdkCalls.some(([name]) => name === 'createTable'), 'downloaded existing tables are reused');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/pageref-resolver.test.js b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
index f2c3c9783..287c7a373 100644
--- a/plugins/model-apps/scripts/tests/pageref-resolver.test.js
+++ b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
@@ -446,3 +446,113 @@ test('DECOY end-to-end: declared "detail" but the real nav points at "wrong" —
const code = `const decoy = "PAGEREF_detail";\n${NAV('"PAGEREF_wrong"')}`;
assert.deepStrictEqual(navTargetParity(['detail'], navReferencedKeys(code)), { declaredNotReferenced: ['detail'], referencedNotDeclared: ['wrong'] });
});
+
+test('extractNavTargets respects JavaScript identifier boundaries and optional-call syntax', () => {
+ const negatives = [
+ 'notnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ '$navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'αnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ '_navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'navigateTox({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'x\\u0041navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'x\\u{41}navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'x\u200CnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'x\u200DnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ ];
+ for (const code of negatives) assert.deepStrictEqual(navReferencedKeys(code), [], code);
+
+ const positives = [
+ 'navigateTo?.({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'navigateTo /* comment */ ?. /* comment */ ({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'Xrm?.Navigation?.navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})',
+ 'navigate\\u0054o({pageType:"generative",pageId:"PAGEREF_detail"})',
+ ];
+ for (const code of positives) assert.deepStrictEqual(navReferencedKeys(code), ['detail'], code);
+});
+
+test('extractNavTargets follows object-literal last-write wins for runtime pageId and pageType overrides', () => {
+ const dynamicPageId = [
+ 'pageId(){return "runtime";}',
+ 'get pageId(){return "runtime";}',
+ 'set pageId(v){}',
+ 'async pageId(){return "runtime";}',
+ '*pageId(){yield "runtime";}',
+ 'async *pageId(){yield "runtime";}',
+ '"pageId"(){return "runtime";}',
+ "get 'pageId'(){return 'runtime';}",
+ 'pageId',
+ 'page\\u0049d(){return "runtime";}',
+ ];
+ for (const override of dynamicPageId) {
+ const code = `const pageId = "runtime"; navigateTo({pageType:"generative",pageId:"PAGEREF_detail",${override}})`;
+ const [target] = extractNavTargets(code);
+ assert.strictEqual(target && target.kind, 'dynamic', override);
+ }
+
+ const dynamicPageType = [
+ 'pageType(){return "entityrecord";}',
+ 'get pageType(){return "entityrecord";}',
+ 'set pageType(v){}',
+ 'async pageType(){return "entityrecord";}',
+ '*pageType(){yield "entityrecord";}',
+ 'async *pageType(){yield "entityrecord";}',
+ '"pageType"(){return "entityrecord";}',
+ "get 'pageType'(){return 'entityrecord';}",
+ 'pageType',
+ 'page\\u0054ype(){return "entityrecord";}',
+ ];
+ for (const override of dynamicPageType) {
+ const code = `const pageType = "entityrecord"; navigateTo({pageType:"generative",pageId:"PAGEREF_detail",${override}})`;
+ const [target] = extractNavTargets(code);
+ assert.strictEqual(target && target.kind, 'dynamic', override);
+ }
+
+ assert.deepStrictEqual(navReferencedKeys('navigateTo({pageType:"generative",pageId(){return "runtime";},pageId:"PAGEREF_detail"})'), ['detail']);
+ assert.deepStrictEqual(navReferencedKeys('navigateTo({pageType(){return "entityrecord";},pageType:"generative",pageId:"PAGEREF_detail"})'), ['detail']);
+ assert.deepStrictEqual(navReferencedKeys('navigateTo({pageType:"generative",data:{pageId(){return "nested";}},pageId:"PAGEREF_detail"})'), ['detail']);
+});
+
+test('resolvePageRefs changes only real navigation pageId spans', () => {
+ const code = [
+ 'notnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"});',
+ '$navigateTo({pageType:"generative",pageId:"PAGEREF_detail"});',
+ 'Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"PAGEREF_detail"});',
+ ].join('\n');
+ const { deployment, unresolved } = resolvePageRefs(new Map([['overview', { code }]]), new Map([['detail', 'gp-detail']]));
+ assert.deepStrictEqual(unresolved, []);
+ assert.strictEqual(deployment.get('overview'), code.replace('Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"PAGEREF_detail"});', 'Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"gp-detail"});'));
+});
+
+test('extractNavTargets treats modifier-computed keys as runtime overrides', () => {
+ const cases = [
+ 'get ["pageId"](){return "runtime";}',
+ 'set [k](v){}',
+ 'async [k](){return "runtime";}',
+ '*[k](){yield "runtime";}',
+ 'async *[k](){yield "runtime";}',
+ ];
+ for (const override of cases) {
+ const code = `const k = "pageId"; navigateTo({pageType:"generative",pageId:"PAGEREF_a",${override}})`;
+ assert.strictEqual(extractNavTargets(code)[0].kind, 'dynamic', override);
+ }
+});
+
+test('extractNavTargets keeps astral and private identifiers out of navigateTo matches', () => {
+ assert.deepStrictEqual(navReferencedKeys('𝑥navigateTo({pageType:"generative",pageId:"PAGEREF_a"})'), []);
+ assert.deepStrictEqual(navReferencedKeys('this.#navigateTo({pageType:"generative",pageId:"PAGEREF_a"})'), []);
+});
+
+test('quoted property names decode escapes without executing source text', () => {
+ assert.deepStrictEqual(navReferencedKeys('navigateTo({pageType:"generative",page\\u0049d:"PAGEREF_a"})'), ['a']);
+ assert.deepStrictEqual(navReferencedKeys('navigateTo({pageType:"generative",\'pageI\\x64\':"PAGEREF_b"})'), ['b']);
+});
+
+test('lexer and resolver source do not evaluate page source while scanning', () => {
+ const fs = require('node:fs');
+ const resolver = fs.readFileSync(path.join(__dirname, '..', 'lib', 'pageref-resolver.js'), 'utf8');
+ const lexer = fs.readFileSync(path.join(__dirname, '..', 'lib', 'source-literals.js'), 'utf8');
+ for (const [file, text] of [['pageref-resolver.js', resolver], ['source-literals.js', lexer]]) {
+ assert.doesNotMatch(text, /\bFunction\s*\(|\beval\s*\(|new\s+Function\b|\bvm\./, file);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/provision-entities.test.js b/plugins/model-apps/scripts/tests/provision-entities.test.js
index 791030880..2b0cf9777 100644
--- a/plugins/model-apps/scripts/tests/provision-entities.test.js
+++ b/plugins/model-apps/scripts/tests/provision-entities.test.js
@@ -1,8 +1,13 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
const path = require('node:path');
+const vm = require('node:vm');
const { provisionEntities } = require(path.join(__dirname, '..', 'provision-entities.js'));
+const { loadCli } = require('./helpers/cli-harness.js');
+const { validateFlagsFromParsed, realAuth } = require('./helpers/fake-auth.js');
const input = { solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
entities: [{ schemaName: 'cr_candidate', displayName: 'Candidate', pluralName: 'Candidates', primaryAttribute: { schemaName: 'cr_name' },
@@ -227,3 +232,225 @@ test('provision-entities surfaces a language fallback through deps.warn', async
'the fallback must reach deps.warn; got: ' + JSON.stringify(warnings)
);
});
+
+// makeSdk/main are otherwise never called: the tests above inject mockDeps into provisionEntities().
+// emitResult() ends the process, so a cleanup that runs in a finally the printer never returns to
+// leaks both throwaway workspaces. The stub throws where the real printer exits, and only after both
+// directories are gone. validateFlagsFromParsed cannot see an unknown flag (parseArgs drops it), so
+// the real checker runs first; the rebuilt-argv check still guards the success-path `known` list.
+const PROVISION_SCRIPT = path.join(__dirname, '..', 'provision-entities.js');
+const PROVISION_ENV = 'https://contoso.crm.dynamics.com';
+
+function cliProvisionInput() {
+ return {
+ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
+ entities: [{
+ schemaName: 'cr_candidate',
+ displayName: 'Candidate',
+ pluralName: 'Candidates',
+ primaryAttribute: { schemaName: 'cr_name' },
+ columns: [{ schemaName: 'cr_status', type: 'Choice', options: ['Applied', 'Hired'] }],
+ }],
+ relationships: [],
+ sampleData: { cr_candidate: [{ cr_name: 'Ada' }, { cr_name: 'Grace' }] },
+ };
+}
+
+function provisionHarness({ initThrows = null, constructThrows = null, provisioned = [1033, 3082, 1036], onEmit = null } = {}) {
+ const d = mockDeps();
+ const seen = { envs: [], http: [], cols: [], order: [], removed: [], storages: [], solution: undefined, emitted: null };
+ d.sdk.seedRecordGraph = async () => ({ createdIds: { cr_candidate: ['rec-0', 'rec-1'] } });
+ d.sdk.createColumn = async (_logical, column) => {
+ d.calls.push('createColumn');
+ seen.cols.push(column);
+ return { logicalName: column.schemaName.toLowerCase(), metadataId: `col-${column.schemaName}` };
+ };
+ d.provision.queryRecords = async (set) => (set === 'organization' ? [{ languagecode: 1033 }] : [{ solutionid: 's' }]);
+ const requires = {
+ 'node:fs': {
+ mkdtempSync: (prefix) => {
+ const dir = prefix + String(seen.storages.length);
+ seen.storages.push(dir);
+ seen.order.push('mkdtemp');
+ return dir;
+ },
+ rmSync: (dir, opts) => {
+ seen.order.push('rm');
+ seen.removed.push({ dir, opts });
+ },
+ },
+ './lib/sdk-http-client.js': {
+ createAzHttpClient: (env) => {
+ seen.http.push(env);
+ return { env };
+ },
+ },
+ './vendor/cds-maker-sdk.cjs': {
+ createNodeWorkspaceStorage: (root) => ({ root }),
+ createMakerSdk: (opts) => {
+ seen.envs.push(opts.instanceUrl);
+ if (opts.solutionUniqueName) seen.solution = opts.solutionUniqueName;
+ if (constructThrows) throw new Error(constructThrows);
+ const base = opts.solutionUniqueName ? d.sdk : d.provision;
+ return Object.assign({}, base, {
+ initWorkspace: async () => { if (initThrows) throw new Error(initThrows); },
+ });
+ },
+ },
+ './lib/dataverse-auth.js': {
+ parseArgs: realAuth.parseArgs,
+ validateFlags: (passed, contract) => {
+ const direct = realAuth.validateFlags(passed, contract);
+ if (direct) return direct;
+ return validateFlagsFromParsed(() => realAuth.parseArgs(passed).flags)(passed, contract);
+ },
+ readAliasedFlag: realAuth.readAliasedFlag,
+ readJsonArg: realAuth.readJsonArg,
+ readProvisionedLanguages: async () => provisioned,
+ emitResult: (ok, payload) => {
+ seen.order.push('emit');
+ if (seen.removed.length < 2) throw new Error(`emit before workspace cleanup (removed ${seen.removed.length})`);
+ seen.emitted = { ok, payload };
+ if (onEmit) return onEmit(ok, payload);
+ const err = new Error(`process.exit(${ok ? 0 : 1})`);
+ err.exitCode = ok ? 0 : 1;
+ throw err;
+ },
+ },
+ };
+ return { d, seen, requires };
+}
+
+function assertCleanedBeforeEmit(seen) {
+ assert.deepStrictEqual(seen.removed.map((r) => r.dir), seen.storages, 'both workspaces makeSdk created are the ones removed');
+ assert.ok(seen.removed.every((r) => r.opts && r.opts.recursive === true && r.opts.force === true));
+ const emitAt = seen.order.lastIndexOf('emit');
+ assert.ok(emitAt > 1, 'emit ran');
+ assert.ok(seen.order.slice(0, emitAt).filter((step) => step === 'rm').length >= 2, 'cleanup ran before the emitter exited: ' + seen.order.join(','));
+}
+
+test('CLI provisions the requested input and cleans its workspace before emit', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'provision-cli-'));
+ const inputFile = path.join(dir, 'input.json');
+ fs.writeFileSync(inputFile, JSON.stringify(cliProvisionInput()));
+ const inputArg = '@' + inputFile;
+
+ async function viaLoadCli(argv, opts) {
+ const h = provisionHarness(opts);
+ const cli = loadCli(PROVISION_SCRIPT, { argv, requires: h.requires });
+ let exitErr = null;
+ try { await cli.main(); } catch (err) { exitErr = err; }
+ return { ...h, exitErr, stderr: cli.stderrText(), stdout: cli.stdoutText() };
+ }
+
+ // The entry `main().catch(emitResult)` only arms when the file is the process main. loadCli cannot
+ // set that, so thrown init/provision failures are driven through the same compile with require.main
+ // pointed at the module — otherwise a deleted catch would still look green.
+ function viaEntry(argv, opts) {
+ let finish;
+ const done = new Promise((resolve) => { finish = resolve; });
+ const h = provisionHarness({ ...opts, onEmit: () => finish() });
+ const source = fs.readFileSync(PROVISION_SCRIPT, 'utf8');
+ const mod = { exports: {} };
+ const stderr = [];
+ const customRequire = (id) => {
+ if (Object.prototype.hasOwnProperty.call(h.requires, id)) return h.requires[id];
+ const noExt = id.replace(/\.js$/, '');
+ if (Object.prototype.hasOwnProperty.call(h.requires, noExt)) return h.requires[noExt];
+ if (id.startsWith('.')) return require(path.resolve(path.dirname(PROVISION_SCRIPT), id));
+ return require(id);
+ };
+ customRequire.main = mod;
+ const sandboxProcess = {
+ argv: ['node', PROVISION_SCRIPT, ...argv],
+ env: {},
+ platform: process.platform,
+ execPath: process.execPath,
+ exit: (code) => { h.seen.exitCode = code; finish(); },
+ stdout: { write: () => true },
+ stderr: { write: (s) => { stderr.push(String(s)); return true; } },
+ };
+ const fn = vm.compileFunction(source, ['require', 'module', 'exports', 'process'], { filename: PROVISION_SCRIPT });
+ fn(customRequire, mod, mod.exports, sandboxProcess);
+ return done.then(() => ({ ...h, stderr: stderr.join('') }));
+ }
+
+ try {
+ const dry = await viaLoadCli(['--env', PROVISION_ENV, '--input', inputArg, '--sample-data']);
+ assert.strictEqual(dry.exitErr && dry.exitErr.exitCode, 0);
+ assert.strictEqual(dry.seen.emitted.ok, true);
+ assert.strictEqual(dry.seen.emitted.payload.dryRun, true);
+ assert.ok(dry.seen.emitted.payload.plan.includes('table cr_candidate'));
+ assert.ok(dry.seen.emitted.payload.plan.includes('2 record(s) -> cr_candidate'));
+ assert.deepStrictEqual(dry.d.calls, [], 'dry-run must not write');
+ assert.ok(dry.seen.envs.every((env) => env === PROVISION_ENV));
+ assert.deepStrictEqual(dry.seen.http, [PROVISION_ENV]);
+ assertCleanedBeforeEmit(dry.seen);
+
+ const applied = await viaLoadCli(['--env', PROVISION_ENV, '--input', inputArg, '--apply', '--sample-data', '--language-code', '3082']);
+ assert.strictEqual(applied.exitErr && applied.exitErr.exitCode, 0, applied.stderr);
+ const body = applied.seen.emitted.payload;
+ assert.strictEqual(body.ok, true);
+ assert.strictEqual(body.entities[0].logicalName, 'cr_candidate');
+ assert.strictEqual(body.entities[0].entitySetName, 'cr_candidates');
+ assert.strictEqual(body.entities[0].metadataId, 'tbl-cr_candidate');
+ assert.strictEqual(body.columns[0].logicalName, 'cr_status');
+ assert.strictEqual(body.columns[0].metadataId, 'col-cr_status');
+ assert.deepStrictEqual(body.records, { cr_candidate: ['rec-0', 'rec-1'] });
+ assert.strictEqual(applied.seen.cols[0].languageCode, 3082, '--language-code must reach the column create');
+ assert.strictEqual(applied.seen.solution, 'Default');
+ assert.ok(applied.d.calls.includes('createTable'));
+ assert.ok(applied.seen.envs.every((env) => env === PROVISION_ENV));
+ assertCleanedBeforeEmit(applied.seen);
+
+ const camel = await viaLoadCli(['--env', PROVISION_ENV, '--input', inputArg, '--apply', '--languageCode', '1036']);
+ assert.strictEqual(camel.exitErr && camel.exitErr.exitCode, 0, camel.stderr);
+ assert.strictEqual(camel.seen.cols[0].languageCode, 1036, '--languageCode is the same flag, not a dropped alias');
+
+ const badInput = path.join(dir, 'bad.json');
+ fs.writeFileSync(badInput, JSON.stringify({ solution: { uniqueName: 'Default' }, entities: [], relationships: [] }));
+ const refused = await viaLoadCli(['--env', PROVISION_ENV, '--input', '@' + badInput, '--apply']);
+ assert.strictEqual(refused.exitErr && refused.exitErr.exitCode, 1);
+ assert.strictEqual(refused.seen.emitted.ok, false);
+ assert.ok(refused.seen.emitted.payload.errors.some((e) => /publisherPrefix/i.test(e)));
+ assert.deepStrictEqual(refused.d.calls, [], 'a refused input must not write');
+ assertCleanedBeforeEmit(refused.seen);
+
+ const badLcid = await viaLoadCli(['--env', PROVISION_ENV, '--input', inputArg, '--language-code', '1O33']);
+ assert.strictEqual(badLcid.exitErr && badLcid.exitErr.exitCode, 1);
+ assert.match(badLcid.stderr, /--language-code \/ --languageCode must be digits only/);
+ assert.match(badLcid.stderr, /got '1O33'/);
+ assert.deepStrictEqual(badLcid.seen.storages, [], 'an invalid LCID exits before makeSdk');
+ assert.strictEqual(badLcid.seen.emitted, null);
+
+ const unknown = await viaLoadCli(['--env', PROVISION_ENV, '--bogus', 'x', '--input', inputArg]);
+ assert.strictEqual(unknown.exitErr && unknown.exitErr.exitCode, 1);
+ assert.match(unknown.stderr, /unknown flag\(s\): --bogus/);
+ assert.deepStrictEqual(unknown.seen.storages, []);
+ assert.deepStrictEqual(unknown.d.calls, []);
+
+ const initFailed = await viaEntry(['--env', PROVISION_ENV, '--input', inputArg, '--apply'], { initThrows: 'workspace init failed' });
+ assert.strictEqual(initFailed.seen.emitted.ok, false);
+ assert.match(initFailed.seen.emitted.payload.message, /workspace init failed/);
+ assert.deepStrictEqual(initFailed.d.calls, []);
+ assert.ok(initFailed.seen.envs.includes(PROVISION_ENV));
+ assertCleanedBeforeEmit(initFailed.seen);
+
+ const constructFailed = await viaEntry(['--env', PROVISION_ENV, '--input', inputArg, '--apply'], { constructThrows: 'bundle missing' });
+ assert.strictEqual(constructFailed.seen.emitted.ok, false);
+ assert.match(constructFailed.seen.emitted.payload.message, /bundle missing/);
+ assert.deepStrictEqual(constructFailed.d.calls, []);
+ assertCleanedBeforeEmit(constructFailed.seen);
+
+ const unprovisioned = await viaEntry(
+ ['--env', PROVISION_ENV, '--input', inputArg, '--apply', '--language-code', '3082'],
+ { provisioned: [1033] }
+ );
+ assert.strictEqual(unprovisioned.seen.emitted.ok, false);
+ assert.match(unprovisioned.seen.emitted.payload.message, /3082 is not provisioned/);
+ assert.ok(!unprovisioned.d.calls.includes('createTable'), 'an unprovisioned language must not write tables');
+ assertCleanedBeforeEmit(unprovisioned.seen);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/provision-input.test.js b/plugins/model-apps/scripts/tests/provision-input.test.js
index d0922388a..415c80c53 100644
--- a/plugins/model-apps/scripts/tests/provision-input.test.js
+++ b/plugins/model-apps/scripts/tests/provision-input.test.js
@@ -3,6 +3,7 @@ const { test } = require('node:test');
const assert = require('node:assert');
const path = require('node:path');
const { validateProvisionInput } = require(path.join(__dirname, '..', 'lib', 'provision-input.js'));
+const { provisionEntities } = require(path.join(__dirname, '..', 'provision-entities.js'));
test('accepts a minimal valid input', () => {
const r = validateProvisionInput({ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
@@ -199,3 +200,151 @@ test('sampleData rows get the same row-level gate as the app-builder path', () =
assert.deepStrictEqual(ok.errors.filter((e) => /sampleData\[/.test(e)), [],
'a valid row must not be rejected');
});
+
+// Guards below are the ones a subset test can delete without the happy-path cases noticing. Each
+// refusal must name the field and must not reach the SDK: provisionEntities writes the solution
+// before the data model, so a validator that fails open leaves a real solution behind.
+function refusingDeps() {
+ const calls = [];
+ const trap = new Proxy({}, {
+ get(_target, prop) {
+ if (prop === 'then') return undefined;
+ return async () => {
+ calls.push(String(prop));
+ throw new Error(`unexpected SDK ${String(prop)}`);
+ };
+ },
+ });
+ return { calls, sdk: trap, provision: trap };
+}
+
+function baseEntity(extra = {}) {
+ return Object.assign({
+ schemaName: 'cr_candidate',
+ displayName: 'Candidate',
+ pluralName: 'Candidates',
+ primaryAttribute: { schemaName: 'cr_name' },
+ columns: [],
+ }, extra);
+}
+
+function baseInput(extra = {}) {
+ return Object.assign({
+ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
+ entities: [baseEntity()],
+ relationships: [],
+ }, extra);
+}
+
+const twoEntities = [
+ baseEntity({ schemaName: 'cr_parent', displayName: 'Parent', pluralName: 'Parents' }),
+ baseEntity({ schemaName: 'cr_child', displayName: 'Child', pluralName: 'Children' }),
+];
+
+test('malformed provisioning inputs return errors before writes', async () => {
+ const cases = [
+ ['null input', null, /input is not an object/],
+ ['string input', 'not-an-object', /input is not an object/],
+ ['solution null', baseInput({ solution: null }), /solution is required and must be an object/],
+ ['solution uniqueName blank', baseInput({ solution: { uniqueName: ' ', publisherPrefix: 'cr' } }), /solution\.uniqueName is required and must be a non-empty string/],
+ ['entities object', baseInput({ entities: {} }), /entities must be an array/],
+ ['null entity', baseInput({ entities: [null] }), /each entity must be an object/],
+ ['entity missing schemaName', baseInput({ entities: [{ displayName: 'Candidate' }] }), /entity\.schemaName is required and must be a string/],
+ ['primaryAttribute null', baseInput({ entities: [baseEntity({ primaryAttribute: null })] }), /primaryAttribute is required and must be an object/],
+ ['primaryAttribute missing schemaName', baseInput({ entities: [baseEntity({ primaryAttribute: { displayName: 'Name' } })] }), /primaryAttribute\.schemaName is required and must be a string/],
+ ['null column', baseInput({ entities: [baseEntity({ columns: [null] })] }), /each column must be an object/],
+ ['column missing schemaName', baseInput({ entities: [baseEntity({ columns: [{ type: 'Text' }] })] }), /column\.schemaName is required and must be a string/],
+ ['choice without options', baseInput({ entities: [baseEntity({ columns: [{ schemaName: 'cr_status', type: 'Choice' }] })] }), /needs options\[\] or a globalChoice reference/],
+ ['relationships null', baseInput({ relationships: null }), /relationships must be an array/],
+ ['null relationship', baseInput({ relationships: [null] }), /each relationship must be an object/],
+ ['1:N missing referenced', baseInput({ relationships: [{ type: 'OneToMany', referencing: 'cr_candidate', lookup: { schemaName: 'cr_parentid' } }] }), /OneToMany relationship: referenced entity is required/],
+ ['1:N unknown referenced', baseInput({ relationships: [{ type: 'OneToMany', referenced: 'cr_missing', referencing: 'cr_candidate', lookup: { schemaName: 'cr_parentid' } }] }), /referenced entity 'cr_missing' not found in entities\[\]/],
+ ['1:N missing referencing', baseInput({ relationships: [{ type: 'OneToMany', referenced: 'cr_candidate', lookup: { schemaName: 'cr_parentid' } }] }), /OneToMany relationship: referencing entity is required/],
+ ['1:N unknown referencing', baseInput({ relationships: [{ type: 'OneToMany', referenced: 'cr_candidate', referencing: 'cr_missing', lookup: { schemaName: 'cr_parentid' } }] }), /referencing entity 'cr_missing' not found in entities\[\]/],
+ ['1:N missing lookup', baseInput({ relationships: [{ type: 'OneToMany', referenced: 'cr_candidate', referencing: 'cr_candidate' }] }), /OneToMany relationship: lookup object is required/],
+ ['1:N lookup missing schemaName', baseInput({ relationships: [{ type: 'OneToMany', referenced: 'cr_candidate', referencing: 'cr_candidate', lookup: {} }] }), /OneToMany relationship: lookup\.schemaName is required/],
+ ['N:N missing entity1', baseInput({ entities: twoEntities, relationships: [{ type: 'ManyToMany', entity2: 'cr_child' }] }), /ManyToMany relationship: entity1 is required/],
+ ['N:N unknown entity1', baseInput({ entities: twoEntities, relationships: [{ type: 'ManyToMany', entity1: 'cr_missing', entity2: 'cr_child' }] }), /entity1 'cr_missing' not found in entities\[\]/],
+ ['N:N missing entity2', baseInput({ entities: twoEntities, relationships: [{ type: 'ManyToMany', entity1: 'cr_parent' }] }), /ManyToMany relationship: entity2 is required/],
+ ['N:N unknown entity2', baseInput({ entities: twoEntities, relationships: [{ type: 'ManyToMany', entity1: 'cr_parent', entity2: 'cr_missing' }] }), /entity2 'cr_missing' not found in entities\[\]/],
+ ['globalChoices not an array', baseInput({ globalChoices: {} }), /globalChoices must be an array when provided/],
+ ['null globalChoice', baseInput({ globalChoices: [null] }), /each globalChoice must be an object/],
+ ['globalChoice missing name', baseInput({ globalChoices: [{ options: ['Low'] }] }), /globalChoice\.name is required and must be a string/],
+ ['globalChoice empty options', baseInput({ globalChoices: [{ name: 'cr_priority', options: [] }] }), /options must be a non-empty array/],
+ ['sampleData array', baseInput({ sampleData: [] }), /sampleData must be an object keyed by entity schemaName when provided/],
+ ['unknown sample table', baseInput({ sampleData: { cr_missing: [] } }), /sampleData: entity key 'cr_missing' not found in entities\[\]/],
+ ['sample rows not an array', baseInput({ sampleData: { cr_candidate: { cr_name: 'Ada' } } }), /sampleData\['cr_candidate'\]: value must be an array of records/],
+ ];
+
+ for (const [label, input, pattern] of cases) {
+ const validated = validateProvisionInput(input);
+ assert.strictEqual(validated.ok, false, `${label} must be refused; got ${JSON.stringify(validated.errors)}`);
+ assert.ok(validated.errors.some((e) => pattern.test(e)), `${label}: expected ${pattern} in ${JSON.stringify(validated.errors)}`);
+
+ const deps = refusingDeps();
+ const applied = await provisionEntities(input, { apply: true, sampleData: true }, deps);
+ assert.strictEqual(applied.ok, false, `${label} must not apply`);
+ assert.ok(applied.errors.some((e) => pattern.test(e)), `${label}: apply path dropped the error ${pattern}`);
+ assert.deepStrictEqual(deps.calls, [], `${label} reached the SDK: ${deps.calls.join(',')}`);
+ }
+
+ // Object.keys is the inspection the unknown-key gate depends on. A throwing enumeration must be
+ // a returned error, not an exception that skips the rest of the gate and proceeds to createTable.
+ const explosive = new Proxy(baseEntity(), {
+ ownKeys() { throw new Error('keys exploded'); },
+ });
+ const exploded = baseInput({ entities: [explosive] });
+ const explodedCheck = validateProvisionInput(exploded);
+ assert.ok(
+ explodedCheck.errors.some((e) => e === "entity 'cr_candidate': could not be inspected — enumerating its keys threw"),
+ JSON.stringify(explodedCheck.errors)
+ );
+ const explodedDeps = refusingDeps();
+ const explodedApply = await provisionEntities(exploded, { apply: true }, explodedDeps);
+ assert.strictEqual(explodedApply.ok, false);
+ assert.deepStrictEqual(explodedDeps.calls, []);
+
+ // Valid control: the same shapes, filled in, are not refused — and a real apply does write, so the
+ // zero-call assertion above is not passing because the SDK double never records calls.
+ const valid = {
+ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
+ entities: [
+ baseEntity({
+ schemaName: 'cr_parent',
+ displayName: 'Parent',
+ pluralName: 'Parents',
+ columns: [{ schemaName: 'cr_priority', type: 'Choice', globalChoice: 'cr_priority' }],
+ }),
+ baseEntity({ schemaName: 'cr_child', displayName: 'Child', pluralName: 'Children' }),
+ ],
+ relationships: [
+ { type: 'OneToMany', schemaName: 'cr_parent_children', referenced: 'cr_parent', referencing: 'cr_child', lookup: { schemaName: 'cr_parentid' } },
+ { type: 'ManyToMany', schemaName: 'cr_parent_child_nn', entity1: 'cr_parent', entity2: 'cr_child' },
+ ],
+ globalChoices: [{ name: 'cr_priority', options: ['Low', 'High'] }],
+ sampleData: { cr_parent: [{ cr_name: 'Ada' }], cr_child: [] },
+ };
+ const accepted = validateProvisionInput(valid);
+ assert.deepStrictEqual(accepted.errors, [], 'a complete input must not be refused');
+ assert.strictEqual(accepted.ok, true);
+
+ const writes = [];
+ const sdk = {
+ queryRecords: async () => [{ solutionid: 's' }],
+ createTable: async (o) => { writes.push('createTable'); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: 'tbl' }; },
+ createColumn: async (l, o) => { writes.push('createColumn'); return { logicalName: o.schemaName.toLowerCase(), metadataId: 'col' }; },
+ createGlobalOptionSet: async () => ({ metadataId: 'g' }),
+ createRelationship: async (o) => ({ schemaName: o.schemaName, metadataId: 'rel' }),
+ createRecordsBulk: async () => [],
+ seedRecordGraph: async () => ({ createdIds: {} }),
+ };
+ const provision = {
+ findTables: async () => [],
+ findColumns: async () => [],
+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),
+ queryRecords: async () => [{ solutionid: 's', languagecode: 1033 }],
+ };
+ const applied = await provisionEntities(baseInput(), { apply: true }, { sdk, provision });
+ assert.strictEqual(applied.ok, true, JSON.stringify(applied.errors || applied));
+ assert.ok(writes.includes('createTable'), 'the valid control must be able to observe an SDK write');
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
index 548f2053b..d2915ddc0 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
@@ -520,3 +520,116 @@ test('deploy: pages that omit prompt/agentMessage entirely still deploy', async
assert.ok(genpageCli.uploads.length > 0, 'an omitted key is not an authoring mistake');
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+
+test('lexical navigation variants survive deploy-download-rebuild', async () => {
+ const { runDownload } = require('../download-model-app.js');
+ const { appDir, spec } = makeTwoPageApp();
+ const overviewId = 'aaaaaaaa-0000-4000-8000-000000000001';
+ const detailId = 'bbbbbbbb-0000-4000-8000-000000000002';
+ const live = [{ pageId: overviewId, name: 'Overview' }, { pageId: detailId, name: 'Detail' }];
+ // Build the expected bytes independently; decoy IDs and PAGEREFs outside navigation must stay put.
+ const source = (target) => [
+ 'export default function Overview() {',
+ ` const decoy = "${detailId}"; const token = "PAGEREF_detail";`,
+ ' const separators = "left\u2028middle\u2029right";',
+ ` // navigateTo({pageType:"generative",pageId:"${detailId}"})\u2028 Xrm.Navigation.navigateTo?.({pageType:"generative",/* keep pageId */pageId:"${target}",data:{}});`,
+ ` // another inert pageId\u2029 Xrm.Navigation.navigateTo?.({pageType:"generative",pageId:"${target}"});`,
+ String.raw` Xrm?.Navigation?.navigateTo({"page\u0054ype":"generative","page\u{49}d":"` + target + '"});',
+ ` Xrm.Navigation.navigateTo({pageType:"generative",pageId:"${target}",// pageId stays\u2029data:{}});`,
+ String.raw` Xrm.Navigation.navigate\u0054o?.({"pageType":"generative",'page\x49d':"` + target + '"});',
+ ` Xrm.Navigation.navigateTo?.({pageType(){return "entityrecord";},pageType:"generative",get pageId(){return "runtime";},pageId:"${target}"});`,
+ ' return null;',
+ '}',
+ '',
+ ].join('\r\n');
+ const canonical = source('PAGEREF_detail');
+ const resolved = source(detailId);
+ try {
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), canonical, 'utf8');
+ spec.pages[0].pageId = overviewId;
+ spec.pages[1].pageId = detailId;
+ const xml = `<SiteMap><Area><Group><SubArea GenPageId="${overviewId}" Title="Overview"/><SubArea GenPageId="${detailId}" Title="Detail"/></Group></Area></SiteMap>`;
+ const { sdk, calls } = mockSdk({ liveSitemapXml: xml });
+ const genpageCli = mockGenpageCli(live);
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://contoso.crm.dynamics.com', appDir, genpageCli, phases: PHASES });
+ assert.strictEqual(genpageCli.uploads.length, 2);
+ assert.strictEqual(genpageCli.uploads.find((u) => u.requestedId === overviewId).content, resolved);
+ assert.strictEqual(fs.readFileSync(path.join(appDir, 'overview.tsx'), 'utf8'), canonical);
+ const writes = calls.filter((c) => (c.name === 'createWebResource' && /_pagemanifest$/.test(c.args[0].name)) || c.name === 'updateWebResource');
+ const last = writes[writes.length - 1];
+ const manifest = last.name === 'updateWebResource' ? last.args[1].content : last.args[0].content;
+ const manifestB64 = Buffer.from(manifest, 'utf8').toString('base64');
+ const downloadDir = path.join(appDir, 'download');
+ fs.mkdirSync(downloadDir);
+ const downloadSdk = {
+ fetchArtifact: async () => ({
+ name: spec.app.name, description: '',
+ siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Pages', subAreas: [
+ ...live.map((p) => ({ type: 'GenPage', genPageId: p.pageId, title: p.name })),
+ { type: 'Entity', entity: 'contoso_item' },
+ ] }] }] },
+ }),
+ queryRecords: async (logical) => {
+ if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, uniquename: 'contoso_deployapp' }];
+ if (logical === 'appmodulecomponent') return [{ objectid: SELF_SITEMAP_ID, componenttype: 62 }];
+ if (logical === 'sitemap') return [{ sitemapxml: xml }];
+ if (logical === 'webresource') return [{ content: manifestB64 }];
+ return [];
+ },
+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Item', primaryNameAttribute: 'contoso_name', attributes: [], relationships: [] }),
+ dataverse: { get: async () => ({ status: 200, body: { value: [] } }) },
+ };
+ genpageCli.download = async ({ outputDir, pageIds }) => {
+ assert.deepStrictEqual([...pageIds].sort(), [overviewId, detailId].sort());
+ for (const id of pageIds) {
+ const dir = path.join(outputDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'page.tsx'), genpageCli.uploads.find((u) => u.requestedId === id).content, 'utf8');
+ fs.writeFileSync(path.join(dir, 'config.json'), '\uFEFF{"dataSources":[]}', 'utf8');
+ }
+ return true;
+ };
+ const downloaded = await runDownload({ sdk: downloadSdk, genpageCli, outDir: downloadDir, appId: APP_ID, appUnique: 'contoso_deployapp' });
+ assert.ok(downloaded.ok, JSON.stringify(downloaded));
+ const overview = downloaded.spec.pages.find((p) => p.key === 'overview');
+ assert.deepStrictEqual(overview.navigatesTo, [{ targetKey: 'detail' }]);
+ assert.strictEqual(fs.readFileSync(path.join(downloadDir, overview.source.codeFile), 'utf8'), canonical, 'download reverses only effective navigation target spans');
+ const rebuiltCli = mockGenpageCli(live);
+ const { sdk: rebuiltSdk } = mockSdk({ liveSitemapXml: xml, pageManifest: manifestB64 });
+ await runSdkBuild(downloaded.spec, { sdk: rebuiltSdk, apply: true, env: 'https://contoso.crm.dynamics.com', appDir: downloadDir, genpageCli: rebuiltCli, phases: ['app-shell', 'pages'] });
+ assert.strictEqual(rebuiltCli.uploads.length, 2);
+ assert.ok(rebuiltCli.uploads.every((u) => u.requestedId), 'the rebuild performs only updates');
+ assert.strictEqual(rebuiltCli.uploads.find((u) => u.requestedId === overviewId).content, resolved);
+ assert.strictEqual(fs.readFileSync(path.join(downloadDir, overview.source.codeFile), 'utf8'), canonical);
+ for (const dir of [appDir, downloadDir]) {
+ const staging = path.join(dir, '.maker-workspace', '.pageref-deploy');
+ assert.ok(!fs.existsSync(staging) || fs.readdirSync(staging).length === 0, 'run-scoped staging cleaned');
+ }
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('lexical navigation overrides halt before any upload', async () => {
+ for (const override of [
+ 'pageId(){return "runtime";}',
+ 'get pageId(){return "runtime";}',
+ 'set pageId(value){}',
+ 'pageId',
+ '["page" + "Id"]:"runtime"',
+ '...{pageId:"runtime"}',
+ ]) {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ spec.pages[0].navigatesTo = [];
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'),
+ `export default function Overview(){ const pageId = "runtime"; Xrm.Navigation.navigateTo?.({pageType:"generative",/* pageId */pageId:"PAGEREF_detail",${override}}); return null; }`, 'utf8');
+ const { sdk } = mockSdk();
+ const genpageCli = mockGenpageCli();
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://contoso.crm.dynamics.com', appDir, genpageCli, phases: PHASES }),
+ (e) => e && e.phase === 'pages' && e.code === 'pages-nav-parity' && /non-symbolic navigation target/.test(e.message),
+ override
+ );
+ assert.strictEqual(genpageCli.uploads.length, 0, `${override}: rejected before target pre-minting or source upload`);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js b/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js
new file mode 100644
index 000000000..7901cb173
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js
@@ -0,0 +1,273 @@
+'use strict';
+// The batched publish opt-in (SDK `publishArtifacts` + `enrichDefaultViews(…, { publish: false })`).
+//
+// The SDK measured a PublishXml at ~2-2.5 s even with nothing pending, with parallel ones queueing
+// on the server, and the build published every enriched table twice. With `--publish` the build
+// now defers the default-view enrichment's publish to its final phase and sends that phase as ONE
+// envelope. These tests pin the contract: what goes in the envelope, what happens when the envelope
+// fails or is refused, that a deferred enrichment's saves are never left unpublished, and that
+// nothing changes without `--publish` or with an SDK that has no `publishArtifacts`. A build that
+// halts before its publish phase hands what it still owes to its caller, which publishes it once no
+// retry follows (settleOwedPublishes; the CLI side is pinned in build-model-app.test.js).
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, BuildHalt } = require('../lib/sdk-build.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+
+// Two tables: Project (with a form, so phase 8 already names it) and Task (no form, view or chart,
+// so only its enriched default views can put it in the envelope).
+function spec() {
+ return {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoBatch', displayName: 'Contoso Batch', publisherPrefix: 'cnt' },
+ app: { name: 'Batch App' },
+ entities: [
+ { schemaName: 'cnt_project', displayName: 'Project', pluralName: 'Projects', primaryAttribute: { schemaName: 'cnt_name', displayName: 'Name' },
+ columns: [{ schemaName: 'cnt_code', displayName: 'Code', type: 'Text' }, { schemaName: 'cnt_budget', displayName: 'Budget', type: 'Decimal' }] },
+ { schemaName: 'cnt_task', displayName: 'Task', pluralName: 'Tasks', primaryAttribute: { schemaName: 'cnt_name', displayName: 'Name' },
+ columns: [{ schemaName: 'cnt_due', displayName: 'Due', type: 'DateTime' }, { schemaName: 'cnt_hours', displayName: 'Hours', type: 'Integer' }] },
+ ],
+ forms: [{ entity: 'cnt_project', name: 'Project', formType: 'Main' }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Items', subAreas: [{ entity: 'cnt_project' }, { entity: 'cnt_task' }] }] }] },
+ };
+}
+
+// The simple mock, recording publishes, with the new SDK surface: a deferred enrichment returns the
+// publish it owes, and `publishArtifacts` answers one result per input.
+function batchSdk({ envelope = (targets) => targets.map(({ type, id }) => ({ type, id, shipped: true, publish: { kind: 'verified' } })), withBatch = true } = {}) {
+ const { sdk, calls } = makeSimpleMockSdk();
+ // The simple mock answers every query with a publisher row, which the form lookup would read as an
+ // existing (id-less) form; a fresh org has none of this spec's forms.
+ const query = sdk.queryRecords;
+ sdk.queryRecords = async (entity, ...rest) => (entity === 'systemform' ? [] : query(entity, ...rest));
+ sdk.enrichDefaultViews = async (logical, cols, opts = {}) => {
+ calls.push(['enrichDefaultViews', logical, opts]);
+ const updated = [`defview-${logical}`];
+ if (opts.publish !== false) return { updated };
+ return { updated, results: [], pendingPublish: [{ scope: { envelope: 'entity', entityLogicalName: logical }, artifacts: [{ type: 'view', id: `defview-${logical}` }] }] };
+ };
+ sdk.publishArtifact = async (type, id) => { calls.push(['publishArtifact', type, id]); return { type, id, shipped: true, publish: { kind: 'verified' } }; };
+ if (withBatch) sdk.publishArtifacts = async (targets) => { calls.push(['publishArtifacts', targets]); return envelope(targets); };
+ return { sdk, calls };
+}
+
+const named = (calls, name) => calls.filter((c) => c[0] === name);
+
+test('with --publish, the enrichment defers its publish and the final phase sends one envelope', async () => {
+ const { sdk, calls } = batchSdk();
+ const warnings = [];
+ await runSdkBuild(spec(), { sdk, apply: true, publish: true, warn: (w) => warnings.push(w) });
+ const enrich = named(calls, 'enrichDefaultViews');
+ assert.equal(enrich.length, 2, 'both tables are enriched');
+ for (const call of enrich) assert.equal(call[2].publish, false, `${call[1]}: the enrichment's publish is deferred`);
+ const batches = named(calls, 'publishArtifacts');
+ assert.equal(batches.length, 1, 'one envelope');
+ const targets = batches[0][1];
+ assert.deepEqual(targets.map((t) => t.type), ['form', 'view', 'app'], JSON.stringify(targets));
+ assert.equal(targets[1].id, 'defview-cnt_task', 'the table only its default views name is published through the view that owes it');
+ assert.equal(targets[2].type, 'app', 'the app rides last in the same envelope');
+ assert.equal(named(calls, 'publishArtifact').length, 0, 'no per-target publish when the envelope succeeds');
+ assert.deepEqual(warnings.filter((w) => /publish/i.test(w)), []);
+});
+
+test('without --publish nothing is deferred and nothing is published', async () => {
+ const { sdk, calls } = batchSdk();
+ await runSdkBuild(spec(), { sdk, apply: true, publish: false });
+ const enrich = named(calls, 'enrichDefaultViews');
+ assert.equal(enrich.length, 2);
+ for (const call of enrich) assert.notEqual(call[2].publish, false, 'the SDK publishes the enrichment itself');
+ assert.equal(named(calls, 'publishArtifacts').length, 0);
+ assert.equal(named(calls, 'publishArtifact').length, 0);
+});
+
+test('an SDK without publishArtifacts publishes per target, entities before the app', async () => {
+ const { sdk, calls } = batchSdk({ withBatch: false });
+ await runSdkBuild(spec(), { sdk, apply: true, publish: true });
+ const singles = named(calls, 'publishArtifact').map((c) => `${c[1]} ${c[2]}`);
+ assert.equal(singles.length, 3, singles.join(', '));
+ assert.ok(singles.includes('view defview-cnt_task'), 'the owed table is still published');
+ assert.match(singles[singles.length - 1], /^app /, 'the app goes last');
+});
+
+test('a failed envelope publishes each failed target again on its own', async () => {
+ const failing = (targets) => targets.map(({ type, id }, i) => (i === 0
+ ? { type, id, shipped: true, publish: { kind: 'verified' } }
+ : { type, id, shipped: false, publish: { kind: 'failed', error: new Error('envelope 400') } }));
+ const { sdk, calls } = batchSdk({ envelope: failing });
+ const warnings = [];
+ await runSdkBuild(spec(), { sdk, apply: true, publish: true, warn: (w) => warnings.push(w) });
+ const retried = named(calls, 'publishArtifact').map((c) => `${c[1]} ${c[2]}`);
+ assert.equal(retried.length, 2, retried.join(', '));
+ assert.ok(retried.includes('view defview-cnt_task'));
+ assert.ok(retried.some((r) => r.startsWith('app ')));
+ assert.deepEqual(warnings.filter((w) => /FAILED/.test(w)), [], 'the shared envelope error is not reported for targets that then published');
+});
+
+test('a refused envelope falls back to the per-target path unchanged', async () => {
+ const { sdk, calls } = batchSdk({ envelope: () => { throw new Error('ARTIFACT_NOT_FOUND: view/x not in workspace'); } });
+ await runSdkBuild(spec(), { sdk, apply: true, publish: true });
+ assert.equal(named(calls, 'publishArtifacts').length, 1);
+ const singles = named(calls, 'publishArtifact').map((c) => c[1]);
+ assert.deepEqual(singles, ['form', 'view', 'app']);
+});
+
+const failure = (promise) => promise.then(() => assert.fail('the build was expected to halt'), (e) => e);
+const owedView = (logical) => ['view', `defview-${logical}`];
+
+test('a deferred enrichment that fails part-way halts, and the halt carries every publish still owed', async () => {
+ const PARTIAL = Symbol.for('cds-maker-sdk.partialDefaultViewEnrichment');
+ const record = { updated: ['defview-cnt_task'], results: [], pendingPublish: [{ scope: { envelope: 'entity', entityLogicalName: 'cnt_task' }, artifacts: [{ type: 'view', id: 'defview-cnt_task' }] }] };
+ // The SDK attaches the record to the error it throws; it may be wrapped, so the cause chain is read.
+ const inner = Object.assign(new Error('second view push failed'), { [PARTIAL]: record });
+ assert.equal(partialEnrichment(inner), record);
+ assert.equal(partialEnrichment(new Error('outer', { cause: inner })), record);
+ assert.equal(partialEnrichment(new Error('no record')), undefined);
+ assert.equal(partialEnrichment(undefined), undefined);
+
+ const { sdk, calls } = batchSdk();
+ const enrich = sdk.enrichDefaultViews;
+ sdk.enrichDefaultViews = async (logical, cols, opts) => {
+ if (logical === 'cnt_task') { calls.push(['enrichDefaultViews', logical, opts]); throw new Error('wrapped', { cause: inner }); }
+ return enrich(logical, cols, opts);
+ };
+ const steps = [];
+ const halt = await failure(runSdkBuild(spec(), { sdk, apply: true, publish: true, emit: (e) => steps.push(e) }));
+ assert.ok(halt instanceof BuildHalt && halt.phase === 'views', String(halt));
+ assert.ok(steps.some((e) => e.status === 'error' && /enrich default views for cnt_task/.test(e.label || '')), 'the failed step is reported');
+ // The build itself publishes nothing on a halt: only its caller knows whether a retry follows.
+ assert.equal(named(calls, 'publishArtifacts').length + named(calls, 'publishArtifact').length, 0);
+ assert.deepEqual(halt.owedPublishes, [owedView('cnt_project'), owedView('cnt_task')], 'the table enriched before the failure, and what the failed call had saved');
+ assert.equal(Object.keys(halt).includes('owedPublishes'), false, 'it rides along, never into a serialized error');
+ assert.equal(halt.owedPaid, false, 'no publish phase ran');
+ assert.equal(Object.keys(halt).includes('owedPaid'), false);
+
+ const warnings = [];
+ await settleOwedPublishes(sdk, halt.owedPublishes, (w) => warnings.push(w));
+ const batches = named(calls, 'publishArtifacts');
+ assert.equal(batches.length, 1, 'one envelope');
+ assert.deepEqual(batches[0][1], [{ type: 'view', id: 'defview-cnt_project' }, { type: 'view', id: 'defview-cnt_task' }]);
+ assert.deepEqual(warnings, []);
+});
+
+test('a default-view push refused by value (a concurrent edit) fails the enrichment step; what was saved stays owed', async () => {
+ const { sdk, calls } = batchSdk();
+ const enrich = sdk.enrichDefaultViews;
+ sdk.enrichDefaultViews = async (logical, cols, opts) => {
+ if (logical !== 'cnt_task') return enrich(logical, cols, opts);
+ calls.push(['enrichDefaultViews', logical, opts]);
+ // The SDK RESOLVES a 412 as saved:false; the table's other default view saved.
+ return {
+ updated: ['defview-cnt_task-active'],
+ results: [
+ { type: 'view', id: 'defview-cnt_task-active', saved: true, shipped: false, publish: { kind: 'notRequested' } },
+ { type: 'view', id: 'defview-cnt_task-inactive', saved: false, shipped: false, publish: { kind: 'notRequested' }, error: Object.assign(new Error('Version conflict for view/defview-cnt_task-inactive'), { code: 'VERSION_CONFLICT' }) },
+ ],
+ pendingPublish: [{ scope: { envelope: 'entity', entityLogicalName: 'cnt_task' }, artifacts: [{ type: 'view', id: 'defview-cnt_task-active' }] }],
+ };
+ };
+ const halt = await failure(runSdkBuild(spec(), { sdk, apply: true, publish: true }));
+ assert.ok(halt instanceof BuildHalt && halt.phase === 'views' && halt.code === 'version-conflict', `${halt.code}: ${halt.message}`);
+ assert.match(halt.message, /default view defview-cnt_task-inactive of cnt_task/);
+ assert.deepEqual(halt.owedPublishes, [owedView('cnt_project'), ['view', 'defview-cnt_task-active']], 'the saved view still owes its publish');
+ assert.equal(halt.owedPaid, false);
+ assert.equal(named(calls, 'publishArtifacts').length + named(calls, 'publishArtifact').length, 0);
+});
+
+test('a later phase that halts hands every enriched table to the caller: nothing it saved is lost', async () => {
+ // Before the publish was batched, each table's enrichment published itself, so a build stopped by
+ // a later phase left those tables live.
+ const { sdk, calls } = batchSdk();
+ const create = sdk.createArtifact;
+ sdk.createArtifact = (type, def) => { if (type === 'app') throw new Error('app create refused'); return create(type, def); };
+ const halt = await failure(runSdkBuild(spec(), { sdk, apply: true, publish: true }));
+ assert.ok(halt instanceof BuildHalt && halt.phase === 'app-shell', String(halt));
+ assert.equal(named(calls, 'publishArtifacts').length + named(calls, 'publishArtifact').length, 0);
+ assert.deepEqual(halt.owedPublishes, [owedView('cnt_project'), owedView('cnt_task')]);
+ assert.equal(halt.owedPaid, false);
+ await settleOwedPublishes(sdk, halt.owedPublishes, () => {});
+ assert.deepEqual(named(calls, 'publishArtifacts').map((c) => c[1].map((t) => t.id)), [['defview-cnt_project', 'defview-cnt_task']]);
+});
+
+test('a halt inside the publish phase still owes; once that phase has run, a later halt owes nothing', async () => {
+ // Inside: the envelope and every per-target publish throw, so the phase halts having paid nothing.
+ const inside = batchSdk({ envelope: () => { throw new Error('envelope refused'); } });
+ inside.sdk.publishArtifact = async () => { throw new Error('publish down'); };
+ const halted = await failure(runSdkBuild(spec(), { sdk: inside.sdk, apply: true, publish: true }));
+ assert.ok(halted instanceof BuildHalt && halted.phase === 'publish', String(halted));
+ assert.deepEqual(halted.owedPublishes, [owedView('cnt_project'), owedView('cnt_task')]);
+ assert.equal(halted.owedPaid, false, 'a publish phase that halts has paid nothing');
+
+ // After: the AI re-confirmation runs after the publish phase; an event it emits fails the build.
+ const after = batchSdk();
+ after.sdk.setAppAiFeatures = async () => ({ applied: [], skipped: [], notPersisted: ['formFill'], unverified: [], failed: [], outcomes: [] });
+ let published = false;
+ const emit = (e) => {
+ if (e.phase === 'publish' && e.status === 'ok') published = true;
+ if (published && e.phase === 'ai-features') throw new Error('late failure');
+ };
+ const late = await failure(runSdkBuild({ ...spec(), ai: { appFeatures: { formFill: true } } }, { sdk: after.sdk, apply: true, publish: true, emit }));
+ assert.match(String(late && late.message), /late failure/);
+ assert.equal(named(after.calls, 'publishArtifacts').length, 1, 'the publish phase ran and paid');
+ assert.deepEqual(late.owedPublishes, [], 'nothing more is owed');
+ // …and the CLI reads `owedPaid` as "an earlier attempt's debt is paid too": every attempt enriches the
+ // same tables, and this one's publish phase published them.
+ assert.equal(late.owedPaid, true);
+});
+
+test('settleOwedPublishes: nothing owed is a no-op, and one target that cannot be published keeps no other back', async () => {
+ const calls = [];
+ // A's publish throws, B's succeeds.
+ const publishOne = async (type, id) => {
+ calls.push(`publishArtifact ${id}`);
+ if (id === 'defview-a') throw new Error('publish down');
+ return { type, id, shipped: true, publish: { kind: 'verified' } };
+ };
+ const refused = { publishArtifacts: async () => { calls.push('publishArtifacts'); throw new Error('envelope refused'); }, publishArtifact: publishOne };
+ for (const nothing of [[], undefined, null, [['view']], 'defview-a']) await settleOwedPublishes(refused, nothing, () => assert.fail('no warning'));
+ await settleOwedPublishes(null, [owedView('a')], () => assert.fail('no warning'));
+ assert.deepEqual(calls, []);
+
+ // A refused envelope falls back to one publish per target; A throwing does not stop B.
+ const warnings = [];
+ await settleOwedPublishes(refused, [owedView('a'), owedView('b')], (w) => warnings.push(w));
+ assert.deepEqual(calls, ['publishArtifacts', 'publishArtifact defview-a', 'publishArtifact defview-b']);
+ assert.equal(warnings.length, 1, warnings.join('\n'));
+ assert.match(warnings[0], /^the build stopped before its publish phase; publish view defview-a FAILED: publish down — the change is SAVED/);
+
+ // A failed envelope: each target is published again on its own, and again A throwing does not stop B.
+ calls.length = 0;
+ warnings.length = 0;
+ const failed = {
+ publishArtifacts: async (targets) => { calls.push('publishArtifacts'); return targets.map(({ type, id }) => ({ type, id, shipped: false, publish: { kind: 'failed', error: new Error('envelope 400') } })); },
+ publishArtifact: publishOne,
+ };
+ await settleOwedPublishes(failed, [owedView('a'), owedView('b')], (w) => warnings.push(w));
+ assert.deepEqual(calls, ['publishArtifacts', 'publishArtifact defview-a', 'publishArtifact defview-b']);
+ assert.equal(warnings.length, 1, warnings.join('\n'));
+
+ // Without a warn callback it still never throws.
+ await settleOwedPublishes(refused, [owedView('a')]);
+});
+
+test('publishTargets in the publish phase still halts on a thrown per-target publish, as it always did', async () => {
+ const provision = { publishArtifact: async () => { throw new Error('publish down'); } };
+ const runner = { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) };
+ await assert.rejects(publishTargets(provision, runner, 2, [['form', 'f1']], null, () => {}), /publish down/);
+});
+
+test('publishTargets: a single target and an empty list never use the envelope', async () => {
+ const calls = [];
+ const provision = {
+ publishArtifacts: async (t) => { calls.push(['publishArtifacts', t]); return []; },
+ publishArtifact: async (type, id) => { calls.push(['publishArtifact', type, id]); return { type, id, publish: { kind: 'verified' } }; },
+ };
+ const runner = { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) };
+ await publishTargets(provision, runner, 2, [['form', 'f1']], null, () => {});
+ assert.deepEqual(calls, [['publishArtifact', 'form', 'f1']]);
+ calls.length = 0;
+ await publishTargets(provision, runner, 2, [], null, () => {});
+ assert.deepEqual(calls, []);
+ // A result list of the wrong length is not trusted: every target is published on its own.
+ await publishTargets(provision, runner, 2, [['form', 'f1'], ['view', 'v1']], ['app', 'a1', 'app One'], () => {});
+ assert.deepEqual(calls.map((c) => c[0]), ['publishArtifacts', 'publishArtifact', 'publishArtifact', 'publishArtifact']);
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index 5d6ab2517..f98da74a9 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -774,10 +774,11 @@ test('#583 the deferred routing-description push refuses a copy holding an earli
assert.strictEqual(find(quiet.calls, 'listArtifacts').length, 0, 'without a routing description there is nothing to push');
});
-// #583: the SDK refuses a header write with a 412 while an earlier header change is unpublished, and the
-// generic remedy (re-download) cannot clear that. The explanation is keyed on a PROVEN draft only. The
-// error is shaped as the real bundle returns it: `detail` names the refused request (pinned in
-// app-ai-description-real-bundle.test.js), and the message carries it too.
+// #583: a 412 on the app push is a concurrent edit wherever it lands. With cds-maker-sdk 8930278f the header
+// write carries the appmodule's ROW token, so an unpublished header change no longer refuses it (pinned in
+// app-ai-description-real-bundle.test.js); only a never-published app's header is "publish first". The
+// error is shaped as the real bundle returns it: `detail` names the refused request, and the message
+// carries it too.
const conflictOn = (row) => {
const detail = `Version conflict (412) from https://contoso.crm.dynamics.com/api/data/v9.2/${row}`;
return { saved: false, shipped: false, publish: { kind: 'notRequested' }, error: Object.assign(new Error(`Version conflict for app/x: local=W/"2", server=(none). Re-fetch and reapply changes. ${detail}`), { code: 'VERSION_CONFLICT', detail }) };
@@ -797,34 +798,29 @@ const draftReader = (answer, seen = []) => ({ get: async (url) => {
} });
const routingSpec = () => makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } });
-test('#583 a 412 over an unpublished header change halts with the step that works', async () => {
- // The last case puts the PUBLISHED row first: the unpublished layer must be found wherever it is.
- for (const [deferred, value] of [[false, [{ componentstate: 1 }]], [true, [{ componentstate: 1 }]], [false, [{ componentstate: 0 }, { componentstate: 1 }]]]) {
- const spec = routingSpec();
- if (deferred) spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });
- const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });
- const seen = [];
- sdk.dataverse = draftReader({ status: 200, body: { value } }, seen);
- await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases }), (e) => {
- assert.strictEqual(e.code, 'app-header-unpublished', `${deferred ? 'deferred' : 'sitemap'} path, rows ${JSON.stringify(value)}: ${e.message}`);
- assert.match(e.message, /unpublished change to its name, description or routing description/);
- assert.match(e.message, /publish the app in Power Apps \(or discard the change\), then re-run the build\.$/);
- return true;
- });
- assert.strictEqual(seen.length, 1);
- assert.match(seen[0], /^\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)\?\$select=componentstate&\$filter=appmoduleid eq \S+$/);
- assert.strictEqual(appCalls(calls, 'publishArtifact').length, 0, 'nothing is published after the refused push');
- // The refused push left this run's edits in the workspace copy; it is reset so the re-run's plain
- // fetch is not refused with LOCAL_EDITS_WOULD_BE_LOST once the operator has published.
- const resets = appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true);
- assert.strictEqual(resets.length, 1, 'the workspace copy is reset');
- assert.ok(calls.indexOf(resets[0]) > calls.indexOf(appCalls(calls, 'pushArtifact')[0]), 'after the refused push');
+test('#583 a 412 on the appmodule row is a concurrent edit, over a pending draft too: the generic halt, and the copy is kept', async () => {
+ // Whatever the draft holds — pending (in either order), settled, nothing — none of it is read.
+ const drafts = [[{ componentstate: 1 }], [{ componentstate: 0 }, { componentstate: 1 }], [{ componentstate: 0 }], []];
+ for (const [what, deferred, phases] of [['app-shell', false, appShellPhases], ['app-shell, deferred', true, appShellPhases], ['finalizer', false, fullPhases]]) {
+ for (const value of drafts) {
+ const spec = routingSpec();
+ if (deferred) spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });
+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });
+ const seen = [];
+ sdk.dataverse = draftReader({ status: 200, body: { value } }, seen);
+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases, genpageCli: noPages }), (e) => {
+ assert.strictEqual(e.code, 'version-conflict', `${what}, rows ${JSON.stringify(value)}: ${e.message}`);
+ return true;
+ });
+ assert.strictEqual(seen.length, 0, `${what}: no draft read`);
+ assert.strictEqual(appCalls(calls, 'publishArtifact').length, 0, `${what}: nothing is published after the refused push`);
+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 0, `${what}: the copy is kept as the fence`);
+ }
}
});
test('#583 when the workspace copy cannot be reset, the halt names the workspace to delete', async () => {
- const { sdk } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412, failOverwriteFetch: true });
- sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });
+ const { sdk } = mockSdk({ artifactsExist: true, appPushThrows: 'APP_DRAFT_HEADER_NOT_WRITABLE', failOverwriteFetch: true });
await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'app-header-unpublished', e.message);
assert.match(e.message, /then re-run the build\. First reset the workspace, which still holds this run's unpushed copy of the app \(a re-run would refuse to overwrite it\): stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json and destructive-approval\.json\./);
@@ -832,22 +828,6 @@ test('#583 when the workspace copy cannot be reset, the halt names the workspace
});
});
-test('#583 any other 412 keeps the generic re-download halt', async () => {
- for (const [what, answer] of [
- ['a settled row', { status: 200, body: { value: [{ componentstate: 0 }] } }],
- ['no row', { status: 200, body: { value: [] } }],
- ['a non-2xx draft read, whatever its body', { status: 500, body: { value: [{ componentstate: 1 }] } }],
- ['a failed draft read', new Error('network down')],
- ]) {
- const { sdk } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });
- sdk.dataverse = draftReader(answer);
- await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
- assert.strictEqual(e.code, 'version-conflict', `${what}: ${e.message}`);
- return true;
- });
- }
-});
-
test('#583 a push refused for another reason keeps its own halt, even over a pending draft', async () => {
const refused = { ...HEADER_412, error: Object.assign(new Error('a row already exists at that id'), { code: 'ARTIFACT_ALREADY_EXISTS' }) };
const { sdk } = mockSdk({ artifactsExist: true, appPushResult: refused });
@@ -859,10 +839,9 @@ test('#583 a push refused for another reason keeps its own halt, even over a pen
// The halt reads a push result the way requireSuccessfulPush does: `saved`, then the older SDK spelling
// `success`. Reading `saved` alone sent a legacy-shaped refusal to the generic conflict remedy.
-test('#583 the unpublished-header halt reads the older `success` result shape as well', async () => {
- const legacy = { success: false, error: HEADER_412.error };
+test('#583 the never-published halt reads the older `success` result shape as well', async () => {
+ const legacy = { success: false, error: Object.assign(new Error('The retrieval of version numbers failed.'), { code: 'APP_DRAFT_HEADER_NOT_WRITABLE' }) };
const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: legacy });
- sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });
await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'app-header-unpublished', e.message);
return true;
@@ -870,9 +849,9 @@ test('#583 the unpublished-header halt reads the older `success` result shape as
assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1, 'and resets the copy');
});
-// Only the APPMODULE row's 412 can be the unpublished-header state. A sitemap 412 is a concurrent sitemap
-// edit, over the unpublished layer this very push's header write just left — relabelling it reset the copy,
-// and "publish, then re-run" then overwrote the other edit. So is a conflict that names no request at all.
+// A sitemap 412 is a concurrent sitemap edit too, over the unpublished layer this very push's header write
+// just left — re-explaining it as "publish, then re-run" would reset the copy and then overwrite the other
+// edit. So is a conflict that names no request at all.
test('#583 a 412 that is not the appmodule row\u2019s keeps the generic halt and the copy, over a pending draft too', async () => {
const unnamed = { ...HEADER_412, error: Object.assign(new Error('Version conflict for app/x: local=W/"2", server=W/"3". Re-fetch and reapply changes.'), { code: 'VERSION_CONFLICT' }) };
for (const [what, result] of [['a sitemap 412', SITEMAP_412], ['a conflict naming no request', unnamed]]) {
@@ -911,17 +890,6 @@ test('#583 with the pages phase, the routing description rides the finalizer pus
assert.ok(at(pushes[0]) > at(appCalls(calls, 'updateElement', (c) => c.args[2] === '/siteMap')[0]), 'on the same push as the finalized sitemap');
});
-test('#583 the finalizer push halts precisely over an unpublished header change, after resetting the copy', async () => {
- const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });
- sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });
- await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: fullPhases, genpageCli: noPages }), (e) => {
- assert.strictEqual(e.code, 'app-header-unpublished', e.message);
- assert.match(e.message, /^pages failed: push app Support Desk failed: the app has an unpublished change/);
- return true;
- });
- assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1);
-});
-
// #583 review: a copy an earlier run left holding unpushed edits went out with the next push of the app, whatever
// that run asked for — a routing description the spec left out was overwritten with the earlier run's, and a
// wanted one read as already set. Every run that pushes the app refuses such a copy before it applies anything.
@@ -2158,6 +2126,61 @@ test('pages phase reuses an existing page by MANIFEST+EXISTENCE (not by name)
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+// pac stores whatever `--model` an upload sends, so an upload without one stored the page's model empty. The build sends
+// the spec's `pages[].model` on every upload — the create, and the in-place update of an existing page — and nothing
+// for a page without one.
+test('pages phase sends each page\'s model on create and on update, and none for a page without one', async () => {
+ const spec = makeSpec();
+ spec.schemaVersion = 2;
+ spec.pages = [
+ { key: 'overview', name: 'Overview', model: 'gpt-4.1', source: { kind: 'tsx', codeFile: 'o.tsx' } },
+ { key: 'detail', name: 'Detail', model: 'claude-3-5-sonnet@20240620', source: { kind: 'tsx', codeFile: 'd.tsx' } },
+ { key: 'about', name: 'About', source: { kind: 'tsx', codeFile: 'a.tsx' } },
+ ];
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'overview', title: 'Overview' }, { page: 'detail', title: 'Detail' }, { page: 'about', title: 'About' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ // overview exists (manifest + env + this app's sitemap) → an UPDATE; detail and about are new → CREATEs.
+ const REUSE = '9a1c2b3d-4e5f-4061-8072-0839455a6b7c';
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: REUSE }] }), 'utf8').toString('base64');
+ const sm = `<SiteMap><Area><Group><SubArea GenPageId="${REUSE}" Title="Overview"/></Group></Area></SiteMap>`;
+ const { sdk } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sm });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [REUSE], pages: [{ pageId: REUSE, name: 'Overview' }] }),
+ upload: async (o) => { uploads.push(o); return { pageId: o.pageId || `gp-${o.name.toLowerCase()}` }; } };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ const byName = Object.fromEntries(uploads.map((u) => [u.name, u]));
+ assert.deepStrictEqual([byName.Overview.pageId, byName.Overview.model], [REUSE, 'gpt-4.1'], 'the update sends the model');
+ assert.deepStrictEqual([byName.Detail.pageId, byName.Detail.model], [undefined, 'claude-3-5-sonnet@20240620'], 'the create sends it');
+ assert.strictEqual(byName.About.model, undefined, 'no model, nothing sent');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// A page another page navigates to is created FIRST when it does not exist yet ("pre-minted"), so the navigation can
+// carry its id. That create is an upload like any other and sends the model too.
+test('pages phase sends the model when it pre-mints a navigation target', async () => {
+ const spec = makeSpec();
+ spec.schemaVersion = 2;
+ spec.pages = [
+ { key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'o.tsx' }, navigatesTo: [{ targetKey: 'detail' }] },
+ { key: 'detail', name: 'Detail', model: 'gpt-4.1', source: { kind: 'tsx', codeFile: 'd.tsx' } },
+ ];
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'overview', title: 'Overview' }, { page: 'detail', title: 'Detail' });
+ const appDir = stagePages(spec.pages, {
+ 'o.tsx': 'export function go(){ Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" }); }\nexport default function P(){ return null; }',
+ });
+ try {
+ const { sdk } = mockSdk();
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }),
+ upload: async (o) => { uploads.push(o); return { pageId: o.pageId || (o.name === 'Detail' ? 'gp-detail' : 'gp-overview') }; } };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ const first = uploads[0];
+ assert.deepStrictEqual([first && first.name, first && first.pageId, first && first.model], ['Detail', undefined, 'gpt-4.1'], 'the pre-minted target is created first, with its model');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
test('defaultViewColumns: primary first (wide) + declared columns, capped at 7, skipping wide types', () => {
const entity = {
schemaName: 'new_ticket',
@@ -5108,6 +5131,31 @@ test('form topology: packing counts colspan, not cell count', async () => {
assert.strictEqual(rowAdds.length, 1, 'so the next field opens a new row');
});
+// A cell that spans rows keeps its column through the rows it covers. A full-width field ADDED after it cannot sit
+// in any of them, so it lands below the reservation — on a row reached through empty rows, which carry the span.
+test('form topology: a full-width field added below a row-spanning cell lands under the rows it reserves', async () => {
+ const spec = makeSpec();
+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [
+ { name: 'section_general', label: 'General', columns: 2, fields: ['new_name', { name: 'new_tier', colspan: 2 }] },
+ ] }]);
+ // A maker made new_name span three rows; the spec has no opinion on it, so it is kept.
+ const deployed = { id: 'f1', tabs: [{ id: 't0', name: 'tab_general', label: 'General', expanded: true, visible: true,
+ columns: [{ width: '100%', sections: [
+ { id: 's0', name: 'section_general', label: 'General', visible: true, showLabel: true, columns: 2,
+ rows: [{ cells: [{ rowspan: 3, control: { fieldName: 'new_name' } }] }] },
+ ] }] }], bag: { a: [], c: [] } };
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'] });
+
+ const sec = '/tabs/0/columns/0/sections/0';
+ const rowAdds = find(calls, 'addElement').filter((c) => String(c.args[2]) === sec + '/rows');
+ assert.deepStrictEqual(rowAdds.map((c) => c.args[3].cells.map((cell) => cell.control.fieldName)), [[], [], ['new_tier']],
+ 'two empty rows carry the span, and the field opens the row after them');
+ assert.deepStrictEqual(
+ find(calls, 'updateElement').filter((c) => String(c.args[2]) === sec + '/rows/0' && Array.isArray(c.args[3].cells)), [],
+ 'the spanning cell\'s row is not rewritten');
+});
+
// --- #581 item 2: a section the layout VACATED is reclaimed, not left as an empty twin ----------
//
// A generated section name encodes POSITION (`section_<tab>[_<column>]_<index>`), so moving a
@@ -5506,6 +5554,79 @@ test('form topology: a relocated field is clamped against its DESTINATION, not i
assert.strictEqual(moved.id, 'c1', 'the cell is moved, not recreated');
});
+// A span the spec does NOT declare stays the maker's — but a moved cell cannot keep a span wider than
+// the grid it lands in. The row used to be chosen for the compiled cell (no span: "no opinion"), the
+// existing colspan-2 cell was then moved into a ONE-column section, and it overflowed that section on
+// every apply (live, on two applies; verify's occupancy check failed it). The move now sizes the row
+// for the cell actually moving, clamps an undeclared too-wide colspan to the destination grid, and says so.
+const movedCellForm = (destColumns, destRows = []) => ({ id: 'f1', tabs: [{ id: 't0', name: 'tab_general', label: 'General', expanded: true, visible: true,
+ columns: [{ width: '100%', sections: [
+ { id: 's0', name: 'sec_src', label: 'Source', visible: true, showLabel: true, columns: 2,
+ rows: [{ cells: [{ id: 'c1', colspan: 2, control: { fieldName: 'new_name' } }] }, { cells: [{ id: 'c2', control: { fieldName: 'new_tier' } }] }] },
+ { id: 's1', name: 'sec_dest', label: 'Destination', visible: true, showLabel: true, columns: destColumns, rows: destRows },
+ ] }] }], bag: { a: [], c: [] } });
+const destinationOf = (form) => form.tabs[0].columns[0].sections[1];
+const movedCellOf = (form) => (destinationOf(form).rows || []).flatMap((r) => r.cells || []).find((c) => c.control && c.control.fieldName === 'new_name');
+async function buildMove(destColumns, nameEntry, destRows) {
+ const spec = makeSpec();
+ spec.forms = explicitForm([{ name: 'tab_general', label: 'General', sections: [
+ { name: 'sec_src', label: 'Source', columns: 2, fields: ['new_tier'] },
+ { name: 'sec_dest', label: 'Destination', columns: destColumns, fields: [nameEntry] },
+ ] }]);
+ spec.forms[0].prune = false;
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: movedCellForm(destColumns, destRows) });
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], warn: (m) => warnings.push(String(m)) });
+ const formCall = calls.find((c) => (c.name === 'updateElement' || c.name === 'addElement' || c.name === 'moveElement') && c.args[0] === 'form');
+ return { sdk, calls, warnings, form: await sdk.getArtifact('form', formCall.args[1]), spec };
+}
+
+test('form topology: a moved cell whose undeclared colspan is wider than its destination is narrowed to fit, and reported', async () => {
+ const { form, warnings } = await buildMove(1, 'new_name');
+ const moved = movedCellOf(form);
+ assert.ok(moved, `new_name lands in the destination; got ${JSON.stringify(destinationOf(form).rows)}`);
+ assert.strictEqual(moved.id, 'c1', 'the cell is moved, not recreated');
+ assert.strictEqual(moved.colspan, 1, 'a one-column section cannot hold a colspan-2 cell');
+ for (const row of destinationOf(form).rows) {
+ assert.ok((row.cells || []).reduce((n, c) => n + (Number(c.colspan) || 1), 0) <= 1, `no row overflows the grid: ${JSON.stringify(row)}`);
+ }
+ const note = warnings.filter((w) => /new_name/.test(w) && /spanned 2 columns/.test(w));
+ assert.strictEqual(note.length, 1, `the narrowing is reported once: ${JSON.stringify(warnings)}`);
+ assert.match(note[0], /1-column section 'sec_dest'.*now spans 1\. Declare its colspan/);
+});
+
+test('form topology: a moved colspan-2 cell is not squeezed into a half-full row of a 2-column section', async () => {
+ // The destination's last row has one free column: enough for the compiled cell (no span), not for the
+ // colspan-2 cell that is actually moving. It must take a row of its own.
+ const { form, warnings } = await buildMove(2, 'new_name', [{ cells: [{ id: 'c9', control: { fieldName: 'new_other' } }] }]);
+ const rows = destinationOf(form).rows.map((r) => (r.cells || []).map((c) => [c.control && c.control.fieldName, Number(c.colspan) || 1]));
+ assert.deepStrictEqual(rows, [[['new_other', 1]], [['new_name', 2]]], `got ${JSON.stringify(rows)}`);
+ assert.deepStrictEqual(warnings.filter((w) => /spanned/.test(w)), [], 'nothing was narrowed');
+});
+
+test('form topology: a moved cell that fits its destination keeps the span the maker gave it', async () => {
+ const { form, warnings } = await buildMove(4, 'new_name');
+ assert.strictEqual(movedCellOf(form).colspan, 2, 'an undeclared span is still the maker\u2019s');
+ assert.deepStrictEqual(warnings.filter((w) => /spanned/.test(w)), []);
+});
+
+test('form topology: a DECLARED colspan decides a moved cell\u2019s width, without a narrowing note', async () => {
+ const { form, warnings } = await buildMove(1, { name: 'new_name', colspan: 1 });
+ assert.strictEqual(movedCellOf(form).colspan, 1);
+ assert.deepStrictEqual(warnings.filter((w) => /spanned/.test(w)), [], 'the author chose the width');
+});
+
+test('form topology: after a narrowing move, a second apply of the same spec changes nothing', async () => {
+ const first = await buildMove(1, 'new_name');
+ const after = JSON.parse(JSON.stringify(first.form));
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: after });
+ const warnings = [];
+ await runSdkBuild(first.spec, { sdk, apply: true, phases: ['solution', 'data-model', 'forms'], warn: (m) => warnings.push(String(m)) });
+ const formWrites = calls.filter((c) => ['updateElement', 'addElement', 'moveElement', 'removeElement'].includes(c.name) && c.args[0] === 'form');
+ assert.deepStrictEqual(formWrites.map((c) => [c.name, c.args[2]]), [], 'the layout already matches');
+ assert.deepStrictEqual(warnings.filter((w) => /spanned/.test(w)), []);
+});
+
// --- F2: a span CLAMPED to 1 is still an explicit claim -----------------------------------------
// The clamp branch dropped the attribute when it reduced a span to 1, on the reasoning that "1 is
// the default". That recreates exactly the omission/value ambiguity the explicit-1 fix removed one
@@ -6227,9 +6348,8 @@ test('form topology: a section with a generated name found elsewhere is recreate
});
// A section the build CREATES lands where the layout places it — right after the sections already matched in
-// its column — not at the end. Appended, it followed every section still to come, and since the build never
-// reorders what exists (and verify does not check order) the wrong order was permanent: a new section
-// declared mid-column, or a generated one recreated after a drag in Maker.
+// its column — not at the end. Appended, it followed every section still to come — a new section declared
+// mid-column, or a generated one recreated after a drag in Maker — and the next build then had to move it.
test('form topology: a section the build creates lands where the layout places it, not at the end', async () => {
const layout = (middle) => explicitForm([
{ name: 'tab_one', label: 'One', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }, middle, { name: 'sec_after', label: 'After', columns: 1, fields: ['new_x'] }] },
@@ -6259,6 +6379,167 @@ test('form topology: a section the build creates lands where the layout places i
}
});
+// --- ORDER: the layout's tabs, and each form-column's sections, deploy in the layout's order -----------
+//
+// The build used to leave every existing container where it was: a reordered layout deployed in the old
+// order, and verify, which checked no order, passed it. Only the RELATIVE order of the containers the
+// layout names is the author's — a maker's own container, or an engine host, is never moved for its own
+// sake — and the fewest containers move (planOrderMoves).
+const orderSpec = (tabs) => { const spec = makeSpec(); spec.forms = explicitForm(tabs); return spec; };
+const tabMoves = (calls) => find(calls, 'moveElement')
+ .filter((c) => c.args[0] === 'form' && /^\/tabs\/\d+$/.test(String(c.args[2])))
+ .map((c) => [c.args[2], c.args[3], c.args[4] && c.args[4].index]);
+const settlesIn = async (spec, sdk, calls, shape, what) => {
+ const first = calls.length;
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });
+ const later = calls.slice(first);
+ assert.deepStrictEqual(await formShape(sdk, calls), shape, `${what}: stable`);
+ assert.deepStrictEqual([find(later, 'moveElement').length, find(later, 'addElement').filter((c) => c.args[0] === 'form').length,
+ find(later, 'removeElement').length], [0, 0, 0], `${what}: the next build changes nothing`);
+};
+
+test('form topology: sections an existing form holds in another order are moved into the layout\'s order', async () => {
+ const spec = orderSpec([{ name: 'tab_one', label: 'One', sections: [
+ { name: 'sec_a', label: 'A', columns: 1, fields: ['new_name'] },
+ { name: 'sec_b', label: 'B', columns: 1, fields: ['new_tier'] },
+ { name: 'sec_c', label: 'C', columns: 1, fields: ['new_code'] }] }]);
+ const deployed = tabsForm([['tab_one', 'One', [['s2', 'sec_c', 'C', ['new_code']], ['s0', 'sec_a', 'A', ['new_name']], ['s1', 'sec_b', 'B', ['new_tier']]]]]);
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });
+ const shape = [['tab_one', [['s0', 'sec_a', ['new_name']], ['s1', 'sec_b', ['new_tier']], ['s2', 'sec_c', ['new_code']]]]];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape, 'the same sections, fields and all, in the layout\'s order');
+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/0', '/tabs/0/columns/0/sections', 2]], 'one move: only the section out of order');
+ assert.ok(warnings.some((w) => w.includes("moved 1 section(s) in tab 'tab_one' (form-column 1) to put them in the layout's order: sec_a, sec_b, sec_c")),
+ `the reorder is reported; got ${JSON.stringify(warnings)}`);
+ await settlesIn(spec, sdk, calls, shape, 'sections');
+});
+
+test('form topology: tabs an existing form holds in another order are moved into the layout\'s order', async () => {
+ const spec = orderSpec([
+ { name: 'tab_one', label: 'One', sections: [{ name: 'sec_a', label: 'A', columns: 1, fields: ['new_name'] }] },
+ { name: 'tab_two', label: 'Two', sections: [{ name: 'sec_b', label: 'B', columns: 1, fields: ['new_tier'] }] },
+ { name: 'tab_three', label: 'Three', sections: [{ name: 'sec_c', label: 'C', columns: 1, fields: ['new_code'] }] }]);
+ const deployed = tabsForm([['tab_two', 'Two', [['s1', 'sec_b', 'B', ['new_tier']]]], ['tab_three', 'Three', [['s2', 'sec_c', 'C', ['new_code']]]],
+ ['tab_one', 'One', [['s0', 'sec_a', 'A', ['new_name']]]]]);
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });
+ const shape = [['tab_one', [['s0', 'sec_a', ['new_name']]]], ['tab_two', [['s1', 'sec_b', ['new_tier']]]], ['tab_three', [['s2', 'sec_c', ['new_code']]]]];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape, 'each tab keeps its sections and fields');
+ assert.deepStrictEqual(tabMoves(calls), [['/tabs/2', '/tabs', 0]], 'one move: the first tab goes before the two already in order');
+ assert.ok(warnings.some((w) => w.includes("moved 1 tab(s) to put the tabs in the layout's order: tab_one, tab_two, tab_three")), JSON.stringify(warnings));
+ await settlesIn(spec, sdk, calls, shape, 'tabs');
+});
+
+// A tab declared mid-layout is created in its place. It used to be appended — and before that, the
+// position pass handed it the tab ALREADY at its index, whose own want then found its name taken and
+// created a second tab of that name.
+test('form topology: a new tab declared mid-layout is created in its place, not appended or taken by position', async () => {
+ const spec = orderSpec([
+ { name: 'tab_one', label: 'One', sections: [{ name: 'sec_a', label: 'A', columns: 1, fields: ['new_name'] }] },
+ { name: 'tab_two', label: 'Two', sections: [{ name: 'sec_b', label: 'B', columns: 1, fields: ['new_tier'] }] },
+ { name: 'tab_three', label: 'Three', sections: [{ name: 'sec_c', label: 'C', columns: 1, fields: ['new_code'] }] }]);
+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_a', 'A', ['new_name']]]], ['tab_three', 'Three', [['s2', 'sec_c', 'C', ['new_code']]]]]);
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });
+ const shape = [['tab_one', [['s0', 'sec_a', ['new_name']]]], ['tab_two', [['new', 'sec_b', ['new_tier']]]], ['tab_three', [['s2', 'sec_c', ['new_code']]]]];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape, 'one tab of each name, in the layout\'s order');
+ const tabAdds = find(calls, 'addElement').filter((c) => c.args[0] === 'form' && c.args[2] === '/tabs');
+ assert.deepStrictEqual(tabAdds.map((c) => [c.args[3].name, c.args[4]]), [['tab_two', { position: { index: 1 } }]], 'created at its index');
+ assert.deepStrictEqual(tabMoves(calls), [], 'so nothing has to move');
+ await settlesIn(spec, sdk, calls, shape, 'new tab');
+});
+
+test('form topology: new tab with a reserved sibling label cannot steal that sibling', async () => {
+ for (const [what, authoredName, deployedName, incomingLabel, deployedLabel] of [
+ ['same spelling', 'tab_reserved', 'tab_reserved', 'Reserved', 'Reserved'],
+ ['case variants', 'TaB_ReSeRvEd', 'TAB_RESERVED', 'rEsErVeD', 'RESERVED'],
+ ]) {
+ const spec = orderSpec([
+ { name: 'tab_one', label: 'One', sections: [{ name: 'sec_a', label: 'A', columns: 1, fields: ['new_name'] }] },
+ { name: 'tab_new', label: incomingLabel, sections: [{ name: 'sec_new', label: 'New', columns: 1, fields: ['new_tier'] }] },
+ { name: authoredName, label: deployedLabel, sections: [{ name: 'sec_reserved', label: 'Reserved', columns: 1, fields: ['new_code'] }] },
+ ]);
+ const deployed = tabsForm([
+ ['tab_one', 'One', [['s0', 'sec_a', 'A', ['new_name']]]],
+ [deployedName, deployedLabel, [['s2', 'sec_reserved', 'Reserved', ['new_code']]]],
+ ]);
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });
+ const shape = [
+ ['tab_one', [['s0', 'sec_a', ['new_name']]]],
+ ['tab_new', [['new', 'sec_new', ['new_tier']]]],
+ [deployedName, [['s2', 'sec_reserved', ['new_code']]]],
+ ];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape, `${what}: distinct fields and containers, in authored order`);
+ const formId = find(calls, 'fetchArtifact').find((c) => c.args[0] === 'form').args[1];
+ const form = await sdk.getArtifact('form', formId);
+ assert.strictEqual(form.tabs.length, 3, `${what}: exactly one new tab`);
+ assert.strictEqual(form.tabs[2].id, deployed.tabs[1].id, `${what}: the reserved sibling keeps its deployed id`);
+ assert.strictEqual(form.tabs[0].id, deployed.tabs[0].id, `${what}: the first tab also keeps its id`);
+ const tabAdds = find(calls, 'addElement').filter((c) => c.args[0] === 'form' && c.args[2] === '/tabs');
+ assert.deepStrictEqual(tabAdds.map((c) => [c.args[3].name, c.args[4]]),
+ [['tab_new', { position: { index: 1 } }]], `${what}: the new tab is inserted, not a replacement for the sibling`);
+ assert.deepStrictEqual(tabMoves(calls), [], `${what}: insertion needs no corrective reorder`);
+ const first = calls.length;
+ await settlesIn(spec, sdk, calls, shape, what);
+ assert.deepStrictEqual(find(calls.slice(first), 'updateElement').filter((c) => c.args[0] === 'form'), [],
+ `${what}: the second apply changes no form attributes either`);
+ assert.strictEqual((await sdk.getArtifact('form', formId)).tabs[2].id, deployed.tabs[1].id,
+ `${what}: the same reserved sibling survives the second apply`);
+ }
+});
+
+// Only the layout's own sections are ordered: a maker's section (kept by `prune: false`) and an engine host
+// (the notes timeline) are not moved for their own sake.
+test('form topology: ordering moves only the layout\'s sections — a maker\'s own and an engine host keep their place', async () => {
+ const spec = orderSpec([{ name: 'tab_one', label: 'One', sections: [
+ { name: 'sec_a', label: 'A', columns: 1, fields: ['new_name'] },
+ { name: 'sec_b', label: 'B', columns: 1, fields: ['new_tier'] }] }]);
+ spec.forms[0].prune = false;
+ const deployed = tabsForm([['tab_one', 'One', [['s1', 'sec_b', 'B', ['new_tier']], ['m1', 'maker_x', 'Maker', ['new_code']],
+ ['s0', 'sec_a', 'A', ['new_name']], ['n1', 'section_notes', 'Notes', []]]]]);
+ deployed.tabs[0].columns[0].sections[3].rows = [{ cells: [{ control: { classId: '{06375649-C143-495E-A496-C962E5B4488E}' } }] }];
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });
+ const shape = [['tab_one', [['m1', 'maker_x', ['new_code']], ['s0', 'sec_a', ['new_name']], ['s1', 'sec_b', ['new_tier']], ['n1', 'section_notes', [undefined]]]]];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape, 'sec_b follows sec_a; the maker\'s section and the timeline host keep their places around them');
+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/0', '/tabs/0/columns/0/sections', 2]]);
+ await settlesIn(spec, sdk, calls, shape, 'mixed column');
+});
+
+// Tab order, a named section moved across tabs, and the order in its new column, in one build.
+test('form topology: tab order, a cross-tab section move and section order converge together', async () => {
+ const spec = orderSpec([
+ { name: 'tab_a', label: 'A', sections: [{ name: 'sec_x', label: 'X', columns: 1, fields: ['new_name'] }, { name: 'sec_z', label: 'Z', columns: 1, fields: ['new_code'] }] },
+ { name: 'tab_b', label: 'B', sections: [{ name: 'sec_y', label: 'Y', columns: 1, fields: ['new_tier'] }] }]);
+ const deployed = tabsForm([['tab_b', 'B', [['s1', 'sec_y', 'Y', ['new_tier']], ['s0', 'sec_x', 'X', ['new_name']]]], ['tab_a', 'A', [['s2', 'sec_z', 'Z', ['new_code']]]]]);
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });
+ const shape = [['tab_a', [['s0', 'sec_x', ['new_name']], ['s2', 'sec_z', ['new_code']]]], ['tab_b', [['s1', 'sec_y', ['new_tier']]]]];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape);
+ assert.deepStrictEqual(tabMoves(calls), [['/tabs/0', '/tabs', 1]]);
+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/1/columns/0/sections/1', '/tabs/0/columns/0/sections', 0]], 'the section is moved in ahead of sec_z, so no reorder follows');
+ await settlesIn(spec, sdk, calls, shape, 'combined');
+});
+
+// Sections matched by LABEL carry no name of their own — the field pass finds them through the recorded
+// POINTER, which the reorder shifts — and the next build must match them to the same wants again rather
+// than trade them back.
+test('form topology: sections matched by label are reordered, keep their fields, and stay put on the next build', async () => {
+ const spec = orderSpec([{ name: 'tab_one', label: 'One', sections: [
+ { label: 'Alpha', columns: 1, fields: ['new_name'] },
+ { label: 'Beta', columns: 1, fields: ['new_tier'] }] }]);
+ const deployed = tabsForm([['tab_one', 'One', [['s1', null, 'Beta', ['new_tier']], ['s0', null, 'Alpha', ['new_name']]]]]);
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });
+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });
+ const shape = [['tab_one', [['s0', null, ['new_name']], ['s1', null, ['new_tier']]]]];
+ assert.deepStrictEqual(await formShape(sdk, calls), shape);
+ assert.deepStrictEqual(find(calls, 'moveElement').length, 1, 'one section move, and no field had to follow it');
+ await settlesIn(spec, sdk, calls, shape, 'label-matched');
+});
+
// An older build could leave two sections of one name: the real one in the old tab and an empty twin
// in the new one. The twin already in place is used, so nothing is moved on top of it.
test('form topology: a same-named section already in the target column wins over one elsewhere', async () => {
diff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
index 83b43dccb..383a0a939 100644
--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
@@ -88,6 +88,16 @@ test('refreshes token with a fresh acquire on 401, bypassing any process memo',
assert.deepStrictEqual(calls.map((c) => c.headers.Authorization), ['Bearer OLD', 'Bearer NEW']);
});
+// The refresh after a 401 can fail too. That stops the request with the token failure — worded like every other one —
+// and nothing is re-sent with the rejected token.
+test('a 401 whose token refresh fails stops with the token failure and re-sends nothing', async () => {
+ const { request, calls } = fakeTransport({ statusCode: 401, headers: {}, body: '' });
+ let acquired = 0;
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => (++acquired === 1 ? 'OLD' : null), request });
+ await assert.rejects(http.get('https://org.crm.dynamics.com/x'), /Failed to refresh Azure CLI token for https:\/\/org\.crm\.dynamics\.com\. Run 'az login' first\./);
+ assert.deepStrictEqual([calls.length, acquired], [1, 2]);
+});
+
test('retries a transient 500 (SQL deadlock) with backoff, then succeeds', async () => {
const { request, calls } = fakeTransport(() =>
calls.length <= 2 ? { statusCode: 500, headers: {}, body: 'deadlock 1205' } : { statusCode: 200, headers: {}, body: '{"ok":true}' }
diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
index a14c0bc57..b03c52435 100644
--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
@@ -76,6 +76,11 @@ const SKILL_SDK_SURFACE = [
'listArtifacts',
'moveElement',
'publishArtifact',
+ // Step 8 publishes the app and every table whose default-view enrichment was saved but not yet
+ // published in ONE PublishXml envelope (one customization lock, one publish job) instead of one
+ // call per artifact. `publishArtifact` stays above: it is the per-target fallback when the batch
+ // is refused or a target in it fails.
+ 'publishArtifacts',
'pushArtifact',
'queryRecords',
'removeElement',
diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
index 79484997d..caab4e514 100644
--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
@@ -1716,16 +1716,20 @@ test('genpage resolve ignores live pages the manifest does not claim', async ()
assert.deepStrictEqual(items.map((i) => i.id), [PAGE_1]);
});
-test('genpage deletes nothing when the live-existence query fails (cannot prove what is ours)', async () => {
+test('genpage deletes nothing when the live-existence query fails, and FAILS the step (cannot prove what is ours)', async () => {
const sdk = {
async queryRecords(entity) {
if (entity === 'webresource') return [{ content: Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: PAGE_1 }] }), 'utf8').toString('base64') }];
throw new Error('uxagentproject query failed');
},
- async deleteRecord() {},
+ async deleteRecord() { throw new Error('nothing may be deleted'); },
};
- const items = await KIND_HANDLERS.genpage.resolve(sdk, { manifestName: 'new_app_pagemanifest' });
- assert.deepStrictEqual(items, []);
+ // Not an empty resolution: "none of them" would let the same run delete the manifest naming them.
+ await assert.rejects(() => KIND_HANDLERS.genpage.resolve(sdk, { manifestName: 'new_app_pagemanifest' }), (err) => {
+ assert.match(err.message, /could not check which of the 1 page\(s\) in 'new_app_pagemanifest' still exist \(uxagentproject query failed\) — no page is deleted/);
+ assert.strictEqual(err.failClosed, true, 'a "not found" in the read error must not read as "no pages"');
+ return true;
+ });
});
test('genpage skips a page the manifest claims but that no longer exists', async () => {
@@ -1737,10 +1741,142 @@ test('genpage skips a page the manifest claims but that no longer exists', async
assert.deepStrictEqual(items, []);
});
-test('genpage deletes nothing when the manifest is absent or unreadable', async () => {
- const sdk = { async queryRecords() { throw new Error('no manifest'); }, async deleteRecord() {} };
+test('genpage deletes nothing when the manifest is absent (the app never recorded a page)', async () => {
+ const queried = [];
+ const sdk = { async queryRecords(entity) { queried.push(entity); return []; }, async deleteRecord() {} };
const items = await KIND_HANDLERS.genpage.resolve(sdk, { manifestName: 'new_app_pagemanifest' });
assert.deepStrictEqual(items, []);
+ assert.deepStrictEqual(queried, ['webresource'], 'no manifest means no page query at all');
+});
+
+test('genpage deletes nothing when the manifest cannot be read, and FAILS the step', async () => {
+ const sdk = { async queryRecords() { throw new Error('HTTP 404 Not Found from a proxy'); }, async deleteRecord() {} };
+ await assert.rejects(() => KIND_HANDLERS.genpage.resolve(sdk, { manifestName: 'new_app_pagemanifest' }), (err) => {
+ assert.match(err.message, /could not read the page manifest 'new_app_pagemanifest' \(HTTP 404 Not Found from a proxy\) — no page is deleted; re-run the teardown/);
+ assert.strictEqual(err.failClosed, true);
+ return true;
+ });
+});
+
+// The manifest is the ONLY record of which pages this app authored, and the web-resources phase deletes
+// it well after the pages step. Deleting it after a failed pages step left the retry nothing to find
+// the pages by: it resolved none, reported ok, and the pages stayed behind for good.
+function pageTeardownRun({ pageDelete, manifestRead, liveQuery, declareManifest = false } = {}) {
+ const spec = { solution: { uniqueName: 'PgSln', publisherPrefix: 'new' }, app: { name: 'Pages App' } };
+ const manifestName = `${appUniqueName(spec)}_pagemanifest`;
+ if (declareManifest) spec.webResources = [{ name: manifestName.toUpperCase(), type: 'Data' }];
+ const state = {
+ app: true,
+ pages: new Set([PAGE_1]),
+ resources: new Map([[manifestName.toLowerCase(), 'wr-manifest'], [`${appUniqueName(spec)}_icon`.toLowerCase(), 'wr-icon']]),
+ solution: true,
+ deletes: [],
+ };
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: PAGE_1 }] }), 'utf8').toString('base64');
+ const sdk = {
+ resolveArtifact: async (kind, identity) => {
+ if (kind === 'app') return state.app ? [{ id: 'app-1', name: 'Pages App', appModuleIdUnique: 'app-u-1' }] : [];
+ if (kind === 'webResource') {
+ const id = state.resources.get(String(identity.name).toLowerCase());
+ return id ? [{ id, name: identity.name }] : [];
+ }
+ if (kind === 'solution') return state.solution ? [{ id: 'sol-1', name: 'PgSln' }] : [];
+ return [];
+ },
+ deleteAppCascade: async () => { state.deletes.push('app'); state.app = false; return { success: true, deleted: [], failures: [] }; },
+ queryRecords: async (entity) => {
+ if (entity === 'webresource') {
+ if (manifestRead) manifestRead();
+ return state.resources.has(manifestName.toLowerCase()) ? [{ content: manifest }] : [];
+ }
+ if (entity === 'uxagentproject') {
+ if (liveQuery) liveQuery();
+ return [...state.pages].map((id) => ({ uxagentprojectid: id }));
+ }
+ return [];
+ },
+ deleteRecord: async (entity, id) => {
+ assert.strictEqual(entity, 'uxagentproject');
+ if (pageDelete) pageDelete();
+ state.deletes.push(`page:${id}`);
+ state.pages.delete(id);
+ },
+ deleteWebResource: async (id) => {
+ state.deletes.push(id);
+ for (const [name, rid] of state.resources) if (rid === id) state.resources.delete(name);
+ },
+ deleteSolution: async () => { state.deletes.push('solution'); state.solution = false; },
+ };
+ return { spec, sdk, state, manifestName };
+}
+
+for (const [label, fault] of [
+ ['the page delete fails', { pageDelete: () => { throw new Error('HTTP 503 Service Unavailable'); } }],
+ ['the manifest read fails', { manifestRead: () => { const e = new Error('Resource not found (proxy)'); e.statusCode = 404; throw e; } }],
+ ['the live-page read fails', { liveQuery: () => { throw new Error('HTTP 429 Too Many Requests'); } }],
+ ['the live-page read answers a gateway 404', { liveQuery: () => { throw new Error('HTTP 404 Not Found (gateway)'); } }],
+]) {
+ test(`teardown keeps the page manifest (and the solution) when ${label}, and a clean re-run deletes the page`, async () => {
+ const faults = { ...fault };
+ const run = pageTeardownRun({
+ pageDelete: () => faults.pageDelete && faults.pageDelete(),
+ manifestRead: () => faults.manifestRead && faults.manifestRead(),
+ liveQuery: () => faults.liveQuery && faults.liveQuery(),
+ });
+ const events = [];
+ const failed = await runTeardown(run.spec, { apply: true }, { sdk: run.sdk, emit: (e) => events.push(e) });
+ assert.strictEqual(failed.ok, false);
+ assert.deepStrictEqual(failed.errors.map((e) => e.step), ['generative pages authored by this app']);
+ assert.ok(run.state.pages.has(PAGE_1), 'the page is still there');
+ assert.ok(run.state.resources.has(run.manifestName.toLowerCase()), 'the manifest naming the page survives for the re-run');
+ assert.ok(!run.state.resources.has(`${appUniqueName(run.spec)}_icon`.toLowerCase()), 'other app-owned web resources are still cleaned up');
+ assert.ok(run.state.solution, 'the solution is kept while a step failed');
+ const kept = events.find((e) => e.status === 'skip' && e.skip === 'kept' && e.label.includes('(page manifest)'));
+ assert.ok(kept, 'the kept manifest is reported as kept on purpose, not as not-found');
+ assert.match(kept.label, /kept — the generative pages step failed, and a re-run needs this manifest/);
+ assert.ok(failed.skipped.some((s) => s === kept.label));
+
+ for (const k of Object.keys(faults)) faults[k] = null;
+ run.state.deletes.length = 0;
+ const retry = await runTeardown(run.spec, { apply: true }, { sdk: run.sdk, emit: () => {} });
+ assert.strictEqual(retry.ok, true, JSON.stringify(retry.errors));
+ assert.deepStrictEqual(retry.deleted.genpage, [PAGE_1]);
+ assert.strictEqual(run.state.pages.size, 0, 'the retry finds the page through the kept manifest and deletes it');
+ assert.deepStrictEqual(run.state.deletes, [`page:${PAGE_1}`, 'wr-manifest', 'solution'], 'then the manifest, then the solution');
+ });
+}
+
+test('teardown deletes the page manifest when the pages step succeeds or a page is only still referenced', async () => {
+ const run = pageTeardownRun({ pageDelete: () => { throw new Error('The uxagentproject(x) component cannot be deleted because it is referenced by 1 other components.'); } });
+ const r = await runTeardown(run.spec, { apply: true }, { sdk: run.sdk, emit: () => {} });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.ok(run.state.pages.has(PAGE_1), 'a page another consumer holds is left to it');
+ assert.ok(!run.state.resources.has(run.manifestName.toLowerCase()), 'a skip is not a failure: the manifest goes');
+ assert.ok(!run.state.solution);
+});
+
+test('teardown keeps a DECLARED web resource that carries the page manifest name (any case) when the pages step fails', async () => {
+ const run = pageTeardownRun({ declareManifest: true, pageDelete: () => { throw new Error('HTTP 500'); } });
+ const plan = planTeardown(run.spec);
+ assert.strictEqual(plan.filter((s) => s.kind === 'webResource' && s.target.name.toLowerCase() === run.manifestName.toLowerCase()).length, 1,
+ 'the declared entry replaces the derived manifest step');
+ const r = await runTeardown(run.spec, { apply: true }, { sdk: run.sdk, emit: () => {} });
+ assert.strictEqual(r.ok, false);
+ assert.ok(run.state.resources.has(run.manifestName.toLowerCase()), 'the declared manifest-named resource is kept');
+});
+
+test('a failure in a step OTHER than the pages step still deletes the page manifest', async () => {
+ const run = pageTeardownRun();
+ const originalDelete = run.sdk.deleteWebResource;
+ run.sdk.deleteWebResource = async (id) => {
+ if (id === 'wr-icon') throw new Error('HTTP 500 icon delete failed');
+ return originalDelete(id);
+ };
+ const r = await runTeardown(run.spec, { apply: true }, { sdk: run.sdk, emit: () => {} });
+ assert.strictEqual(r.ok, false);
+ assert.deepStrictEqual(r.errors.map((e) => e.step), [`web resource ${appUniqueName(run.spec)}_icon (generated app icon)`]);
+ assert.strictEqual(run.state.pages.size, 0);
+ assert.ok(!run.state.resources.has(run.manifestName.toLowerCase()), 'the pages were handled, so the manifest has nothing left to find');
});
// --- command teardown: delete order must respect the real hierarchy depth -----------------------
diff --git a/plugins/model-apps/scripts/tests/skill-posttool-validation.test.js b/plugins/model-apps/scripts/tests/skill-posttool-validation.test.js
new file mode 100644
index 000000000..85a72dd8f
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/skill-posttool-validation.test.js
@@ -0,0 +1,276 @@
+"use strict";
+
+// The PostToolUse validator hook resolves the plugin root from its own directory
+// (hooks/ -> scripts/lib/modelapps-hook-utils.js -> skills/). Spawning the checked-in
+// hook would discover the real skills tree, which has no synthetic validators. Stage
+// a temp plugin that contains a byte copy of the real hook plus synthetic skills.
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");
+const REAL_HOOK = path.join(PLUGIN_ROOT, "hooks", "run-skill-posttool-validation.js");
+const HOOKS_JSON = path.join(PLUGIN_ROOT, "hooks", "hooks.json");
+
+const dirs = [];
+test.after(() => {
+ for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function mkTemp() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-posttool-"));
+ dirs.push(dir);
+ return dir;
+}
+
+function stagePlugin() {
+ const root = mkTemp();
+ fs.mkdirSync(path.join(root, "hooks"), { recursive: true });
+ fs.mkdirSync(path.join(root, "scripts", "lib"), { recursive: true });
+ fs.copyFileSync(REAL_HOOK, path.join(root, "hooks", "run-skill-posttool-validation.js"));
+ fs.copyFileSync(
+ path.join(PLUGIN_ROOT, "scripts", "lib", "modelapps-hook-utils.js"),
+ path.join(root, "scripts", "lib", "modelapps-hook-utils.js")
+ );
+ fs.copyFileSync(
+ path.join(PLUGIN_ROOT, "scripts", "lib", "utf8-stream.js"),
+ path.join(root, "scripts", "lib", "utf8-stream.js")
+ );
+ // The staged hook must be the real source, not a rewritten stand-in.
+ assert.equal(
+ fs.readFileSync(path.join(root, "hooks", "run-skill-posttool-validation.js"), "utf8"),
+ fs.readFileSync(REAL_HOOK, "utf8")
+ );
+ return root;
+}
+
+function writeSkill(root, name, scripts) {
+ const skillDir = path.join(root, "skills", name);
+ fs.mkdirSync(path.join(skillDir, "scripts"), { recursive: true });
+ fs.writeFileSync(path.join(skillDir, "SKILL.md"), "---\nname: " + name + "\n---\nSynthetic skill for hook tests.\n");
+ for (const script of scripts) {
+ fs.writeFileSync(path.join(skillDir, "scripts", script.name), script.source);
+ }
+}
+
+function validatorSource({ which, exitCode }) {
+ return [
+ '"use strict";',
+ 'const fs = require("node:fs");',
+ "const chunks = [];",
+ 'process.stdin.on("data", (chunk) => chunks.push(chunk));',
+ 'process.stdin.on("end", () => {',
+ ' const data = Buffer.concat(chunks).toString("utf8");',
+ " const marker = process.env.VALIDATOR_MARKER;",
+ " if (marker) {",
+ " fs.writeFileSync(marker, JSON.stringify({ which: " + JSON.stringify(which) + ", cwd: process.cwd(), data }));",
+ " }",
+ ' process.stdout.write("STDOUT:" + data);',
+ ' process.stderr.write("STDERR:' + which + '");',
+ // exitCode, not process.exit(): on macOS a pipe write is asynchronous, and exiting at once
+ // cuts off output past the 64 KiB pipe buffer.
+ " process.exitCode = " + exitCode + ";",
+ "});",
+ "",
+ ].join("\n");
+}
+
+function hookEnv(root, extra) {
+ return {
+ ...process.env,
+ ...extra,
+ DEBUG: "",
+ MODEL_APPS_DISABLE_HOOKS: extra && extra.MODEL_APPS_DISABLE_HOOKS ? extra.MODEL_APPS_DISABLE_HOOKS : "",
+ VALIDATOR_MARKER: path.join(root, "marker.json"),
+ };
+}
+
+function runHookSync(root, input, extraEnv) {
+ return spawnSync(process.execPath, [path.join(root, "hooks", "run-skill-posttool-validation.js")], {
+ input,
+ encoding: "utf8",
+ cwd: root,
+ env: hookEnv(root, extraEnv),
+ timeout: 15_000,
+ });
+}
+
+// Feed stdin from a file. Node reads a file-backed stdin as an fs.ReadStream in 64 KiB
+// chunks (its default highWaterMark), so a multibyte character placed across byte
+// 65,536 arrives in two `data` events on every run. Two writes to a pipe give no such
+// guarantee: the child may read them as one chunk, and a hook that decoded each chunk
+// on its own would still pass.
+const STDIN_CHUNK = 64 * 1024;
+
+function runHookFromFile(root, input, extraEnv, hook = path.join(root, "hooks", "run-skill-posttool-validation.js")) {
+ const file = path.join(root, "stdin.json");
+ fs.writeFileSync(file, input, "utf8");
+ const fd = fs.openSync(file, "r");
+ try {
+ return spawnSync(process.execPath, [hook], {
+ stdio: [fd, "pipe", "pipe"],
+ encoding: "utf8",
+ cwd: root,
+ env: hookEnv(root, extraEnv),
+ timeout: 15_000,
+ });
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+// A JSON payload whose `note` ends in 😀東京, with the 4-byte 😀 starting two bytes
+// before the first stdin chunk ends.
+function payloadSplitAcrossChunks(fields) {
+ const head = JSON.stringify({ ...fields, note: "" }).slice(0, -2);
+ const pad = "a".repeat(STDIN_CHUNK - 2 - Buffer.byteLength(head, "utf8"));
+ const payload = head + pad + "😀東京" + '"}';
+ const bytes = Buffer.from(payload, "utf8");
+ assert.ok(bytes.subarray(STDIN_CHUNK - 2, STDIN_CHUNK + 2).equals(Buffer.from("😀", "utf8")), "😀 straddles the chunk boundary");
+ assert.equal(JSON.parse(payload).note.slice(-4), "😀東京");
+ return payload;
+}
+
+// The real hook with its stdin reader swapped for one that decodes each chunk on its
+// own — the regression the payload above must expose.
+function stageNaiveHook(root) {
+ const hook = path.join(root, "hooks", "naive-posttool.js");
+ const source = fs.readFileSync(REAL_HOOK, "utf8");
+ const reader = "readUtf8Stream(process.stdin)";
+ assert.equal(source.split(reader).length, 2, "the hook reads stdin through readUtf8Stream exactly once");
+ fs.writeFileSync(hook, source.replace(reader,
+ "new Promise((resolve) => { let d = ''; process.stdin.on('data', (c) => { d += c.toString('utf8'); }); process.stdin.on('end', () => resolve(d)); })"));
+ return hook;
+}
+
+function readMarker(root) {
+ const marker = path.join(root, "marker.json");
+ if (!fs.existsSync(marker)) return null;
+ return JSON.parse(fs.readFileSync(marker, "utf8"));
+}
+
+test("hooks.json registers posttool validation for Skill", () => {
+ const hooks = JSON.parse(fs.readFileSync(HOOKS_JSON, "utf8"));
+ const post = hooks.hooks.PostToolUse;
+ const skill = post.find((entry) => entry.matcher === "Skill|skill");
+ assert.ok(skill, "PostToolUse must match Skill|skill");
+ assert.equal(skill.hooks.length, 1);
+ assert.equal(skill.hooks[0].type, "command");
+ assert.equal(skill.hooks[0].timeout, 30);
+ assert.match(skill.hooks[0].command, /PLUGIN_ROOT\|\|process\.env\.CLAUDE_PLUGIN_ROOT/);
+ assert.match(skill.hooks[0].command, /run-skill-posttool-validation\.js/);
+ assert.equal(fs.existsSync(REAL_HOOK), true);
+});
+
+test("posttool forwards payload cwd output and validator exit", () => {
+ const root = stagePlugin();
+ const validatorCwd = path.join(root, "validator-cwd");
+ fs.mkdirSync(validatorCwd);
+ writeSkill(root, "genpage", [
+ {
+ name: "validate-a.js",
+ source: validatorSource({ which: "validate-a.js", exitCode: 3 }),
+ },
+ ]);
+ const payload = payloadSplitAcrossChunks({
+ tool_input: { skill: "model-apps:genpage" },
+ cwd: validatorCwd,
+ });
+ const { status, stdout, stderr } = runHookFromFile(root, payload);
+ assert.equal(status, 3, stderr);
+ assert.match(stdout, /STDOUT:/);
+ assert.match(stdout, /😀東京/);
+ assert.match(stderr, /STDERR:validate-a\.js/);
+ const marker = readMarker(root);
+ assert.ok(marker, "validator must have run");
+ assert.equal(marker.which, "validate-a.js");
+ // realpath on both sides: on macOS the temp dir is under /var, a symlink, while the
+ // child's process.cwd() reports the resolved /private/var path.
+ assert.equal(fs.realpathSync(marker.cwd), fs.realpathSync(validatorCwd));
+ assert.equal(marker.data, payload, "the payload reaches the validator byte for byte");
+
+ // Negative control: the same payload through a hook that decodes each chunk on its own
+ // reaches the validator damaged, so the split above really happened.
+ fs.rmSync(path.join(root, "marker.json"));
+ const naive = runHookFromFile(root, payload, undefined, stageNaiveHook(root));
+ assert.equal(naive.status, 3, naive.stderr);
+ const damaged = readMarker(root);
+ assert.ok(damaged, "the naive hook still runs the validator");
+ assert.notEqual(damaged.data, payload);
+ assert.match(damaged.data, /\uFFFD/);
+});
+
+test("posttool runs the lexicographically first validate script", () => {
+ const root = stagePlugin();
+ writeSkill(root, "genpage", [
+ { name: "helper.js", source: validatorSource({ which: "helper.js", exitCode: 9 }) },
+ { name: "validate-z.js", source: validatorSource({ which: "validate-z.js", exitCode: 9 }) },
+ { name: "validate-a.js", source: validatorSource({ which: "validate-a.js", exitCode: 3 }) },
+ { name: "validate.txt", source: "not javascript\n" },
+ ]);
+ const { status } = runHookSync(root, JSON.stringify({ tool_input: { skill: "genpage" } }));
+ assert.equal(status, 3);
+ assert.equal(readMarker(root).which, "validate-a.js");
+});
+
+test("posttool exits 0 on malformed stdin", () => {
+ const root = stagePlugin();
+ writeSkill(root, "genpage", [
+ { name: "validate-a.js", source: validatorSource({ which: "validate-a.js", exitCode: 3 }) },
+ ]);
+ const { status, stderr } = runHookSync(root, "{not json");
+ assert.equal(status, 0);
+ assert.match(stderr, /Unexpected error/);
+ assert.equal(readMarker(root), null, "a parse failure must not run the validator");
+});
+
+test("posttool approves a skill with no validator", () => {
+ const root = stagePlugin();
+ writeSkill(root, "plain", []);
+ writeSkill(root, "genpage", [
+ { name: "validate-a.js", source: validatorSource({ which: "validate-a.js", exitCode: 3 }) },
+ ]);
+ const { status, stderr } = runHookSync(root, JSON.stringify({ tool_input: { skill: "plain" } }));
+ assert.equal(status, 0);
+ assert.doesNotMatch(stderr, /Unexpected error/);
+ assert.equal(readMarker(root), null);
+});
+
+test("posttool fail-opens when the validator cannot be spawned", () => {
+ const root = stagePlugin();
+ writeSkill(root, "genpage", [
+ { name: "validate-a.js", source: validatorSource({ which: "validate-a.js", exitCode: 3 }) },
+ ]);
+ const missingCwd = path.join(root, "missing-cwd");
+ const { status, stderr } = runHookSync(
+ root,
+ JSON.stringify({ tool_input: { skill: "genpage" }, cwd: missingCwd })
+ );
+ // spawnSync reports a missing cwd as a spawn error (status null), and the hook
+ // fail-opens that to 0. A successful spawn would have exited 3.
+ assert.equal(status, 0, stderr);
+ assert.equal(readMarker(root), null, "a spawn error must not look like the validator ran");
+ assert.doesNotMatch(stderr, /Unexpected error/);
+});
+
+test("posttool disable switch is a clean no-op", () => {
+ for (const value of ["1", "true"]) {
+ const root = stagePlugin();
+ writeSkill(root, "genpage", [
+ { name: "validate-a.js", source: validatorSource({ which: "validate-a.js", exitCode: 3 }) },
+ ]);
+ const { status, stdout, stderr } = runHookSync(
+ root,
+ JSON.stringify({ tool_input: { skill: "genpage" } }),
+ { MODEL_APPS_DISABLE_HOOKS: value }
+ );
+ assert.equal(status, 0, value);
+ assert.equal(stdout, "");
+ assert.equal(stderr, "");
+ assert.equal(readMarker(root), null, value + " must not run the validator");
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/smoke-eval.test.js b/plugins/model-apps/scripts/tests/smoke-eval.test.js
index 9a809c859..8c939f2a4 100644
--- a/plugins/model-apps/scripts/tests/smoke-eval.test.js
+++ b/plugins/model-apps/scripts/tests/smoke-eval.test.js
@@ -1,7 +1,10 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
+const fs = require('node:fs');
+const path = require('node:path');
const { buildSmokeSpec, runSmokeAssertions, subAreaTag, hasSitemapAttr } = require('../smoke-eval.js');
+const { loadCli } = require('./helpers/cli-harness.js');
const { validateAppSpec } = require('../lib/app-spec.js');
const { appDef } = require('../lib/sdk-build.js');
@@ -153,3 +156,121 @@ test('hasSitemapAttr matches whole attribute names and escapes path values', ()
// `.` and `/` in a platform ref must stay literal, not act as regex metacharacters.
assert.strictEqual(hasSitemapAttr(tag, 'VectorIcon', '/WebResources/new_tvecXsvg'), false);
});
+
+// The build → verify → cleanup driver is otherwise live-only. spawnSync is required at load, so the
+// CLI harness can replace it; nothing here may launch the real build, dataverse-request, or teardown.
+const SMOKE_ENV = 'https://contoso.crm.dynamics.com';
+const smokeScript = path.join(__dirname, '..', 'smoke-eval.js');
+
+test('smoke orchestration reports build assertion and teardown outcomes', async () => {
+ const passingXml = sitemapXmlFor(buildSmokeSpec('t'));
+ const origMk = fs.mkdtempSync;
+ const origRm = fs.rmSync;
+ const prevDirname = global.__dirname;
+
+ async function drive({ buildStatus, buildStdout = '', buildStderr = '', teardownStatus, views, xml, prefix = 't' }) {
+ const order = [];
+ const dirs = [];
+ const spawns = [];
+ fs.mkdtempSync = (p) => {
+ const dir = origMk.call(fs, p);
+ dirs.push(dir);
+ order.push('mkdtemp');
+ return dir;
+ };
+ fs.rmSync = (p, o) => {
+ order.push('rm');
+ return origRm.call(fs, p, o);
+ };
+ global.__dirname = path.join(__dirname, '..');
+ try {
+ const cli = loadCli(smokeScript, {
+ requires: {
+ 'node:child_process': {
+ spawnSync: (exec, args) => {
+ const base = path.basename(args[0] || '');
+ order.push('spawn:' + base);
+ spawns.push({ exec, args, base });
+ assert.strictEqual(exec, process.execPath, 'the driver must spawn node, never az or pac');
+ assert.ok(args.includes(SMOKE_ENV), base + ' was not given the requested environment');
+ if (base === 'build-model-app.js') {
+ const specArg = args[args.indexOf('--spec') + 1];
+ assert.ok(specArg && specArg.startsWith('@') && fs.existsSync(specArg.slice(1)), 'spec must be on disk before the build spawn');
+ return { status: buildStatus, stdout: buildStdout, stderr: buildStderr };
+ }
+ if (base === 'teardown-model-app.js') {
+ assert.ok(args.includes('--allow-destructive'), 'teardown must stay explicitly destructive');
+ return { status: teardownStatus, stdout: 'torn down\n', stderr: teardownStatus ? 'teardown failed\n' : '' };
+ }
+ if (base === 'dataverse-request.js') {
+ const api = args[3] || '';
+ let data = {};
+ if (api.startsWith('savedqueries')) data = { value: views };
+ else if (api.startsWith('appmodules(')) data = { appmoduleidunique: 'unique-1' };
+ else if (api.startsWith('appmodulecomponents')) data = { value: [{ objectid: 'sitemap-1' }] };
+ else if (api.startsWith('sitemaps(')) data = { sitemapxml: xml };
+ return { status: 0, stdout: JSON.stringify({ data }), stderr: '' };
+ }
+ throw new Error('unexpected smoke spawn ' + base);
+ },
+ },
+ },
+ });
+ const code = await cli.main(SMOKE_ENV, prefix);
+ return {
+ code,
+ order: order.slice(),
+ spawns,
+ dirExists: dirs.length ? fs.existsSync(dirs[0]) : null,
+ stdout: cli.stdoutText(),
+ stderr: cli.stderrText(),
+ dirs: dirs.slice(),
+ };
+ } finally {
+ fs.mkdtempSync = origMk;
+ fs.rmSync = origRm;
+ if (prevDirname === undefined) delete global.__dirname;
+ else global.__dirname = prevDirname;
+ for (const dir of dirs) origRm.call(fs, dir, { recursive: true, force: true });
+ }
+ }
+
+ const enriched = [{ name: 'Active t Orders', layoutxml: '<grid><row><cell name="new_status"/></row></grid>' }];
+ const built = JSON.stringify({ created: { app: 'app-1' } });
+
+ const ok = await drive({ buildStatus: 0, buildStdout: built, teardownStatus: 0, views: enriched, xml: passingXml });
+ assert.strictEqual(ok.code, 0, ok.stdout + ok.stderr);
+ assert.match(ok.stdout, /=== smoke eval: PASS \(/);
+ assert.strictEqual(ok.dirExists, false, 'a successful teardown deletes the local workspace');
+ assert.ok(ok.order.indexOf('spawn:teardown-model-app.js') < ok.order.indexOf('rm'), 'cleanup must follow a successful teardown, not precede it: ' + ok.order.join(','));
+ assert.ok(!ok.spawns.some((s) => /az|pac/i.test(path.basename(s.args[0] || ''))));
+
+ const buildFail = await drive({ buildStatus: 7, buildStdout: 'partial build\n', buildStderr: 'build-err\n', teardownStatus: 0, views: enriched, xml: passingXml });
+ assert.strictEqual(buildFail.code, 7);
+ assert.match(buildFail.stderr, /smoke build failed with exit code 7/);
+ assert.match(buildFail.stdout, /FAIL \(build failed; assertions skipped\)/);
+ assert.ok(!buildFail.order.includes('spawn:dataverse-request.js'), 'assertions must not run after a failed build');
+ assert.ok(buildFail.order.includes('spawn:teardown-model-app.js'), 'a failed build still tears down partial artifacts');
+ assert.strictEqual(buildFail.dirExists, false, 'cleanup still runs when teardown itself succeeded');
+
+ const assertFail = await drive({
+ buildStatus: 0,
+ buildStdout: built,
+ teardownStatus: 0,
+ views: [{ name: 'Active t Orders', layoutxml: '<grid><row><cell name="new_name"/></row></grid>' }],
+ xml: '<SiteMap><SubArea/></SiteMap>',
+ });
+ assert.strictEqual(assertFail.code, 1);
+ assert.match(assertFail.stdout, /▶ smoke assertions/);
+ assert.match(assertFail.stdout, /FAIL {2}default view enriched/);
+ assert.match(assertFail.stdout, /=== smoke eval: FAIL \(/);
+ assert.ok(!/assertions skipped/.test(assertFail.stdout));
+ assert.strictEqual(assertFail.dirExists, false, 'assertion failure still cleans up after a successful teardown');
+
+ const teardownFail = await drive({ buildStatus: 0, buildStdout: built, teardownStatus: 4, views: enriched, xml: passingXml });
+ assert.strictEqual(teardownFail.code, 4);
+ assert.match(teardownFail.stderr, /preserving local workspace for recovery/);
+ assert.match(teardownFail.stdout, /FAIL \(teardown failed; workspace preserved at /);
+ assert.strictEqual(teardownFail.dirExists, true, 'a failed teardown must keep the workspace for recovery');
+ assert.ok(!teardownFail.order.includes('rm'), 'cleanup must not run unless teardown succeeded: ' + teardownFail.order.join(','));
+});
diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.js
index 9e593cab5..297802c27 100644
--- a/plugins/model-apps/scripts/tests/source-literals.test.js
+++ b/plugins/model-apps/scripts/tests/source-literals.test.js
@@ -920,3 +920,27 @@ test('every committed .tsx the repo ships is accepted (false-positive corpus)',
});
assert.deepEqual(rejected, [], 'these real pages would have been rejected');
});
+
+test('ECMAScript line terminators end // comments without hiding executable navigation', () => {
+ for (const term of ['\r', '\n', '\r\n', '\u2028', '\u2029']) {
+ const code = `// inert${term}navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})`;
+ assert.deepStrictEqual(navReferencedKeys(code), ['detail'], JSON.stringify(term));
+ }
+});
+
+test('page structure accepts default exports after every ECMAScript line terminator', () => {
+ const { pageStructureProblems } = require('../lib/page-structure.js');
+ for (const term of ['\r', '\n', '\r\n', '\u2028', '\u2029']) {
+ const code = `// header${term}export default function Page() { return null; }\n`;
+ assert.deepStrictEqual(pageStructureProblems(code), [], JSON.stringify(term));
+ }
+});
+
+test('string and regex literal line-terminator rules follow ECMAScript', () => {
+ const ls = 'const s = "a\u2028b";\nexport default function Page() { return null; }\n';
+ const ps = 'const s = "a\u2029b";\nexport default function Page() { return null; }\n';
+ assert.equal(hasDefaultExport(ls), true, 'LS is legal inside string literals since ES2019');
+ assert.equal(hasDefaultExport(ps), true, 'PS is legal inside string literals since ES2019');
+ assert.equal(hasDefaultExport('const s = "a\rb";\nexport default function Page() { return null; }\n'), true, 'CR ends the broken string so later code remains visible');
+ assert.deepStrictEqual(navReferencedKeys('const r = /a\u2028/;\nnavigateTo({pageType:"generative",pageId:"PAGEREF_detail"})'), ['detail'], 'raw LS terminates a regex literal scan');
+});
diff --git a/plugins/model-apps/scripts/tests/spec-lint.test.js b/plugins/model-apps/scripts/tests/spec-lint.test.js
index d5e803fe3..e7f694a9f 100644
--- a/plugins/model-apps/scripts/tests/spec-lint.test.js
+++ b/plugins/model-apps/scripts/tests/spec-lint.test.js
@@ -21,6 +21,73 @@ test('a clean spec passes with no errors', () => {
assert.strictEqual(r.errors.length, 0);
});
+// Views, charts and forms belong to a table, and the build finds each by table and name (a form also by
+// type). The same name on two tables is the supported shape — two tables' "By Status" charts — and used
+// to be warned about as a duplicate; only a repeat on ONE table collides.
+test('a view, chart or form name repeated on another table is not a duplicate; on the same table it is', () => {
+ const s = base();
+ s.views = [{ entity: 'new_customer', name: 'Active', columns: ['new_name'] }, { entity: 'new_ticket', name: 'active', columns: ['new_name'] }];
+ s.charts = [{ entity: 'new_customer', name: 'By Status', chartType: 'Pie', groupBy: 'new_name', measure: 'count' },
+ { entity: 'new_ticket', name: 'By Status', chartType: 'Pie', groupBy: 'new_priority', measure: 'count' }];
+ s.forms = [{ entity: 'new_customer', name: 'Main' }, { entity: 'new_ticket', name: 'Main' }, { entity: 'new_ticket', name: 'Main', formType: 'QuickCreate' }];
+ assert.deepStrictEqual(lintAppSpec(s).warnings.filter((w) => /Duplicate/.test(w)), []);
+
+ s.views.push({ entity: 'NEW_TICKET', name: 'Active', columns: ['new_name'] });
+ s.charts.push({ entity: 'new_ticket', name: 'by status', chartType: 'Bar', groupBy: 'new_priority', measure: 'count' });
+ s.forms.push({ entity: 'new_ticket', name: 'main', formType: 'Main' });
+ assert.deepStrictEqual(lintAppSpec(s).warnings.filter((w) => /Duplicate/.test(w)), [
+ 'Duplicate view name on NEW_TICKET: Active',
+ 'Duplicate chart name on new_ticket: by status',
+ 'Duplicate form name on new_ticket: main',
+ ]);
+});
+
+// pac stores each ASCII `"` in a page's name as `\"` on the page's own record (live-measured) and changes nothing else.
+// A warning: the navigation shows the subarea title, which the build writes as given.
+test('a page name with an ASCII double quote is warned about; the characters pac keeps are not', () => {
+ const s = base();
+ s.pages = [
+ { key: 'a', name: 'Say "hi" now', source: { kind: 'tsx', file: 'pages/a.tsx' } },
+ { key: 'b', name: 'Back\\slash “curly” \'single\' 東京', source: { kind: 'tsx', file: 'pages/b.tsx' } },
+ ];
+ const r = lintAppSpec(s);
+ assert.deepStrictEqual(r.warnings.filter((w) => /double quote/.test(w)), [
+ 'Page \'Say "hi" now\': pac stores each ASCII double quote (") in a page\'s name as \\" on the page\'s own record — use typographic quotes (“ ”) or an apostrophe instead',
+ ]);
+ assert.strictEqual(r.errors.length, 0, 'a warning, never an error');
+});
+
+// Under an auto layout the build writes readOnly/hidden only on the fields the layout places — the primary column, the
+// declared columns and the parent lookups. A flag on any other field is never applied, so the author is told.
+test('an auto layout\'s fieldOptions flag on a field the layout does not place is warned about', () => {
+ const s = base();
+ s.forms = [{ entity: 'new_ticket', name: 'Ticket Main', layout: 'auto', fieldOptions: {
+ ownerid: { readOnly: true }, // not placed: a stock column the spec does not declare
+ createdon: { hidden: true, readOnly: true },
+ new_priority: { readOnly: true }, // a declared column
+ new_name: { hidden: true }, // the primary column
+ new_customerid: { readOnly: true }, // the parent lookup
+ statuscode: { after: 'new_name' }, // no flag: nothing to apply
+ } }];
+ const warned = lintAppSpec(s).warnings.filter((w) => /does not place/.test(w));
+ assert.deepStrictEqual(warned, [
+ "Form new_ticket 'Ticket Main': fieldOptions['ownerid'] sets readOnly on a field the auto layout does not place — it places the primary column, the table's declared columns and its parent lookups — so the build never applies it. Declare 'ownerid' as a column, or list it in an explicit layout (prune: false keeps the rest of the form).",
+ "Form new_ticket 'Ticket Main': fieldOptions['createdon'] sets readOnly and hidden on a field the auto layout does not place — it places the primary column, the table's declared columns and its parent lookups — so the build never applies it. Declare 'createdon' as a column, or list it in an explicit layout (prune: false keeps the rest of the form).",
+ ]);
+ // An explicit layout places what it lists; this rule is about the auto layout alone.
+ s.forms[0] = { entity: 'new_ticket', name: 'Ticket Main', prune: false, tabs: [{ label: 'G', sections: [{ fields: ['new_name'] }] }], fieldOptions: { ownerid: { readOnly: true } } };
+ assert.deepStrictEqual(lintAppSpec(s).warnings.filter((w) => /does not place/.test(w)), []);
+ // A DECLARED column the auto layout leaves off is not told to declare itself: a BigInt has no form control at all;
+ // a Customer column has one, but the auto layout places only scalar columns — an explicit layout can list it.
+ s.entities[1].columns.push({ schemaName: 'new_bigcount', displayName: 'Big Count', type: 'BigInt' },
+ { schemaName: 'new_payer', displayName: 'Payer', type: 'Customer' });
+ s.forms[0] = { entity: 'new_ticket', name: 'Ticket Main', layout: 'auto', fieldOptions: { new_bigcount: { hidden: true }, new_payer: { readOnly: true } } };
+ assert.deepStrictEqual(lintAppSpec(s).warnings.filter((w) => /fieldOptions\['new_(bigcount|payer)'\]/.test(w)), [
+ "Form new_ticket 'Ticket Main': fieldOptions['new_bigcount'] sets hidden on a BigInt column, which has no form control, so the auto layout leaves it off the form and the build never applies it.",
+ "Form new_ticket 'Ticket Main': fieldOptions['new_payer'] sets readOnly on a Customer column, a type the auto layout does not place, so the build never applies it. List 'new_payer' in an explicit layout to place it (prune: false keeps the rest of the form).",
+ ]);
+});
+
test('malformed top-level collections return lint errors instead of throwing', () => {
for (const spec of [
null,
diff --git a/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js b/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js
index 58bdac13a..a023fb0df 100644
--- a/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js
+++ b/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js
@@ -7,10 +7,36 @@ const os = require("node:os");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
+const {
+ STUB_BANNER,
+ TRAP_BANNER,
+ startedMarker,
+ writePacExecutable,
+ isolatePath,
+} = require("./fixtures/stub-pac/install.js");
+
const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");
const HOOK = path.join(PLUGIN_ROOT, "hooks", "run-skill-pretool-telemetry.js");
const SHIPPED_IKEY = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry", "ikey.json");
+// A forbidden native `pac` is prepended to the parent PATH. Every hook spawn replaces
+// PATH with only the stub directory, so this binary must never start — if a test
+// starts inheriting PATH again, the trap runs and the suite fails.
+let stubDir;
+let trapDir;
+let stubBuilt = false;
+test.before(() => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-tel-pac-"));
+ stubDir = path.join(root, "stub");
+ trapDir = path.join(root, "trap");
+ stubBuilt = writePacExecutable(stubDir, STUB_BANNER);
+ writePacExecutable(trapDir, TRAP_BANNER);
+ const delim = path.delimiter;
+ for (const key of Object.keys(process.env)) {
+ if (key.toUpperCase() === "PATH") process.env[key] = trapDir + delim + process.env[key];
+ }
+});
+
function mkTemp() {
return fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-tel-"));
}
@@ -19,18 +45,22 @@ function runHook({ input, configDir, ikeyPath, fakeProbe }) {
return spawnSync(process.execPath, [HOOK], {
input,
encoding: "utf8",
- env: {
- ...process.env,
- POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
- POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",
- // Clear the CI/automation opt-out so the provisioned path still reaches its probe.
- POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "",
- // Route emission to a local probe instead of a real OneCollector.
- POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",
- },
- // The provisioned path shells out to `pac auth who` + `pac --version`; give it
- // room so pac cold-start doesn't flake when pac is installed.
- timeout: 30_000,
+ env: isolatePath(
+ {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",
+ // Clear the CI/automation opt-out so the provisioned path still reaches its probe.
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "",
+ // Route emission to a local probe instead of a real OneCollector.
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",
+ // A developer machine may have the kill-switch set; the hook must still be exercised.
+ MODEL_APPS_DISABLE_HOOKS: "",
+ },
+ stubDir
+ ),
+ // PATH holds only the stub pac, so this is not waiting on a real PAC cold start.
+ timeout: 15_000,
});
}
@@ -143,3 +173,36 @@ test("enabled config but placeholder key → treated as unprovisioned (no probe)
assert.equal(status, 0);
assert.equal(waitForFile(probePath, 1500), false, "placeholder key must not emit a probe");
});
+
+test("provisioned hooks never use ambient PAC or credentials", (t) => {
+ if (!stubBuilt) {
+ t.skip("no C# compiler (csc.exe) on this Windows machine to build the native pac stub");
+ return;
+ }
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = writeProvisionedConfig(configDir);
+ fs.rmSync(startedMarker(stubDir), { force: true });
+ fs.rmSync(startedMarker(trapDir), { force: true });
+
+ const { status } = runHook({
+ input: JSON.stringify({ tool_input: { skill: "genpage" } }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.ok(waitForFile(probePath, 5000), "dispatcher should have written the probe");
+ const probeText = fs.readFileSync(probePath, "utf8");
+ const body = JSON.parse(JSON.parse(probeText).body);
+ assert.equal(body.data.orgId, STUB_BANNER.orgId);
+ assert.equal(body.data.tenantId, STUB_BANNER.tenantId);
+ assert.equal(body.data.pacCliVersion, STUB_BANNER.version);
+ assert.equal(body.data.eventInfo, undefined);
+ assert.equal(probeText.includes(STUB_BANNER.objectId), false, "Entra object id must not be emitted");
+ assert.equal(probeText.includes(STUB_BANNER.user), false, "user principal must not be emitted");
+ assert.equal(probeText.includes("aadObjectId"), false);
+ assert.equal(probeText.includes(TRAP_BANNER.orgId), false, "trap org must not be the source");
+ assert.equal(fs.existsSync(startedMarker(stubDir)), true, "stub pac must have run");
+ assert.equal(fs.existsSync(startedMarker(trapDir)), false, "ambient pac on the parent PATH must not start");
+});
diff --git a/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js b/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js
index 0552bb5df..402320e6f 100644
--- a/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js
+++ b/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js
@@ -7,9 +7,35 @@ const os = require("node:os");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
+const {
+ STUB_BANNER,
+ TRAP_BANNER,
+ startedMarker,
+ writePacExecutable,
+ isolatePath,
+} = require("./fixtures/stub-pac/install.js");
+
const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");
const HOOK = path.join(PLUGIN_ROOT, "hooks", "run-user-prompt-telemetry.js");
+// A forbidden native `pac` is prepended to the parent PATH. Every hook spawn replaces
+// PATH with only the stub directory, so this binary must never start — if a test
+// starts inheriting PATH again, the trap runs and the suite fails.
+let stubDir;
+let trapDir;
+let stubBuilt = false;
+test.before(() => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-uptel-pac-"));
+ stubDir = path.join(root, "stub");
+ trapDir = path.join(root, "trap");
+ stubBuilt = writePacExecutable(stubDir, STUB_BANNER);
+ writePacExecutable(trapDir, TRAP_BANNER);
+ const delim = path.delimiter;
+ for (const key of Object.keys(process.env)) {
+ if (key.toUpperCase() === "PATH") process.env[key] = trapDir + delim + process.env[key];
+ }
+});
+
function mkTemp() {
return fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-uptel-"));
}
@@ -18,14 +44,18 @@ function runHook({ input, configDir, ikeyPath, fakeProbe }) {
return spawnSync(process.execPath, [HOOK], {
input,
encoding: "utf8",
- env: {
- ...process.env,
- POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
- POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",
- POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "",
- POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",
- },
- timeout: 30_000,
+ env: isolatePath(
+ {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "",
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",
+ MODEL_APPS_DISABLE_HOOKS: "",
+ },
+ stubDir
+ ),
+ timeout: 15_000,
});
}
@@ -141,3 +171,36 @@ test("enabled config but placeholder key → prompt path emits nothing (no probe
assert.equal(status, 0);
assert.equal(waitForFile(probePath, 1500), false, "placeholder key must not emit on the prompt path");
});
+
+test("provisioned hooks never use ambient PAC or credentials", (t) => {
+ if (!stubBuilt) {
+ t.skip("no C# compiler (csc.exe) on this Windows machine to build the native pac stub");
+ return;
+ }
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = writeProvisionedConfig(configDir);
+ fs.rmSync(startedMarker(stubDir), { force: true });
+ fs.rmSync(startedMarker(trapDir), { force: true });
+
+ const { status } = runHook({
+ input: JSON.stringify({ prompt: "/model-apps:genpage build a dashboard", session_id: "s1" }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.ok(waitForFile(probePath, 5000), "dispatcher should have written the probe");
+ const probeText = fs.readFileSync(probePath, "utf8");
+ const body = JSON.parse(JSON.parse(probeText).body);
+ assert.equal(body.data.orgId, STUB_BANNER.orgId);
+ assert.equal(body.data.tenantId, STUB_BANNER.tenantId);
+ assert.equal(body.data.pacCliVersion, STUB_BANNER.version);
+ assert.equal(body.data.eventInfo, undefined);
+ assert.equal(probeText.includes(STUB_BANNER.objectId), false, "Entra object id must not be emitted");
+ assert.equal(probeText.includes(STUB_BANNER.user), false, "user principal must not be emitted");
+ assert.equal(probeText.includes("aadObjectId"), false);
+ assert.equal(probeText.includes(TRAP_BANNER.orgId), false, "trap org must not be the source");
+ assert.equal(fs.existsSync(startedMarker(stubDir)), true, "stub pac must have run");
+ assert.equal(fs.existsSync(startedMarker(trapDir)), false, "ambient pac on the parent PATH must not start");
+});
diff --git a/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js b/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js
index ca4d0c5b6..c8c523527 100644
--- a/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js
+++ b/plugins/model-apps/scripts/tests/telemetry-lib-copy.test.js
@@ -5,8 +5,8 @@
// Marketplace installs copy only the plugin directory, so model-apps carries physical copies of
// * `shared/telemetry/lib` at `scripts/lib/telemetry/lib` (the 1DS library its hooks require), and
// * the shared skill workflows at `skills/telemetry/` and `skills/report-issue/`.
-// Nothing else in model-apps CI compares them with their source: `shared/telemetry/tests` has no
-// workflow of its own. So an edit to one side that forgets the other gives a green build while the
+// The telemetry library copy is also compared by shared/telemetry/tests/bundled-copies.test.js when
+// either side changes; nothing else compares the skill copies. So an edit to one side that forgets the other gives a green build while the
// plugin ships stale code, or a stale disclosure. That happened to the telemetry workflow's
// disclosure: a Power Pages change updated its own copy and not the shared source. This suite turns
// that silent drift into a failure. It mirrors the Power Pages guard of the same name. The workflow's
diff --git a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js b/plugins/model-apps/scripts/tests/validate-icon-imports.test.js
index 638d7bd9d..9c719ac88 100644
--- a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js
+++ b/plugins/model-apps/scripts/tests/validate-icon-imports.test.js
@@ -450,3 +450,21 @@ test('every committed sample page passes the icon hook', () => {
assert.equal(status, 0, `samples/${name} is blocked by the hook:\n${stderr}`);
}
});
+
+test('line comments ending with CR, LS or PS do not hide or forge icon imports', () => {
+ for (const term of ['\r', '\u2028', '\u2029']) {
+ const commented = `// import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';${term}${GENPAGE_HEADER}`;
+ let fp = writeTemp(tmp, 'commented.tsx', commented);
+ assert.equal(runHook(payloadFor(fp, commented)).status, 0, `commented ${JSON.stringify(term)}`);
+
+ const bad = `import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';${term}${GENPAGE_HEADER}`;
+ fp = writeTemp(tmp, 'bad.tsx', bad);
+ assert.equal(runHook(payloadFor(fp, bad)).status, 2, `real ${JSON.stringify(term)}`);
+ }
+});
+
+test('block comments preserve LS and PS offsets while icon imports are matched', () => {
+ const content = `/* note\u2028import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';\u2029 */\nimport { AddRegular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ assert.equal(runHook(payloadFor(fp, content)).status, 0);
+});
diff --git a/plugins/model-apps/scripts/tests/verify-compile-roundtrip-real-bundle.test.js b/plugins/model-apps/scripts/tests/verify-compile-roundtrip-real-bundle.test.js
index 08b975859..331231f1a 100644
--- a/plugins/model-apps/scripts/tests/verify-compile-roundtrip-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/verify-compile-roundtrip-real-bundle.test.js
@@ -22,8 +22,9 @@ const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
const ai = require('../lib/artifact-intent.js');
const { verifySpec } = require('../lib/verify-spec.js');
-const META = { new_ticket: { new_name: 'String', new_notes: 'Memo', new_code: 'String', new_area: 'String' } };
+const META = { new_ticket: { new_name: 'String', new_notes: 'Memo', new_code: 'String', new_area: 'String', new_customerid: 'Lookup' } };
const NOTES_CLASS_ID = '06375649-C143-495E-A496-C962E5B4488E';
+const QUICK_VIEW_CLASS_ID = '5C5600E0-1D6E-4205-A272-BE80DA87FD42';
const dirs = [];
test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
@@ -41,7 +42,7 @@ const baseSpec = () => ({
});
// The formxml the real bundle would send for a compiled form — the engine's createFormShell order.
-async function compiledFormXml(spec, form) {
+async function compiledFormXml(spec, form, addControls) {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const cap = [];
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-rt-'));
@@ -66,6 +67,7 @@ async function compiledFormXml(spec, form) {
const art = await sdk.createArtifact('form', { name: intent.name, entityLogicalName: intent.entityLogicalName, formType: intent.formType, status: intent.status });
for (const tab of intent.tabs) await sdk.addElement('form', art.id, '/tabs', tab);
await sdk.removeElement('form', art.id, '/tabs/0');
+ if (addControls) await addControls(sdk, art.id);
await sdk.pushArtifact('form', art.id);
const xml = String((cap.find((c) => c && typeof c.formxml === 'string') || {}).formxml || '');
assert.ok(xml.includes('<section'), 'the bundle must have serialized a form');
@@ -77,6 +79,10 @@ async function topologyVerdict(form, tamper) {
spec.forms = [form];
let xml = await compiledFormXml(spec, form);
if (tamper) xml = tamper(xml);
+ return topologyVerdictForXml(spec, form, xml);
+}
+
+async function topologyVerdictForXml(spec, form, xml) {
const read = {
findTable: async () => ({ logicalName: 'new_ticket' }),
findColumns: async () => [],
@@ -92,6 +98,18 @@ async function topologyVerdict(form, tamper) {
const explicit = (section, extra = {}) => ({ entity: 'new_ticket', name: 'Main', ...extra,
tabs: [{ name: 'tab_x', label: 'X', sections: [{ name: 'sec_x', label: 'X', ...section }] }] });
+// Every display flag, form-column widths both declared and left to the compiler's equal split, and more
+// than one tab and section to put in order — the attributes verify compares beyond placement and spans.
+const STATEFUL = () => ({ entity: 'new_ticket', name: 'Main', tabs: [
+ { name: 'tab_a', label: 'A', columns: [
+ { width: '70%', sections: [
+ { name: 'sec_a1', label: 'A1', fields: [{ name: 'new_name', readOnly: true }, { name: 'new_code', hidden: true }] },
+ { name: 'sec_a2', label: 'A2', visible: false, showLabel: false, fields: ['new_area'] }] },
+ { width: '30%', sections: [{ name: 'sec_a3', label: 'A3', fields: [] }] }] },
+ { name: 'tab_b', label: 'B', expanded: false, columns: [{ sections: [{ name: 'sec_b1', label: 'B1', fields: ['new_notes'] }] }, { sections: [] }] },
+ { name: 'tab_c', label: 'C', visible: false, sections: [{ name: 'sec_c1', label: 'C1', fields: [] }] },
+] });
+
const CASES = [
['a section that omits columns, with a declared colspan', explicit({ fields: ['new_name', { name: 'new_notes', colspan: 2 }] })],
['a QuickCreate section that asks for 2 columns', explicit({ columns: 2, fields: ['new_name', 'new_code'] }, { name: 'Quick', formType: 'QuickCreate' })],
@@ -100,6 +118,7 @@ const CASES = [
['a declared rowspan on the last field', explicit({ columns: 2, fields: ['new_name', 'new_code', { name: 'new_notes', rowspan: 3 }] })],
['a span declared through form-level fieldOptions on a plain string entry',
{ ...explicit({ columns: 2, fields: ['new_name', 'new_notes'] }), fieldOptions: { new_notes: { colspan: 2 } } }],
+ ['display state: a collapsed and a hidden tab, a hidden section without its label, a hidden and a read-only field', STATEFUL()],
];
for (const [label, form] of CASES) {
@@ -127,3 +146,100 @@ test('compile -> verify round trip FAILS a tampered span that was declared throu
assert.strictEqual(chk.present, false, 'a fieldOptions span that did not deploy must fail verification');
assert.match(chk.detail, /new_notes' has colspan 1, the spec declares 2/);
});
+
+// The bundle's own FormXML for the stateful form, with ONE attribute changed after serialization — each
+// is a difference the build converges, so each must fail. Replacements are scoped to one element by
+// name, so a control proves the attribute it names and no other.
+const inElement = (tag, name, fn) => (xml) => {
+ const re = new RegExp(`<${tag}\\b[^>]*\\bname="${name}"[^>]*>`);
+ assert.match(xml, re, `the serialized form has a ${tag} named ${name}`);
+ return xml.replace(re, fn);
+};
+const cellOf = (field, fn) => (xml) => {
+ const at = xml.search(new RegExp(`<control\\b[^>]*\\bdatafieldname="${field}"`));
+ assert.ok(at > 0, `the serialized form has a control for ${field}`);
+ const cellAt = xml.lastIndexOf('<cell', at);
+ const cellEnd = xml.indexOf('>', cellAt) + 1;
+ const controlEnd = xml.indexOf('>', at) + 1;
+ return xml.slice(0, cellAt) + fn(xml.slice(cellAt, cellEnd), xml.slice(cellEnd, at), xml.slice(at, controlEnd)) + xml.slice(controlEnd);
+};
+const swapFirst = (tag) => (xml) => {
+ const re = new RegExp(`(<${tag}\\b[\\s\\S]*?</${tag}>)(<${tag}\\b[\\s\\S]*?</${tag}>)`);
+ assert.match(xml, re, `two adjacent ${tag}s to swap`);
+ return xml.replace(re, '$2$1');
+};
+const TAMPER = [
+ ['a form-column width', (xml) => xml.replace('width="70%"', 'width="50%"'), /form-column 1 is deployed 50% wide, the spec declares 70%/],
+ ['an equal-split width', (xml) => xml.replace(/(<tab\b[^>]*name="tab_b"[\s\S]*?<column\b[^>]*?)width="50%"/, '$1width="60%"'), /tab 'tab_b' form-column 1 is deployed 60% wide, the spec declares 50%/],
+ ['a collapsed tab', inElement('tab', 'tab_b', (t) => t.replace(/expanded="false"/, 'expanded="true"')), /tab 'tab_b' is deployed with expanded="true", the spec declares expanded: false/],
+ ['a hidden tab', inElement('tab', 'tab_c', (t) => t.replace(/visible="false"/, 'visible="true"')), /tab 'tab_c' is deployed with visible="true", the spec declares visible: false/],
+ ['a hidden section', inElement('section', 'sec_a2', (s) => s.replace(/visible="false"/, 'visible="true"')), /section 'sec_a2' is deployed with visible="true", the spec declares visible: false/],
+ ['a section label display', inElement('section', 'sec_a2', (s) => s.replace(/showlabel="false"/, 'showlabel="true"')), /section 'sec_a2' is deployed with showlabel="true", the spec declares showLabel: false/],
+ ['a hidden field', cellOf('new_code', (cell, labels, control) => cell.replace(/visible="false"/, 'visible="true"') + labels + control), /field 'new_code' is deployed with visible="true", the spec declares hidden: true/],
+ ['a read-only field', cellOf('new_name', (cell, labels, control) => cell + labels + control.replace(/disabled="true"/, 'disabled="false"')), /field 'new_name' is deployed with disabled="false", the spec declares readOnly: true/],
+ ['the order of two sections', swapFirst('section'), /the sections of tab 'tab_a' form-column 1 are deployed in the order sec_a2, sec_a1; the spec orders them sec_a1, sec_a2/],
+ ['the order of two tabs', swapFirst('tab'), /the tabs are deployed in the order tab_b, tab_a, tab_c; the spec orders them tab_a, tab_b, tab_c/],
+];
+for (const [what, tamper, expected] of TAMPER) {
+ test(`compile -> verify round trip FAILS the bundle's own form with ${what} changed`, async () => {
+ const chk = await topologyVerdict(STATEFUL(), (xml) => {
+ const changed = tamper(xml);
+ assert.notStrictEqual(changed, xml, `the control must change the serialized form (${what})`);
+ return changed;
+ });
+ assert.strictEqual(chk.present, false, `${what} that did not deploy as compiled must fail verification`);
+ assert.match(chk.detail, expected);
+ });
+}
+
+test('lookup state ignores a bound quick view after real serialization', async () => {
+ for (const surface of ['inline flags', 'fieldOptions']) for (const enabled of [true, false]) {
+ const spec = baseSpec();
+ const form = STATEFUL();
+ const lookup = 'new_customerid';
+ const context = `${surface}: ${enabled ? 'hidden and read-only' : 'explicit defaults'}`;
+ const flags = { hidden: enabled, readOnly: enabled, colspan: 1, rowspan: 1 };
+ form.tabs[1].columns[0].sections[0].fields.push(surface === 'inline flags' ? { name: lookup, ...flags } : lookup);
+ if (surface === 'fieldOptions') form.fieldOptions = { [lookup]: flags };
+ spec.forms = [form];
+ const xml = await compiledFormXml(spec, form, async (sdk, id) => {
+ const cell = ai.quickViewCellIntent({ quickViewClassId: QUICK_VIEW_CLASS_ID, lookupFieldName: lookup,
+ targetEntity: 'new_customer', quickViewFormId: '22222222-2222-4222-8222-222222222222', label: 'Customer' });
+ cell.visible = enabled;
+ cell.control.isReadOnly = !enabled;
+ // Earlier than the ordinary lookup and in a different section: without exclusion the Quick View
+ // supplies both the wrong placement and the opposite state, even though it binds the same field.
+ await sdk.addElement('form', id, '/tabs/0/columns/0/sections/0/rows', { cells: [cell] }, { position: { index: 0 } });
+ });
+ assert.strictEqual((xml.match(/datafieldname="new_customerid"/g) || []).length, 2, `${context}: both controls are really serialized`);
+ assert.match(xml, new RegExp(`classid="\\{${QUICK_VIEW_CLASS_ID}\\}"`, 'i'));
+ assert.match(xml, /QuickForms/);
+ const ordinaryAt = xml.search(/<section\b[^>]*\bname="sec_b1"/);
+ assert.ok(ordinaryAt > 0);
+ const quickViewXml = xml.slice(0, ordinaryAt);
+ assert.match(quickViewXml, /datafieldname="new_customerid"/, 'the Quick View precedes the ordinary lookup');
+ const good = await topologyVerdictForXml(spec, form, xml);
+ assert.ok(good);
+ assert.strictEqual(good.present, true, `${context}: ${good.detail}`);
+
+ const controls = enabled ? [
+ ['hidden', (cell, labels, control) => cell.replace(/visible="false"/, 'visible="true"') + labels + control,
+ /field 'new_customerid' is deployed with visible="true", the spec declares hidden: true/],
+ ['read-only', (cell, labels, control) => cell + labels + control.replace(/disabled="true"/, 'disabled="false"'),
+ /field 'new_customerid' is deployed with disabled="false", the spec declares readOnly: true/],
+ ] : [
+ // False state flags are deliberately no opinion. An explicitly declared default span supplies
+ // the ordinary-field negative control without incorrectly treating false as an unlock/unhide.
+ ['default span', (cell, labels, control) => cell.replace(/colspan="1"/, 'colspan="2"') + labels + control,
+ /field 'new_customerid' has colspan 2, the spec declares 1/],
+ ];
+ for (const [what, tamper, expected] of controls) {
+ const changed = quickViewXml + cellOf(lookup, tamper)(xml.slice(ordinaryAt));
+ assert.notStrictEqual(changed, xml, `${context}: the ordinary lookup's ${what} changes`);
+ assert.strictEqual(changed.slice(0, ordinaryAt), quickViewXml, 'the Quick View is untouched by the negative control');
+ const bad = await topologyVerdictForXml(spec, form, changed);
+ assert.strictEqual(bad.present, false, `${context}: the ordinary lookup's ${what} drift must fail`);
+ assert.match(bad.detail, expected);
+ }
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index 869f197bd..6eee05cff 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -2030,6 +2030,216 @@ test('verify PASSES when the field really is in the requested tab', async () =>
assert.strictEqual(chk.present, true, `a real relocation must verify; got ${chk && chk.detail}`);
});
+// --- Verify proves the ORDER, form-column WIDTHS and display STATE a layout declares ------------------
+//
+// Each of these deployed wrong and verified PASS: a form-column's width, a tab's or section's visibility,
+// expansion or label display, a field's hidden or read-only state, and the order of tabs and of the
+// sections in a form-column. The build converges every one of them, so each is now proven — against what
+// the COMPILER emits, so an undeclared width is the equal split and an undeclared flag is `true`.
+const attrsOf = (o) => Object.entries(o || {}).map(([k, v]) => ` ${k}="${v}"`).join('');
+const layoutXml = (tabs) => '<form><tabs>' + tabs.map((t) => `<tab name="${t.name}"${attrsOf(t.attrs)}><columns>`
+ + t.columns.map((c) => `<column width="${c.width}"><sections>`
+ + c.sections.map((s) => `<section name="${s.name}" columns="1"${attrsOf(s.attrs)}><rows>`
+ + (s.cells || []).map((cell) => `<row><cell${attrsOf(cell.attrs)}><control datafieldname="${cell.field}"${attrsOf(cell.control)} /></cell></row>`).join('')
+ + '</rows></section>').join('')
+ + '</sections></column>').join('')
+ + '</columns></tab>').join('') + '</tabs></form>';
+// TOPO_SPEC's form as deployed — tab_overview at 60%/40%, sec_left holding new_name, sec_right new_notes —
+// with every display flag absent unless a test sets it.
+const overview = (over = {}) => ({ name: 'tab_overview', attrs: over.tab, columns: [
+ { width: over.leftWidth || '60%', sections: [{ name: 'sec_left', attrs: over.left, cells: [{ field: 'new_name', attrs: over.nameCell, control: over.nameControl }] }] },
+ { width: over.rightWidth || '40%', sections: [{ name: 'sec_right', attrs: over.right, cells: [{ field: 'new_notes' }] }] },
+] });
+
+test('verify FAILS a form-column deployed at a width the spec does not declare', async () => {
+ const chk = await topoCheck(layoutXml([overview({ leftWidth: '10%', rightWidth: '90%' })]));
+ assert.strictEqual(chk.present, false);
+ assert.match(chk.detail, /tab_overview' form-column 1 is deployed 10% wide, the spec declares 60%/);
+ assert.match(chk.detail, /tab_overview' form-column 2 is deployed 90% wide, the spec declares 40%/);
+ const same = await topoCheck(layoutXml([overview()]));
+ assert.strictEqual(same.present, true, same.detail);
+});
+
+test('verify expects the compiler\'s equal split for a width the spec leaves out', async () => {
+ const undeclared = (spec) => { for (const c of spec.forms[0].tabs[0].columns) delete c.width; };
+ const split = await topoCheck(layoutXml([overview({ leftWidth: '50%', rightWidth: '50%' })]), undeclared);
+ assert.strictEqual(split.present, true, split.detail);
+ const chk = await topoCheck(layoutXml([overview()]), undeclared);
+ assert.strictEqual(chk.present, false);
+ assert.match(chk.detail, /form-column 1 is deployed 60% wide, the spec declares 50%/);
+});
+
+test('verify FAILS a tab or section whose display state differs from the spec', async () => {
+ const hideAll = (spec) => {
+ const t = spec.forms[0].tabs[0];
+ Object.assign(t, { visible: false, expanded: false });
+ Object.assign(t.columns[0].sections[0], { visible: false, showLabel: false });
+ };
+ // Every flag absent — the attributes a form nobody set them on carries — reads as the rendered default.
+ const chk = await topoCheck(layoutXml([overview()]), hideAll);
+ assert.strictEqual(chk.present, false);
+ for (const re of [
+ /tab 'tab_overview' is deployed with expanded="true" \(absent, the default\), the spec declares expanded: false/,
+ /tab 'tab_overview' is deployed with visible="true" \(absent, the default\), the spec declares visible: false/,
+ /section 'sec_left' is deployed with visible="true" \(absent, the default\), the spec declares visible: false/,
+ /section 'sec_left' is deployed with showlabel="true" \(absent, the default\), the spec declares showLabel: false/,
+ ]) assert.match(chk.detail, re);
+ const applied = await topoCheck(layoutXml([overview({ tab: { expanded: 'false', visible: 'false' }, left: { visible: 'false', showlabel: 'false' } })]), hideAll);
+ assert.strictEqual(applied.present, true, applied.detail);
+ // …and a spec that declares none of them expects a shown, expanded, labelled layout (xs:boolean "0" too).
+ const hidden = await topoCheck(layoutXml([overview({ tab: { visible: 'false' }, right: { showlabel: '0' } })]));
+ assert.strictEqual(hidden.present, false);
+ assert.match(hidden.detail, /tab 'tab_overview' is deployed with visible="false", the spec declares visible: true/);
+ assert.match(hidden.detail, /section 'sec_right' is deployed with showlabel="false", the spec declares showLabel: true/);
+});
+
+// FormXML booleans are xs:boolean — "1" and "0" are as valid as "true" and "false", and Dataverse writes either.
+test('verify reads xs:boolean "1" and "0" in a control\'s disabled state', async () => {
+ const readOnly = (spec) => { spec.forms[0].fieldOptions = { new_name: { readOnly: true } }; };
+ const one = await topoCheck(layoutXml([overview({ nameControl: { disabled: '1' } })]), readOnly);
+ assert.strictEqual(one.present, true, one.detail);
+ const zero = await topoCheck(layoutXml([overview({ nameControl: { disabled: '0' } })]), readOnly);
+ assert.strictEqual(zero.present, false);
+ assert.match(zero.detail, /field 'new_name' is deployed with disabled="false", the spec declares readOnly: true/);
+});
+
+// A quick view binds a lookup's datafieldname too, but it is not that field. Read as the field, it lent the field its
+// state and its section: a quick view placed FIRST made a correctly deployed form fail, and the opposite flags would
+// have passed a wrong one. Verify skips it, as the build does when it picks the cell to patch.
+test('verify reads a field\'s state and placement from the field, never from a quick view bound to it', async () => {
+ const QV = '{5C5600E0-1D6E-4205-A272-BE80DA87FD42}';
+ const form = (realName) => layoutXml([{ name: 'tab_overview', columns: [
+ { width: '60%', sections: [{ name: 'sec_left', cells: [
+ { field: 'new_notes', control: { classid: QV } },
+ { field: 'new_name', control: { classid: QV } },
+ { field: 'new_name', control: realName },
+ ] }] },
+ { width: '40%', sections: [{ name: 'sec_right', cells: [{ field: 'new_notes' }] }] },
+ ] }]);
+ const readOnly = (spec) => { spec.forms[0].tabs[0].columns[0].sections[0].fields = [{ name: 'new_name', readOnly: true }]; };
+ const ok = await topoCheck(form({ disabled: 'true' }), readOnly);
+ assert.strictEqual(ok.present, true, ok.detail);
+ // CONTROL — the real field still decides: editable, it fails, whatever the quick view says.
+ const bad = await topoCheck(form({ disabled: 'false' }), readOnly);
+ assert.strictEqual(bad.present, false);
+ assert.match(bad.detail, /field 'new_name' is deployed with disabled="false", the spec declares readOnly: true/);
+ assert.doesNotMatch(bad.detail, /new_notes/, 'the quick view bound to new_notes does not place new_notes in sec_left');
+ // An auto layout's field state is read the same way.
+ const auto = TOPO_SPEC();
+ auto.forms = [{ entity: 'new_ticket', name: 'Ticket Main', fieldOptions: { new_name: { readOnly: true } } }];
+ const state = async (xml) => ((await verifySpec(auto, topoRead(xml))).checks || []).find((c) => c.kind === 'form-field-state');
+ assert.strictEqual((await state(form({ disabled: 'true' }))).present, true);
+ assert.strictEqual((await state(form({ disabled: 'false' }))).present, false);
+});
+
+test('verify FAILS a field the spec declares hidden and read-only that deployed shown and editable', async () => {
+ const flagged = (spec) => { spec.forms[0].tabs[0].columns[0].sections[0].fields = [{ name: 'new_name', hidden: true, readOnly: true }]; };
+ const chk = await topoCheck(layoutXml([overview()]), flagged);
+ assert.strictEqual(chk.present, false);
+ assert.match(chk.detail, /field 'new_name' is deployed with visible="true" \(absent, the default\), the spec declares hidden: true/);
+ assert.match(chk.detail, /field 'new_name' is deployed with disabled="false" \(absent, the default\), the spec declares readOnly: true/);
+ const applied = await topoCheck(layoutXml([overview({ nameCell: { visible: 'false' }, nameControl: { disabled: 'true' } })]), flagged);
+ assert.strictEqual(applied.present, true, applied.detail);
+});
+
+test('verify proves a read-only flag declared through form-level fieldOptions on a plain entry', async () => {
+ const viaOptions = (spec) => { spec.forms[0].fieldOptions = { new_name: { readOnly: true } }; };
+ const chk = await topoCheck(layoutXml([overview()]), viaOptions);
+ assert.strictEqual(chk.present, false);
+ assert.match(chk.detail, /field 'new_name' .*readOnly: true/);
+ const applied = await topoCheck(layoutXml([overview({ nameControl: { disabled: 'true' } })]), viaOptions);
+ assert.strictEqual(applied.present, true, applied.detail);
+});
+
+test('verify FAILS tabs, or the sections of a form-column, deployed out of the layout\'s order', async () => {
+ const twoTabs = (spec) => { spec.forms[0].tabs.push({ name: 'tab_more', label: 'More', sections: [{ name: 'sec_more', label: 'M', fields: [] }] }); };
+ const more = { name: 'tab_more', columns: [{ width: '100%', sections: [{ name: 'sec_more' }] }] };
+ const chk = await topoCheck(layoutXml([more, overview()]), twoTabs);
+ assert.strictEqual(chk.present, false);
+ assert.match(chk.detail, /the tabs are deployed in the order tab_more, tab_overview; the spec orders them tab_overview, tab_more/);
+ const maker = { name: 'tab_maker', columns: [{ width: '100%', sections: [{ name: 'sec_maker' }] }] };
+ const inOrder = await topoCheck(layoutXml([overview(), maker, more]), twoTabs);
+ assert.strictEqual(inOrder.present, true, `a maker's own tab between them is not disorder; got ${inOrder.detail}`);
+
+ const twoSections = (spec) => { spec.forms[0].tabs[0].columns[0].sections.push({ name: 'sec_left2', label: 'L2', fields: [] }); };
+ const swapped = overview();
+ swapped.columns[0].sections.unshift({ name: 'sec_left2' });
+ const secChk = await topoCheck(layoutXml([swapped]), twoSections);
+ assert.strictEqual(secChk.present, false);
+ assert.match(secChk.detail, /the sections of tab 'tab_overview' form-column 1 are deployed in the order sec_left2, sec_left; the spec orders them sec_left, sec_left2/);
+ const ordered = overview();
+ ordered.columns[0].sections.push({ name: 'sec_left2' });
+ const secOrdered = await topoCheck(layoutXml([ordered]), twoSections);
+ assert.strictEqual(secOrdered.present, true, secOrdered.detail);
+});
+
+// An AUTO layout has no shape to prove, but its fieldOptions flags are asserted by the build on every
+// apply — so they are proven on their own, and an unreadable form is not proven.
+test('verify proves the read-only and hidden flags an AUTO layout declares in fieldOptions', async () => {
+ // new_notes is a declared column, so the auto layout places it — and the build asserts its flag.
+ const autoForm = (flags) => (spec) => {
+ spec.entities[0].columns = [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Text' }];
+ spec.forms = [{ entity: 'new_ticket', name: 'Ticket Main', fieldOptions: flags }];
+ };
+ const checks = async (xml, mutate, over) => {
+ const spec = TOPO_SPEC();
+ mutate(spec);
+ const res = await verifySpec(spec, topoRead(xml, over));
+ return { state: (res.checks || []).filter((c) => c.kind === 'form-field-state'), topo: (res.checks || []).filter((c) => c.kind === 'form-topology') };
+ };
+ const flags = autoForm({ new_name: { readOnly: true }, new_notes: { hidden: true } });
+ const bare = await checks(layoutXml([overview()]), flags);
+ assert.strictEqual(bare.topo.length, 0, 'an auto layout still has no topology to prove');
+ assert.strictEqual(bare.state.length, 1);
+ assert.strictEqual(bare.state[0].present, false);
+ assert.match(bare.state[0].detail, /field 'new_name' .*readOnly: true/);
+ assert.match(bare.state[0].detail, /field 'new_notes' .*hidden: true/);
+ const appliedXml = layoutXml([overview({ nameControl: { disabled: 'true' } })])
+ .replace('<cell><control datafieldname="new_notes"', '<cell visible="false"><control datafieldname="new_notes"');
+ const applied = await checks(appliedXml, flags);
+ assert.strictEqual(applied.state[0].present, true, applied.state[0].detail);
+ assert.strictEqual((await checks(layoutXml([overview()]), autoForm({ new_name: { after: 'new_notes' } }))).state.length, 0, 'nothing to prove without a flag');
+ const unreadable = await checks(null, flags, { formTopology: async () => { throw new Error('boom'); } });
+ assert.strictEqual(unreadable.state[0].present, false);
+ assert.match(unreadable.state[0].detail, /could not read/);
+});
+
+// The auto layout places every field it flags, so a flagged field the deployed form does not carry is a mismatch —
+// skipping it passed a form whose read-only field a maker had removed. A flag on a field the auto layout never
+// places is never written by the build, so it is not proven: checking it failed a stock field the build never touched.
+test('verify FAILS an auto layout\'s flagged field that is missing, and ignores a flag the build never writes', async () => {
+ const spec = (fieldOptions) => {
+ const s = TOPO_SPEC();
+ s.entities[0].columns = [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Text' }];
+ s.forms = [{ entity: 'new_ticket', name: 'Ticket Main', fieldOptions }];
+ return s;
+ };
+ const stateOf = async (s, xml) => ((await verifySpec(s, topoRead(xml))).checks || []).filter((c) => c.kind === 'form-field-state');
+ // new_notes is flagged and placed by the layout, but the deployed form only carries new_name.
+ const onlyName = layoutXml([{ name: 'tab_overview', columns: [{ width: '100%', sections: [{ name: 'sec_left', cells: [{ field: 'new_name', control: { disabled: 'true' } }] }] }] }]);
+ const missing = await stateOf(spec({ new_name: { readOnly: true }, new_notes: { hidden: true, readOnly: true } }), onlyName);
+ assert.strictEqual(missing.length, 1);
+ assert.strictEqual(missing[0].present, false);
+ assert.match(missing[0].detail, /field 'new_notes' is not on the deployed form, so its readOnly: true and hidden: true is not deployed/);
+ assert.doesNotMatch(missing[0].detail, /new_name/, 'the field that is there and locked passes');
+
+ // ownerid is not a field the auto layout places (not the primary, not a declared column, not a lookup), so the
+ // build never writes its flag: it is not proven — present and editable, or absent — and alone it adds no check.
+ const withOwner = layoutXml([overview({ nameControl: { disabled: 'true' } })]).replace('</rows></section></sections></column></columns>',
+ '<row><cell><control datafieldname="ownerid" /></cell></row></rows></section></sections></column></columns>');
+ const stock = await stateOf(spec({ new_name: { readOnly: true }, ownerid: { readOnly: true } }), withOwner);
+ assert.deepStrictEqual(stock.map((c) => c.present), [true], stock.map((c) => c.detail).join(' | '));
+ assert.deepStrictEqual(await stateOf(spec({ ownerid: { readOnly: true } }), withOwner), [], 'no flag the build writes, no check');
+
+ // A spec validation would refuse (a table with no primary column) cannot say which fields the layout places:
+ // reported as unverified, never a crash and never a pass.
+ const noPrimary = spec({ new_notes: { hidden: true } });
+ delete noPrimary.entities[0].primaryAttribute;
+ const unverified = await stateOf(noPrimary, withOwner);
+ assert.deepStrictEqual(unverified.map((c) => c.present), [false]);
+ assert.match(unverified[0].detail, /could not compile the layout to tell which fields the build places[\s\S]*unverified, not proven correct/);
+});
+
// --- #586 item 3: a deployed dashboard must be internally consistent, not merely present ----------
// A chart tile names a table, a view and a chart. The platform accepts and publishes a tile whose
// chart belongs to another table — and a same-named chart elsewhere made the build produce exactly
diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.json
index b1951cab1..0369b893b 100644
--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json
+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json
@@ -1,14 +1,14 @@
{
- "commit": "dac2cf1e3bed12ff733754e1045b95a1e4b180e2",
- "subject": "cds-maker-sdk: form-embed follow-ups — per-table tokens, edit after publish, embed conversion, SQL deadlock re-send, read-back adoption",
+ "commit": "8930278fa2da1ebb761496d4ef5a8079da9bc5fc",
+ "subject": "cds-maker-sdk: languages, app form lists, genPage type, header token, publish perf (combined)",
"dirtySdkPackage": 0,
- "libBuiltAt": "2026-09-30T01:00:29.443Z",
- "newestSrcAt": "2026-09-30T00:27:58.502Z",
+ "libBuiltAt": "2026-10-01T17:02:15.216Z",
+ "newestSrcAt": "2026-10-01T16:35:27.021Z",
"libIsStale": false,
"nostub": false,
"esbuildVersion": "0.28.1",
"nodeVersion": "v20.20.2",
- "builtAt": "2026-09-30T01:01:39.005Z",
- "bundleSha256": "e3bb276bd822c35609a18f3730d11e0430ca7cf38ea07f341c454f803f576b59",
- "bundleBytes": 818077
+ "builtAt": "2026-10-01T17:03:29.974Z",
+ "bundleSha256": "d06d95be213156070a1b89027881cc72e228aead217ccca94160177760fde8c1",
+ "bundleBytes": 843285
}
diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
index 16f3d8d3f..76c0625d7 100644
--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
@@ -25,33 +25,33 @@
}
globalThis.document=globalThis.document||globalThis.window.document;
})();
-var S1=Object.create;var hl=Object.defineProperty;var N1=Object.getOwnPropertyDescriptor;var D1=Object.getOwnPropertyNames;var I1=Object.getPrototypeOf,_1=Object.prototype.hasOwnProperty;var T=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},pn=(e,t)=>{for(var r in t)hl(e,r,{get:t[r],enumerable:!0})},ml=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of D1(t))!_1.call(e,i)&&i!==r&&hl(e,i,{get:()=>t[i],enumerable:!(n=N1(t,i))||n.enumerable});return e},qn=(e,t,r)=>(ml(e,t,"default"),r&&ml(r,t,"default")),ce=(e,t,r)=>(r=e!=null?S1(I1(e)):{},ml(t||!e||!e.__esModule?hl(r,"default",{value:e,enumerable:!0}):r,e)),Mr=e=>ml(hl({},"__esModule",{value:!0}),e);var Ai=y(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.DateTimeBehavior=D.PrecisionSource=D.StringFormatName=D.SourceType=D.ImeMode=D.SolutionEntityTypeCodeExtToComponentTypeCode=D.SolutionComponentTypeCodeToEntityTypeCodeExt=D.SolutionComponentVirtualAttributeSubtype=D.EntityTypeCode=D.SolutionComponentTypeCodeExt=D.RootComponentBehavior=D.SolutionComponentTypeCode=D.EntityKeyIndexStatus=D.ViewStateCode=D.ViewStatusCode=D.RelationshipSecurityTypes=D.CascadeType=D.RelationshipTypeExt=D.RelationshipType=D.AppSubType=D.BusinessProcessType=D.WorkflowCategory=D.WorkflowScope=D.WorkflowTypeCode=D.StatusCodeEnabledDisabled=D.StateCodeEnabledDisabled=D.StatusCode=D.StateCode=D.OptionSetType=D.AttributeTypeCodeNum=D.AttributeFormatName=D.AttributeFormatCode=D.AttributeTypeName=D.AttributeTypeCode=D.PluginSourceType=D.AuthType=D.PluginIsolationMode=D.ComponentState=D.ChartType=D.ChartsType=D.ViewType=D.AttributeType=D.ActivationState=D.FormPresentation=D.FormType=D.TableTypeCode=D.TableTypes=D.ActivityTypeMask=D.PrincipalType=D.OwnershipTypes=void 0;D.QueryType=D.KnownCustomSolutionComponentEntitySetName=D.TeamTypeEnum=D.EnvironmentVariableDefinitionTypeEnum=D.ConnectorTypeEnum=D.RoleInheritance=D.DefaultRoleTemplates=D.DeleteDependencyErrorCode=D.ServiceEndpointConnectionMode=D.ServiceEndpointContract=D.ServiceNamespaceFormat=D.ConnectionRoleCategory=D.ReportTypeCode=D.SdkMessageProcessingMode=D.SupportedDeployment=D.SdkMessageProcessingStage=D.WebResourceTypeCode=D.IntegerFormat=D.DateTimeFormat=void 0;var s0;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(s0||(D.OwnershipTypes=s0={}));var l0;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(l0||(D.PrincipalType=l0={}));var u0;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(u0||(D.ActivityTypeMask=u0={}));var c0;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(c0||(D.TableTypes=c0={}));var d0;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(d0||(D.TableTypeCode=d0={}));var p0;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(p0||(D.FormType=p0={}));var f0;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(f0||(D.FormPresentation=f0={}));var m0;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(m0||(D.ActivationState=m0={}));var h0;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(h0||(D.AttributeType=h0={}));var g0;(function(e){e[e.Public=0]="Public",e[e.AdvancedFind=1]="AdvancedFind",e[e.Associated=2]="Associated",e[e.QuickFind=4]="QuickFind",e[e.Lookup=64]="Lookup"})(g0||(D.ViewType=g0={}));var v0;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(v0||(D.ChartsType=v0={}));var y0;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(y0||(D.ChartType=y0={}));var b0;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(b0||(D.ComponentState=b0={}));var w0;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(w0||(D.PluginIsolationMode=w0={}));var A0;(function(e){e[e.BasicAuth=0]="BasicAuth"})(A0||(D.AuthType=A0={}));var E0;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(E0||(D.PluginSourceType=E0={}));var C0;(function(e){e.Boolean="Boolean",e.Customer="Customer",e.Date="Date",e.DateTime="DateTime",e.DateTimeNoTimeZone="DateTimeNoTimeZone",e.Decimal="Decimal",e.Double="Double",e.Integer="Integer",e.Lookup="Lookup",e.Memo="Memo",e.Money="Money",e.Owner="Owner",e.PartyList="PartyList",e.Picklist="Picklist",e.State="State",e.Status="Status",e.String="String",e.Uniqueidentifier="Uniqueidentifier",e.CalendarRules="CalendarRules",e.Virtual="Virtual",e.BigInt="BigInt",e.ManagedProperty="ManagedProperty",e.EntityName="EntityName"})(C0||(D.AttributeTypeCode=C0={}));var S0;(function(e){e.DateTimeType="DateTimeType",e.ImageType="ImageType",e.IntegerType="IntegerType",e.FileType="FileType",e.BooleanType="BooleanType",e.CustomerType="CustomerType",e.MemoType="MemoType",e.MultiSelectPicklistType="MultiSelectPicklistType",e.MoneyType="MoneyType",e.DecimalType="DecimalType",e.DoubleType="DoubleType",e.LookupType="LookupType",e.BigIntType="BigIntType",e.UniqueidentifierType="UniqueidentifierType",e.StringType="StringType",e.OwnerType="OwnerType",e.PicklistType="PicklistType",e.StateType="StateType",e.StatusType="StatusType",e.EntityNameType="EntityNameType"})(S0||(D.AttributeTypeName=S0={}));var N0;(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(N0||(D.AttributeFormatCode=N0={}));var D0;(function(e){e.Text="Text",e.TextArea="TextArea",e.Email="Email",e.Url="Url",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(D0||(D.AttributeFormatName=D0={}));var I0;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(I0||(D.AttributeTypeCodeNum=I0={}));var _0;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(_0||(D.OptionSetType=_0={}));var T0;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(T0||(D.StateCode=T0={}));var P0;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(P0||(D.StatusCode=P0={}));var R0;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(R0||(D.StateCodeEnabledDisabled=R0={}));var O0;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(O0||(D.StatusCodeEnabledDisabled=O0={}));var x0;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(x0||(D.WorkflowTypeCode=x0={}));var F0;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(F0||(D.WorkflowScope=F0={}));var L0;(function(e){e[e.Workflow=0]="Workflow",e[e.Dialog=1]="Dialog",e[e.BusinessRule=2]="BusinessRule",e[e.Action=3]="Action",e[e.BusinessProcessFlow=4]="BusinessProcessFlow",e[e.Flow=5]="Flow",e[e.UIFlow=6]="UIFlow"})(L0||(D.WorkflowCategory=L0={}));var k0;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(k0||(D.BusinessProcessType=k0={}));var M0;(function(e){e[e.CanvasApp=0]="CanvasApp",e[e.ComponentLibrary=1]="ComponentLibrary",e[e.CustomCanvasPage=2]="CustomCanvasPage",e[e.UnifiedApp=3]="UnifiedApp",e[e.CodeApp=4]="CodeApp",e[e.MobileApp=5]="MobileApp"})(M0||(D.AppSubType=M0={}));var B0;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(B0||(D.RelationshipType=B0={}));var U0;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(U0||(D.RelationshipTypeExt=U0={}));var $0;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})($0||(D.CascadeType=$0={}));var q0;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(q0||(D.RelationshipSecurityTypes=q0={}));var V0;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(V0||(D.ViewStatusCode=V0={}));var G0;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(G0||(D.ViewStateCode=G0={}));var z0;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(z0||(D.EntityKeyIndexStatus=z0={}));var W0;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.Tour=10061]="Tour"})(W0||(D.SolutionComponentTypeCode=W0={}));var j0;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(j0||(D.RootComponentBehavior=j0={}));var gl;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(gl||(D.SolutionComponentTypeCodeExt=gl={}));var vl;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(vl||(D.EntityTypeCode=vl={}));var H0;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(H0||(D.SolutionComponentVirtualAttributeSubtype=H0={}));function T1(e){let t=gl[e];return vl[t]}D.SolutionComponentTypeCodeToEntityTypeCodeExt=T1;function P1(e){let t=vl[e];return gl[t]}D.SolutionEntityTypeCodeExtToComponentTypeCode=P1;var K0;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(K0||(D.ImeMode=K0={}));var J0;(function(e){e[e.Simple=0]="Simple",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup",e[e.Formula=3]="Formula",e[e.Prompt=4]="Prompt"})(J0||(D.SourceType=J0={}));var Q0;(function(e){e.Email="Email",e.Phone="Phone",e.PhoneticGuide="PhoneticGuide",e.Text="Text",e.TextArea="TextArea",e.TickerSymbol="TickerSymbol",e.Url="Url",e.VersionNumber="VersionNumber"})(Q0||(D.StringFormatName=Q0={}));var X0;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(X0||(D.PrecisionSource=X0={}));var Y0;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Y0||(D.DateTimeBehavior=Y0={}));var Z0;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Z0||(D.DateTimeFormat=Z0={}));var ev;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(ev||(D.IntegerFormat=ev={}));var tv;(function(e){e[e.HTML=1]="HTML",e[e.CSS=2]="CSS",e[e.JScript=3]="JScript",e[e.XML=4]="XML",e[e.PNG=5]="PNG",e[e.JPG=6]="JPG",e[e.GIF=7]="GIF",e[e.Silverlight=8]="Silverlight",e[e.XSL=9]="XSL",e[e.ICO=10]="ICO",e[e.SVG=11]="SVG",e[e.RESX=12]="RESX"})(tv||(D.WebResourceTypeCode=tv={}));var rv;(function(e){e[e.Initial=5]="Initial",e[e.PreValidation=10]="PreValidation",e[e.InternalPreOperationBeforeExternal=15]="InternalPreOperationBeforeExternal",e[e.PreOperation=20]="PreOperation",e[e.InternalPreOperationAfterExternal=25]="InternalPreOperationAfterExternal",e[e.MainOperation=30]="MainOperation",e[e.InternalPostOperationBeforeExternal=35]="InternalPostOperationBeforeExternal",e[e.PostOperation=40]="PostOperation",e[e.InternalPostOperationAfterExternal=45]="InternalPostOperationAfterExternal",e[e.PostOperationDeprecated=50]="PostOperationDeprecated",e[e.FinalPostOperation=55]="FinalPostOperation"})(rv||(D.SdkMessageProcessingStage=rv={}));var nv;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(nv||(D.SupportedDeployment=nv={}));var iv;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(iv||(D.SdkMessageProcessingMode=iv={}));var av;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(av||(D.ReportTypeCode=av={}));var ov;(function(e){e[e.Business=1]="Business",e[e.Family=2]="Family",e[e.Social=3]="Social",e[e.Sales=4]="Sales",e[e.Other=5]="Other",e[e.Stakeholder=1e3]="Stakeholder",e[e.SalesTeam=1001]="SalesTeam",e[e.Service=1002]="Service"})(ov||(D.ConnectionRoleCategory=ov={}));var sv;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(sv||(D.ServiceNamespaceFormat=sv={}));var lv;(function(e){e[e.OneWay=1]="OneWay",e[e.Queue=2]="Queue",e[e.Rest=3]="Rest",e[e.TwoWay=4]="TwoWay",e[e.Topic=5]="Topic",e[e.PersistentQueue=6]="PersistentQueue",e[e.EventHub=7]="EventHub",e[e.WebHook=8]="WebHook"})(lv||(D.ServiceEndpointContract=lv={}));var uv;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(uv||(D.ServiceEndpointConnectionMode=uv={}));var cv;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(cv||(D.DeleteDependencyErrorCode=cv={}));var dv;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(dv||(D.DefaultRoleTemplates=dv={}));var pv;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(pv||(D.RoleInheritance=pv={}));var fv;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(fv||(D.ConnectorTypeEnum=fv={}));var mv;(function(e){e[e.String=1e8]="String",e[e.Number=100000001]="Number",e[e.Boolean=100000002]="Boolean",e[e.JSON=100000003]="JSON",e[e.ConnectionReference=100000004]="ConnectionReference",e[e.Secret=100000005]="Secret"})(mv||(D.EnvironmentVariableDefinitionTypeEnum=mv={}));var hv;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(hv||(D.TeamTypeEnum=hv={}));var gv;(function(e){e.Bots="bots"})(gv||(D.KnownCustomSolutionComponentEntitySetName=gv={}));var vv;(function(e){e[e.MainApplicationView=0]="MainApplicationView",e[e.AdvancedSearch=1]="AdvancedSearch",e[e.SubGrid=2]="SubGrid",e[e.QuickFindSearch=4]="QuickFindSearch",e[e.Reporting=8]="Reporting",e[e.OfflineFilters=16]="OfflineFilters",e[e.MASearch=32]="MASearch",e[e.LookupView=64]="LookupView",e[e.SMAppointmentBookView=128]="SMAppointmentBookView",e[e.OutlookFilters=256]="OutlookFilters",e[e.AddressBookFilters=512]="AddressBookFilters",e[e.SavedQueryTypeOther=2048]="SavedQueryTypeOther",e[e.InteractiveWorkflowView=4096]="InteractiveWorkflowView",e[e.OfflineTemplate=8192]="OfflineTemplate",e[e.OutlookTemplate=131072]="OutlookTemplate",e[e.CustomDefinedView=16384]="CustomDefinedView"})(vv||(D.QueryType=vv={}))});var te=y(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.IncompatibleWorkspaceError=re.PathTraversalError=re.AmbiguousArtifactError=re.JsonPointerError=re.NotImplementedError=re.WorkspaceNotInitializedError=re.ConnectionError=re.VersionConflictError=re.LocalEditsWouldBeLostError=re.StaleArtifactError=re.InvalidArgumentError=re.ValidationError=re.PathNotFoundError=re.ArtifactNotFoundError=re.readPartialTokens=re.withPartialTokens=re.SdkError=void 0;var ot=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};re.SdkError=ot;var yv=Symbol.for("cds-maker-sdk.partialWriteTokens");function R1(e,t){return typeof e=="object"&&e!==null&&(e[yv]=t),e}re.withPartialTokens=R1;function O1(e){let t=e;for(let r=0;t&&typeof t=="object"&&r<8;r++){let n=t[yv];if(n&&typeof n=="object")return n;t=t.cause}}re.readPartialTokens=O1;var xd=class extends ot{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};re.ArtifactNotFoundError=xd;var Fd=class extends ot{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};re.PathNotFoundError=Fd;var Ld=class extends ot{constructor(t,r,n,i){var a,o,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:
+var bx=Object.create;var El=Object.defineProperty;var wx=Object.getOwnPropertyDescriptor;var Ax=Object.getOwnPropertyNames;var Ex=Object.getPrototypeOf,Cx=Object.prototype.hasOwnProperty;var R=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},gn=(e,t)=>{for(var r in t)El(e,r,{get:t[r],enumerable:!0})},Al=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ax(t))!Cx.call(e,i)&&i!==r&&El(e,i,{get:()=>t[i],enumerable:!(n=wx(t,i))||n.enumerable});return e},Jn=(e,t,r)=>(Al(e,t,"default"),r&&Al(r,t,"default")),de=(e,t,r)=>(r=e!=null?bx(Ex(e)):{},Al(t||!e||!e.__esModule?El(r,"default",{value:e,enumerable:!0}):r,e)),$r=e=>Al(El({},"__esModule",{value:!0}),e);var Ti=b(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.DateTimeBehavior=D.PrecisionSource=D.StringFormatName=D.SourceType=D.ImeMode=D.SolutionEntityTypeCodeExtToComponentTypeCode=D.SolutionComponentTypeCodeToEntityTypeCodeExt=D.SolutionComponentVirtualAttributeSubtype=D.EntityTypeCode=D.SolutionComponentTypeCodeExt=D.RootComponentBehavior=D.SolutionComponentTypeCode=D.EntityKeyIndexStatus=D.ViewStateCode=D.ViewStatusCode=D.RelationshipSecurityTypes=D.CascadeType=D.RelationshipTypeExt=D.RelationshipType=D.AppSubType=D.BusinessProcessType=D.WorkflowCategory=D.WorkflowScope=D.WorkflowTypeCode=D.StatusCodeEnabledDisabled=D.StateCodeEnabledDisabled=D.StatusCode=D.StateCode=D.OptionSetType=D.AttributeTypeCodeNum=D.AttributeFormatName=D.AttributeFormatCode=D.AttributeTypeName=D.AttributeTypeCode=D.PluginSourceType=D.AuthType=D.PluginIsolationMode=D.ComponentState=D.ChartType=D.ChartsType=D.ViewType=D.AttributeType=D.ActivationState=D.FormPresentation=D.FormType=D.TableTypeCode=D.TableTypes=D.ActivityTypeMask=D.PrincipalType=D.OwnershipTypes=void 0;D.QueryType=D.KnownCustomSolutionComponentEntitySetName=D.TeamTypeEnum=D.EnvironmentVariableDefinitionTypeEnum=D.ConnectorTypeEnum=D.RoleInheritance=D.DefaultRoleTemplates=D.DeleteDependencyErrorCode=D.ServiceEndpointConnectionMode=D.ServiceEndpointContract=D.ServiceNamespaceFormat=D.ConnectionRoleCategory=D.ReportTypeCode=D.SdkMessageProcessingMode=D.SupportedDeployment=D.SdkMessageProcessingStage=D.WebResourceTypeCode=D.IntegerFormat=D.DateTimeFormat=void 0;var N0;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(N0||(D.OwnershipTypes=N0={}));var D0;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(D0||(D.PrincipalType=D0={}));var _0;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(_0||(D.ActivityTypeMask=_0={}));var I0;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(I0||(D.TableTypes=I0={}));var T0;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(T0||(D.TableTypeCode=T0={}));var P0;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(P0||(D.FormType=P0={}));var R0;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(R0||(D.FormPresentation=R0={}));var O0;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(O0||(D.ActivationState=O0={}));var x0;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(x0||(D.AttributeType=x0={}));var L0;(function(e){e[e.Public=0]="Public",e[e.AdvancedFind=1]="AdvancedFind",e[e.Associated=2]="Associated",e[e.QuickFind=4]="QuickFind",e[e.Lookup=64]="Lookup"})(L0||(D.ViewType=L0={}));var k0;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(k0||(D.ChartsType=k0={}));var F0;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(F0||(D.ChartType=F0={}));var M0;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(M0||(D.ComponentState=M0={}));var B0;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(B0||(D.PluginIsolationMode=B0={}));var $0;(function(e){e[e.BasicAuth=0]="BasicAuth"})($0||(D.AuthType=$0={}));var U0;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(U0||(D.PluginSourceType=U0={}));var q0;(function(e){e.Boolean="Boolean",e.Customer="Customer",e.Date="Date",e.DateTime="DateTime",e.DateTimeNoTimeZone="DateTimeNoTimeZone",e.Decimal="Decimal",e.Double="Double",e.Integer="Integer",e.Lookup="Lookup",e.Memo="Memo",e.Money="Money",e.Owner="Owner",e.PartyList="PartyList",e.Picklist="Picklist",e.State="State",e.Status="Status",e.String="String",e.Uniqueidentifier="Uniqueidentifier",e.CalendarRules="CalendarRules",e.Virtual="Virtual",e.BigInt="BigInt",e.ManagedProperty="ManagedProperty",e.EntityName="EntityName"})(q0||(D.AttributeTypeCode=q0={}));var V0;(function(e){e.DateTimeType="DateTimeType",e.ImageType="ImageType",e.IntegerType="IntegerType",e.FileType="FileType",e.BooleanType="BooleanType",e.CustomerType="CustomerType",e.MemoType="MemoType",e.MultiSelectPicklistType="MultiSelectPicklistType",e.MoneyType="MoneyType",e.DecimalType="DecimalType",e.DoubleType="DoubleType",e.LookupType="LookupType",e.BigIntType="BigIntType",e.UniqueidentifierType="UniqueidentifierType",e.StringType="StringType",e.OwnerType="OwnerType",e.PicklistType="PicklistType",e.StateType="StateType",e.StatusType="StatusType",e.EntityNameType="EntityNameType"})(V0||(D.AttributeTypeName=V0={}));var G0;(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(G0||(D.AttributeFormatCode=G0={}));var z0;(function(e){e.Text="Text",e.TextArea="TextArea",e.Email="Email",e.Url="Url",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(z0||(D.AttributeFormatName=z0={}));var W0;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(W0||(D.AttributeTypeCodeNum=W0={}));var j0;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(j0||(D.OptionSetType=j0={}));var H0;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(H0||(D.StateCode=H0={}));var K0;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(K0||(D.StatusCode=K0={}));var J0;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(J0||(D.StateCodeEnabledDisabled=J0={}));var Q0;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Q0||(D.StatusCodeEnabledDisabled=Q0={}));var X0;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(X0||(D.WorkflowTypeCode=X0={}));var Y0;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Y0||(D.WorkflowScope=Y0={}));var Z0;(function(e){e[e.Workflow=0]="Workflow",e[e.Dialog=1]="Dialog",e[e.BusinessRule=2]="BusinessRule",e[e.Action=3]="Action",e[e.BusinessProcessFlow=4]="BusinessProcessFlow",e[e.Flow=5]="Flow",e[e.UIFlow=6]="UIFlow"})(Z0||(D.WorkflowCategory=Z0={}));var ev;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(ev||(D.BusinessProcessType=ev={}));var tv;(function(e){e[e.CanvasApp=0]="CanvasApp",e[e.ComponentLibrary=1]="ComponentLibrary",e[e.CustomCanvasPage=2]="CustomCanvasPage",e[e.UnifiedApp=3]="UnifiedApp",e[e.CodeApp=4]="CodeApp",e[e.MobileApp=5]="MobileApp"})(tv||(D.AppSubType=tv={}));var rv;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(rv||(D.RelationshipType=rv={}));var nv;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(nv||(D.RelationshipTypeExt=nv={}));var iv;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(iv||(D.CascadeType=iv={}));var ov;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(ov||(D.RelationshipSecurityTypes=ov={}));var av;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(av||(D.ViewStatusCode=av={}));var sv;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(sv||(D.ViewStateCode=sv={}));var lv;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(lv||(D.EntityKeyIndexStatus=lv={}));var uv;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.Tour=10061]="Tour"})(uv||(D.SolutionComponentTypeCode=uv={}));var cv;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(cv||(D.RootComponentBehavior=cv={}));var Cl;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(Cl||(D.SolutionComponentTypeCodeExt=Cl={}));var Sl;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(Sl||(D.EntityTypeCode=Sl={}));var dv;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(dv||(D.SolutionComponentVirtualAttributeSubtype=dv={}));function Sx(e){let t=Cl[e];return Sl[t]}D.SolutionComponentTypeCodeToEntityTypeCodeExt=Sx;function Nx(e){let t=Sl[e];return Cl[t]}D.SolutionEntityTypeCodeExtToComponentTypeCode=Nx;var pv;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(pv||(D.ImeMode=pv={}));var fv;(function(e){e[e.Simple=0]="Simple",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup",e[e.Formula=3]="Formula",e[e.Prompt=4]="Prompt"})(fv||(D.SourceType=fv={}));var mv;(function(e){e.Email="Email",e.Phone="Phone",e.PhoneticGuide="PhoneticGuide",e.Text="Text",e.TextArea="TextArea",e.TickerSymbol="TickerSymbol",e.Url="Url",e.VersionNumber="VersionNumber"})(mv||(D.StringFormatName=mv={}));var hv;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(hv||(D.PrecisionSource=hv={}));var gv;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(gv||(D.DateTimeBehavior=gv={}));var vv;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(vv||(D.DateTimeFormat=vv={}));var yv;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(yv||(D.IntegerFormat=yv={}));var bv;(function(e){e[e.HTML=1]="HTML",e[e.CSS=2]="CSS",e[e.JScript=3]="JScript",e[e.XML=4]="XML",e[e.PNG=5]="PNG",e[e.JPG=6]="JPG",e[e.GIF=7]="GIF",e[e.Silverlight=8]="Silverlight",e[e.XSL=9]="XSL",e[e.ICO=10]="ICO",e[e.SVG=11]="SVG",e[e.RESX=12]="RESX"})(bv||(D.WebResourceTypeCode=bv={}));var wv;(function(e){e[e.Initial=5]="Initial",e[e.PreValidation=10]="PreValidation",e[e.InternalPreOperationBeforeExternal=15]="InternalPreOperationBeforeExternal",e[e.PreOperation=20]="PreOperation",e[e.InternalPreOperationAfterExternal=25]="InternalPreOperationAfterExternal",e[e.MainOperation=30]="MainOperation",e[e.InternalPostOperationBeforeExternal=35]="InternalPostOperationBeforeExternal",e[e.PostOperation=40]="PostOperation",e[e.InternalPostOperationAfterExternal=45]="InternalPostOperationAfterExternal",e[e.PostOperationDeprecated=50]="PostOperationDeprecated",e[e.FinalPostOperation=55]="FinalPostOperation"})(wv||(D.SdkMessageProcessingStage=wv={}));var Av;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(Av||(D.SupportedDeployment=Av={}));var Ev;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Ev||(D.SdkMessageProcessingMode=Ev={}));var Cv;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(Cv||(D.ReportTypeCode=Cv={}));var Sv;(function(e){e[e.Business=1]="Business",e[e.Family=2]="Family",e[e.Social=3]="Social",e[e.Sales=4]="Sales",e[e.Other=5]="Other",e[e.Stakeholder=1e3]="Stakeholder",e[e.SalesTeam=1001]="SalesTeam",e[e.Service=1002]="Service"})(Sv||(D.ConnectionRoleCategory=Sv={}));var Nv;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Nv||(D.ServiceNamespaceFormat=Nv={}));var Dv;(function(e){e[e.OneWay=1]="OneWay",e[e.Queue=2]="Queue",e[e.Rest=3]="Rest",e[e.TwoWay=4]="TwoWay",e[e.Topic=5]="Topic",e[e.PersistentQueue=6]="PersistentQueue",e[e.EventHub=7]="EventHub",e[e.WebHook=8]="WebHook"})(Dv||(D.ServiceEndpointContract=Dv={}));var _v;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(_v||(D.ServiceEndpointConnectionMode=_v={}));var Iv;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Iv||(D.DeleteDependencyErrorCode=Iv={}));var Tv;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Tv||(D.DefaultRoleTemplates=Tv={}));var Pv;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Pv||(D.RoleInheritance=Pv={}));var Rv;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Rv||(D.ConnectorTypeEnum=Rv={}));var Ov;(function(e){e[e.String=1e8]="String",e[e.Number=100000001]="Number",e[e.Boolean=100000002]="Boolean",e[e.JSON=100000003]="JSON",e[e.ConnectionReference=100000004]="ConnectionReference",e[e.Secret=100000005]="Secret"})(Ov||(D.EnvironmentVariableDefinitionTypeEnum=Ov={}));var xv;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(xv||(D.TeamTypeEnum=xv={}));var Lv;(function(e){e.Bots="bots"})(Lv||(D.KnownCustomSolutionComponentEntitySetName=Lv={}));var kv;(function(e){e[e.MainApplicationView=0]="MainApplicationView",e[e.AdvancedSearch=1]="AdvancedSearch",e[e.SubGrid=2]="SubGrid",e[e.QuickFindSearch=4]="QuickFindSearch",e[e.Reporting=8]="Reporting",e[e.OfflineFilters=16]="OfflineFilters",e[e.MASearch=32]="MASearch",e[e.LookupView=64]="LookupView",e[e.SMAppointmentBookView=128]="SMAppointmentBookView",e[e.OutlookFilters=256]="OutlookFilters",e[e.AddressBookFilters=512]="AddressBookFilters",e[e.SavedQueryTypeOther=2048]="SavedQueryTypeOther",e[e.InteractiveWorkflowView=4096]="InteractiveWorkflowView",e[e.OfflineTemplate=8192]="OfflineTemplate",e[e.OutlookTemplate=131072]="OutlookTemplate",e[e.CustomDefinedView=16384]="CustomDefinedView"})(kv||(D.QueryType=kv={}))});var re=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.IncompatibleWorkspaceError=Q.PathTraversalError=Q.AmbiguousArtifactError=Q.JsonPointerError=Q.NotImplementedError=Q.WorkspaceNotInitializedError=Q.ConnectionError=Q.VersionConflictError=Q.LocalEditsWouldBeLostError=Q.StaleArtifactError=Q.InvalidArgumentError=Q.ValidationError=Q.PathNotFoundError=Q.ArtifactNotFoundError=Q.readPartialEnrichment=Q.withPartialEnrichment=Q.readPartialTokens=Q.withPartialTokens=Q.SdkError=void 0;var at=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Q.SdkError=at;var Fv=Symbol.for("cds-maker-sdk.partialWriteTokens");function Dx(e,t){return typeof e=="object"&&e!==null&&(e[Fv]=t),e}Q.withPartialTokens=Dx;function _x(e){return Mv(e,Fv)}Q.readPartialTokens=_x;function Mv(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var Bv=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function Ix(e,t){return typeof e=="object"&&e!==null&&(e[Bv]=t),e}Q.withPartialEnrichment=Ix;function Tx(e){return Mv(e,Bv)}Q.readPartialEnrichment=Tx;var Vd=class extends at{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Q.ArtifactNotFoundError=Vd;var Gd=class extends at{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Q.PathNotFoundError=Gd;var zd=class extends at{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:
`+u.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`
-`)),this.type=t,this.id=r,this.issues=u,this.pointer=(o=(a=u[0])===null||a===void 0?void 0:a.pointer)!==null&&o!==void 0?o:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};re.ValidationError=Ld;var kd=class extends ot{constructor(t){super("INVALID_ARGUMENT",t)}};re.InvalidArgumentError=kd;var Md=class extends ot{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};re.StaleArtifactError=Md;var Bd=class extends ot{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};re.LocalEditsWouldBeLostError=Bd;var Ud=class extends ot{constructor(t,r,n,i,a){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${a?` ${a}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=a}};re.VersionConflictError=Ud;var $d=class extends ot{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};re.ConnectionError=$d;var qd=class extends ot{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};re.WorkspaceNotInitializedError=qd;var Vd=class extends ot{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};re.NotImplementedError=Vd;var Gd=class extends ot{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};re.JsonPointerError=Gd;var zd=class extends ot{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};re.AmbiguousArtifactError=zd;var Wd=class extends ot{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};re.PathTraversalError=Wd;var jd=class extends ot{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};re.IncompatibleWorkspaceError=jd});var ae=y(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.odataQuery=Ue.normalizeGuid=Ue.createSafeXmlElement=Ue.assertNoControlChars=Ue.assertODataName=Ue.assertXmlName=Ue.xmlText=Ue.odataPathLiteral=Ue.odataLiteral=void 0;var yl=te();function bv(e){return String(e??"").replace(/'/g,"''")}Ue.odataLiteral=bv;function x1(e){return encodeURIComponent(bv(e))}Ue.odataPathLiteral=x1;function F1(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}Ue.xmlText=F1;function wv(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(o=>n.test(o))&&!/^xmlns/i.test(r)))throw new yl.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Ue.assertXmlName=wv;function L1(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new yl.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Ue.assertODataName=L1;function k1(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new yl.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Ue.assertNoControlChars=k1;function M1(e,t,r){return e.createElement(wv(t,r))}Ue.createSafeXmlElement=M1;var B1=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function U1(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!B1.test(n))throw new yl.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Ue.normalizeGuid=U1;function $1(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Ue.odataQuery=$1});var be=y(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.nowIso=Q.isAlreadyDeleted=Q.deleteRecord=Q.resendDeadlockVictim=Q.DEADLOCK_BACKOFF_MS=Q.isSqlDeadlockVictim=Q.ensureSuccess=Q.resolveCreatedId=Q.requireCreatedId=Q.withClientMintedId=Q.readCreatedId=Q.readRowEtag=Q.readEtag=Q.requireEtag=Q.echoWrite=Q.UPDATE_NO_ETAG_CODE=Q.VERSION_CONFLICT_CODE=void 0;var sa=te(),la=ae();Q.VERSION_CONFLICT_CODE="VERSION_CONFLICT";Q.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function q1(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}Q.echoWrite=q1;function V1(e,t,r){if(!e)throw new sa.SdkError(Q.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': no concurrency token is held for it, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}Q.requireEtag=V1;function Av(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}Q.readEtag=Av;async function G1(e,t,r,n){let i=`/${t}(${n})${(0,la.odataQuery)([["$select",r]])}`;return Av(Kd(await e.get(i),e.apiUrl(i)))}Q.readRowEtag=G1;function Hd(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,la.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let a of Object.keys(i))if(a.toLowerCase()==="odata-entityid"){let o=/\(([0-9a-fA-F-]{36})\)/.exec(i[a]);if(o)return(0,la.normalizeGuid)(o[1],t)}return null}Q.readCreatedId=Hd;function z1(e,t,r){return r?{...e,[t]:(0,la.normalizeGuid)(r,t)}:e}Q.withClientMintedId=z1;function W1(e,t,r){let n=Hd(e,t);if(!n)throw new sa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}Q.requireCreatedId=W1;function j1(e,t,r,n){let i=Hd(e,t);if(i)return i;if(n)return(0,la.normalizeGuid)(n,t);throw new sa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}Q.resolveCreatedId=j1;function Kd(e,t){if(e.status===412)throw new sa.SdkError(Q.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new sa.ConnectionError(t,e.status,K1(e.body),e.body);return e}Q.ensureSuccess=Kd;function Ev(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}Q.isSqlDeadlockVictim=Ev;Q.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];async function H1(e){for(let t=0;;t+=1){let r=await e();if(t>=Q.DEADLOCK_BACKOFF_MS.length||!Ev(r))return r;await new Promise(n=>setTimeout(n,Q.DEADLOCK_BACKOFF_MS[t]))}}Q.resendDeadlockVictim=H1;function K1(e){if(typeof e=="string"&&e.length>0)return e;if(e!==null&&typeof e=="object"){let t=e;if(t.error&&typeof t.error.message=="string")return t.error.message;if(typeof t.Message=="string")return t.Message;if(typeof t.message=="string")return t.message}return"request failed"}async function J1(e,t,r,n){let i=(0,la.normalizeGuid)(r,"id"),a=`/${t}(${i})`;Kd(await e.delete(a,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(a))}Q.deleteRecord=J1;function Q1(e){return e instanceof sa.ConnectionError&&e.statusCode===404}Q.isAlreadyDeleted=Q1;function X1(){return new Date().toISOString()}Q.nowIso=X1});var Pt=y(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.describeMalformedValue=ua.collectPages=void 0;var Cv=be(),Jd=te();async function Y1(e,t,r,n,i){let a=[],o=new Set,s=e.apiUrl(t),l=(0,Cv.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Jd.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Qd(c)}; refusing to return partial results.`);for(let p of c)a.push(p);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new Jd.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${Qd(d)}); cannot follow it, and refusing to return partial results.`);if(o.has(d))throw new Jd.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);o.add(d),s=d,l=(0,Cv.ensureSuccess)(await e.getAbsolute(d,i),d)}return a}ua.collectPages=Y1;function Qd(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}ua.describeMalformedValue=Qd});var Xd=y(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.businessRuleApi=Br.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Br.WFOM_API_UNAVAILABLE_CODE=void 0;var fn=Ai(),Z1=Pt(),st=be(),Vn=ae(),wl=te();Br.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Br.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function Sv(e,t,r,n){let i=`/workflows(${rx})/Microsoft.Dynamics.CRM.${t}`;try{return(0,st.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(a){throw a?.statusCode!==404?a:new wl.SdkError(Br.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function ex(e,t){let r=`/workflows(${t})${(0,Vn.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,st.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function tx(e,t,r){let n=await ex(e,t);if(n===null||n.etag===null)throw new wl.SdkError(st.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new wl.SdkError(st.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var rx="00000000-0000-0000-0000-000000000000",bl={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},nx="workflowid,name,description,primaryentity,statecode,category,type",ix="category eq 2 and type eq 1";async function Nv(e,t,r){var n;if(r==="Draft")return null;let i=(0,Vn.normalizeGuid)(t,"workflowid"),a=r==="Active",o={statecode:a?fn.StateCode.Activated:fn.StateCode.Draft,statuscode:a?fn.StatusCode.Activated:fn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,st.ensureSuccess)(await e.patch(s,o,{headers:bl}),e.apiUrl(s));return(n=(0,st.readEtag)(l))!==null&&n!==void 0?n:await ko(e,i)}async function ko(e,t){let r=`/workflows(${t})${(0,Vn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,st.readEtag)(n):null}catch{return null}}async function ax(e,t,r){let n=await ko(e,t),i=await r(),a=(0,st.readEtag)(i);if(a)return{response:i,etag:a};let o=await ko(e,t);return{response:i,etag:n!==null&&n===o?o:null}}Br.businessRuleApi={async get(e,t){let r=(0,Vn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:a}=await ax(e,r,async()=>(0,st.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:a}},async list(e,t){let r=[ix];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Vn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Vn.odataQuery)([["$select",nx],["$filter",r.join(" and ")]])}`;return(await(0,Z1.collectPages)(e,n,"listArtifacts('businessRule')")).map(a=>{var o,s;return{type:"businessRule",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Vn.normalizeGuid)(n.Entity.workflowid,"workflowid"),a=await Sv(e,"CreateProcessWithWfomJson",n,bl),o=(0,st.resolveCreatedId)(a,"workflowid","business rule",i),s=null;try{s=await Nv(e,o,n.status)}catch(l){try{await(0,st.deleteRecord)(e,"workflows",o)}catch{}throw l}return{id:o,etag:(r=s??(0,st.readEtag)(a))!==null&&r!==void 0?r:await ko(e,o)}},async update(e,t,r,n){var i,a;let o=r,s=(0,Vn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...bl,"If-Match":(0,st.requireEtag)(n,"business rule",s)},c=await tx(e,s,u["If-Match"]),d=c.statecode===fn.StateCode.Activated;d&&(0,st.ensureSuccess)(await e.patch(l,{statecode:fn.StateCode.Draft,statuscode:fn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await Sv(e,"UpdateProcessWithWfomJson",o,u)}catch(m){if(d)try{(0,st.ensureSuccess)(await e.patch(l,{statecode:fn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:fn.StatusCode.Activated},{headers:bl}),e.apiUrl(l))}catch(h){throw new wl.SdkError(Br.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let f=await Nv(e,s,o.status);return{id:s,etag:(a=f??(0,st.readEtag)(p))!==null&&a!==void 0?a:await ko(e,s)}},delete(e,t){return(0,st.deleteRecord)(e,"workflows",t)}}});var ca=y(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});El.JsonPointer=void 0;var Kt=te(),Al=class e{static isReservedToken(t){return e.RESERVED_TOKENS.has(t)}static decodeToken(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}static encodeToken(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}static parse(t){if(t==="")return[];if(t[0]!=="/")throw new Kt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Kt.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let a of n)if(Array.isArray(i)){let o=e.toArrayIndex(a,i.length);if(o===void 0)return;i=i[o]}else if(i!==null&&typeof i=="object"){let o=i;if(e.isReservedToken(a)||!Object.prototype.hasOwnProperty.call(o,a))return;i=o[a]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Kt.JsonPointerError(r,"cannot set the document root");let{parent:a,lastToken:o}=e.resolveParent(t,i,r);if(Array.isArray(a)){let s=e.toArrayIndex(o,a.length);if(s===void 0)throw new Kt.JsonPointerError(r,`'${o}' is not a valid array index`);if(s>a.length)throw new Kt.JsonPointerError(r,`array index '${o}' is out of range`);a[s]=n}else{if(e.isReservedToken(o))throw new Kt.JsonPointerError(r,`refusing to write reserved property '${o}'`);a[o]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Kt.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:a}=e.resolveParent(t,n,r);if(Array.isArray(i)){let o=e.toArrayIndex(a,i.length);if(o===void 0||o>=i.length)throw new Kt.JsonPointerError(r,`array index '${a}' is out of range`);i.splice(o,1)}else{if(e.isReservedToken(a))throw new Kt.JsonPointerError(r,`refusing to remove reserved property '${a}'`);delete i[a]}}static add(t,r,n,i){let a=e.parse(r);if(a.length>0&&a[a.length-1]==="-"){let l=e.compile(a.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Kt.JsonPointerError(r,"add target must be an array");u.push(n);return}let o=e.resolve(t,r);if(!Array.isArray(o))throw new Kt.JsonPointerError(r,"add target must be an array");let s=i===void 0?o.length:i;if(s<0||s>o.length)throw new Kt.JsonPointerError(r,`insert index ${s} is out of range`);o.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],a=e.compile(r.slice(0,-1)),o=e.resolve(t,a);if(o===null||typeof o!="object")throw new Kt.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:o,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};El.JsonPointer=Al;Al.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var Iv=y(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.findElements=void 0;var Dv=ca();function ox(e,t){let r=[];return Yd(e,"",t,r),r}Cl.findElements=ox;function Yd(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,a)=>{Yd(i,Dv.JsonPointer.append(t,a),r,n)});else for(let i of Object.keys(e))Yd(e[i],Dv.JsonPointer.append(t,i),r,n)}});var Zd=y(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.assertMutationResult=Ur.assertExistsResult=Ur.assertReadResult=Ur.assertStorageContract=void 0;var sx=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],lx=["ensureContainer","exists"];function ux(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of sx)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of lx){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Ur.assertStorageContract=ux;function cx(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Ur.assertReadResult=cx;function dx(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Ur.assertExistsResult=dx;function px(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Ur.assertMutationResult=px});var ep=y(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.retryTransientIoAsync=da.retryTransientIo=void 0;var fx=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),mx=5,_v=10;function hx(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!Tv(r,t))throw r;vx(_v*t)}}da.retryTransientIo=hx;async function gx(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!Tv(r,t))throw r;await new Promise(n=>setTimeout(n,_v*t))}}da.retryTransientIoAsync=gx;function Tv(e,t){let r=e.code;return t<mx&&!!r&&fx.has(r)}function vx(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var xv=y(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.canonicalArtifactId=Jt.WorkspaceManager=Jt.WORKSPACE_SCHEMA_VERSION=Jt.retryTransientIo=void 0;var Ar=Zd(),Sl=te(),yx=ep();Object.defineProperty(Jt,"retryTransientIo",{enumerable:!0,get:function(){return yx.retryTransientIo}});function Pv(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Jt.WORKSPACE_SCHEMA_VERSION=1;var Gn={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},bx="manifest.json",Mo=".metadata",Rv="entities";function Ov(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}var tp=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Gn[t],`${Bo(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Mo,Gn[t],`${Bo(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Mo,Rv,`${t}.json`]}fsStore(){let t=Pv(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=Pv(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Gn[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Sl.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[bx]}async init(){if(this.storage.ensureContainer){let t=this.storage.ensureContainer.bind(this.storage),r=[[Mo,Rv]];for(let i of Object.keys(Gn))r.push([Gn[i]],[Mo,Gn[i]]);let n=await Promise.allSettled(r.map(i=>Ov(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Ar.assertMutationResult)(i.value,"ensureContainer")}}await this.withManifest(async()=>{if(await this.isInitialized())return;let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(t)})}async isInitialized(){return this.storage.exists?(0,Ar.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Ar.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!await this.isInitialized())throw new Sl.WorkspaceNotInitializedError(this.workspaceLabel)}async clean(){let t=Object.keys(Gn).map(i=>[Gn[i]]);t.push([Mo]);let r=await Promise.allSettled(t.map(i=>Ov(()=>this.storage.deleteByPrefix(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,Ar.assertMutationResult)(i.value,"deleteByPrefix")}let n=await this.getManifest();n.artifacts=[],n.lastSyncAt=void 0,await this.init(),await this.writeManifest(n)}async readArtifact(t,r){return await this.ensureInitialized(),this.readJson(this.artifactKey(t,r))}async writeArtifact(t,r,n){await this.ensureInitialized(),await this.writeJson(this.artifactKey(t,r),n),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Ar.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Ar.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Bo(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(a=>!(a.type===t&&a.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return this.readJson(this.metaKey(t,r))}async writeMeta(t,r,n){await this.writeJson(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJson(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJson(this.entityKey(t),r)}async getManifest(){await this.ensureInitialized();let t=await this.readJson(this.manifestKey);if(!t)throw new Sl.WorkspaceNotInitializedError(this.workspaceLabel);if(t.schemaVersion!==void 0&&t.schemaVersion>Jt.WORKSPACE_SCHEMA_VERSION)throw new Sl.IncompatibleWorkspaceError(t.schemaVersion,Jt.WORKSPACE_SCHEMA_VERSION);return t}async writeManifest(t){await this.writeJson(this.manifestKey,{...t,schemaVersion:Jt.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();await this.writeManifest({...r,...t})})}async upsertManifestEntry(t,r,n){await this.withManifest(async()=>{let i=await this.getManifest(),a=Bo(r),o=n,s=typeof o.name=="string"?o.name:`${t}:${a}`,l=typeof o.entityLogicalName=="string"?o.entityLogicalName:void 0,u=i.artifacts.find(c=>c.type===t&&c.id===a);u?(u.name=s,u.entityLogicalName=l):i.artifacts.push({type:t,id:a,name:s,entityLogicalName:l,isDirty:!1}),await this.writeManifest(i)})}async readJson(t){let r=(0,Ar.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJson(t,r){(0,Ar.assertMutationResult)(await this.storage.writeTextAtomic(t,`${JSON.stringify(r,null,2)}
-`),"writeTextAtomic")}async removeFile(t){(0,Ar.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return this.storage.exists?(0,Ar.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Ar.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}};Jt.WorkspaceManager=tp;function Bo(e){let r=/^\{?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Jt.canonicalArtifactId=Bo});var rp=y(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.deepEqual=pa.deepDiff=void 0;var wx=ca();function Ax(e,t){let r=[];return Lv(e,t,"",r,0),r}pa.deepDiff=Ax;var Nl=Symbol("missing"),Dl=512;function Lv(e,t,r,n,i){if(e===t)return;if(i>Dl)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Dl}`);let a=Il(e),o=Il(t);if(a&&o&&Array.isArray(e)===Array.isArray(t)){let s=Ex(e,t);for(let l of s){let u=Fv(e,l),c=Fv(t,l),d=wx.JsonPointer.append(r,l);u===Nl?n.push({pointer:d,type:"added",newValue:c}):c===Nl?n.push({pointer:d,type:"removed",oldValue:u}):Lv(u,c,d,n,i+1)}return}kv(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Il(e){return e!==null&&typeof e=="object"}function Ex(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let a=0;a<n;a++)i.push(String(a));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function Fv(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Nl}return t in e?e[t]:Nl}function kv(e,t){return Mv(e,t,0)}pa.deepEqual=kv;function Mv(e,t,r){if(e===t)return!0;if(r>Dl)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Dl}`);if(!Il(e)||!Il(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(a=>a in t&&Mv(e[a],t[a],r+1))}});var Uv=y(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.VersionManager=fa.PROJECTION_VERSION=void 0;var Bv=rp();fa.PROJECTION_VERSION=5;var np=class{constructor(t){this.workspace=t}async storeMeta(t,r,n){var i;let a=await this.getMeta(t,r),o=((i=n.snapshot)===null||i===void 0?void 0:i.status)==="Active",s=a?.everActivated===!0||o;await this.workspace.writeMeta(t,r,s?{...n,everActivated:s}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r){let n=await this.workspace.readArtifact(t,r);if(n===null)return!1;let i=await this.getMeta(t,r);return i?!(0,Bv.deepEqual)(i.snapshot,n):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),a;return n===null?a=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?a=(0,Bv.deepDiff)(i.snapshot,n):a=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:a}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};fa.VersionManager=np});var qv=y((ip,$v)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof ip=="object"?$v.exports=t():e.compareVersions=t()})(ip,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(a,o){return a.indexOf(o)===-1?a.length:a.indexOf(o)}function r(a){var o=a.replace(/^v/,"").replace(/\+.*$/,""),s=t(o,"-"),l=o.substring(0,s).split(".");return l.push(o.substring(s+1)),l}function n(a){return isNaN(Number(a))?a:Number(a)}function i(a){if(typeof a!="string")throw new TypeError("Invalid argument expected string");if(!e.test(a))throw new Error("Invalid argument not valid semver ('"+a+"' received)")}return function(o,s){[o,s].forEach(i);for(var l=r(o),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),p=parseInt(u[c]||0,10);if(d>p)return 1;if(p>d)return-1}var f=l[l.length-1],m=u[u.length-1];if(f&&m){var h=f.split(".").map(n),v=m.split(".").map(n);for(c=0;c<Math.max(h.length,v.length);c++){if(h[c]===void 0||typeof v[c]=="string"&&typeof h[c]=="number")return-1;if(v[c]===void 0||typeof h[c]=="string"&&typeof v[c]=="number"||h[c]>v[c])return 1;if(v[c]>h[c])return-1}}else if(f||m)return f?-1:1;return 0}})});var jv=y(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.EnvironmentFlowHostingType=Re.EnvironmentDisableReasonCode=Re.EnvironmentMigrationConstants=Re.EnvironmentProvisioningStates=Re.EnvironmentLocations=Re.EnvironmentCreationTypeConstants=Re.EnvironmentType=Re.EnvironmentSkuConstants=Re.environmentPermissions=Re.DatabaseType=void 0;var Vv;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Vv||(Re.DatabaseType=Vv={}));Re.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Re.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var Gv;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(Gv||(Re.EnvironmentType=Gv={}));Re.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Re.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Re.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Re.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var zv;(function(e){e.NotSpecified="NotSpecified",e.NoValidLicense="NoValidLicense",e.SuspendedLicense="SuspendedLicense",e.TrialExpiration="TrialExpiration",e.UserRequested="UserRequested",e.InstanceStateUpdate="InstanceStateUpdated",e.InactivityThreshold="InactivityThreshold",e.OperationsInitiated="OperationsInitiated",e.EnvironmentLifecycleOperation="EnvironmentLifecycleOperation",e.TenantPolicyEvaluation="TenantPolicyEvaluation"})(zv||(Re.EnvironmentDisableReasonCode=zv={}));var Wv;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(Wv||(Re.EnvironmentFlowHostingType=Wv={}))});var ey=y(S=>{"use strict";var Cx=S&&S.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(S,"__esModule",{value:!0});S.hasCommonDataServiceDatabase=S.getEnvironmentDiscoveryUrl=S.getEnvironmentWebApiUrl=S.getEnvironmentInstanceApiUrl=S.getEnvironmentLanguageCode=S.getEnvironmentUpdateCadence=S.checkVersions=S.isCds2EnvironmentVersionAtLeast=S.getSecurityOrConnectedGroupId=S.hasSecurityGroupId=S.doesCds2VersionSupportApiVersion9_1=S.doesCds2EnvironmentSupportApiVersion9_1=S.cdsVersionSupportingOSColorEdit=S.getEnvironmentDisplayName=S.getEnvironmentName=S.isEnvironmentInFirstReleaseCluster=S.isEnvironmentInPreprodCluster=S.isEnvironmentInTestCluster=S.isLiteEnvironmentUpgrading=S.isEnvironmentExpired=S.isEnvironmentInDeletedState=S.isEnvironmentInCreatingState=S.isDatabaseInProvisioningState=S.canUserCreateDatabase=S.isDisabledEnvironment=S.isDefaultEnvironment=S.isTrialEnvironment=S.isPlatformEnvironment=S.isTeamsEnvironment=S.isSandboxEnvironment=S.isProdEnvironment=S.isDevEnvironment=S.getEnvironmentType=S.getCrmInstanceName=S.getCrmInstanceUrl=S.getCrmAppDesignerUrl=S.getDevResourcesUrl=S.isEnvironmentInSuccessfulState=S.getAllThemesUrl=S.getAllPublishersUrl=S.getAllSolutionsUrl=S.getSecurityRolesUrl=S.getSecurityUsersUrl=S.environmentHasCds2Database=S.DEFAULT_SOLUTION_UNIQUE_NAME=S.DEFAULT_SOLUTION_ID=S.crmBapSolutionId=S.doesUserHavePermission=S.getLinkedEnvironmentMetadata=S.getCrmVersion=void 0;S.doesUserHaveFlowRunOnlyPermission=S.isUserPautoMakerWithoutDataAccess=S.isUserPautoMakerWithDataAccess=S.doesUserHaveCreateFlowPermission=S.equalsIgnoreCase=S.doesUserHaveCreateDatabasePermission=S.doesUserHaveDatabaseTablePermissions=S.isUserMakerWithoutDataAccess=S.isUserMakerWithDataAccess=S.doesUserHaveCreateAppPermission=S.doesUserHaveAdminPermission=void 0;var Sx=Cx(qv()),he=jv(),Uo=op();function Nx(e){let t=hn(e);return t&&t.version}S.getCrmVersion=Nx;function hn(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}S.getLinkedEnvironmentMetadata=hn;function mn(e,t){return e?!!e[t]:!1}S.doesUserHavePermission=mn;S.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";S.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";S.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ei(e){return!!hn(e)&&Hv(e)}S.environmentHasCds2Database=Ei;function Dx(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmAdminSecurityRolesUrl)(t)}return""}S.getSecurityUsersUrl=Dx;function Ix(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmAdminSecurityUsersUrl)(t)}return""}S.getSecurityRolesUrl=Ix;function _x(e){if(e&&Ei(e)){let t=zn(e);(0,Uo.getCrmAllSolutionsUrl)(t)}return""}S.getAllSolutionsUrl=_x;function Tx(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmAllPublishersUrl)(t)}return""}S.getAllPublishersUrl=Tx;function Px(e){return e&&Ei(e)?zn(e):""}S.getAllThemesUrl=Px;function Hv(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===he.EnvironmentProvisioningStates.Succeeded.toUpperCase()}S.isEnvironmentInSuccessfulState=Hv;function Rx(e){if(e&&Ei(e)){let t=zn(e);return(0,Uo.getCrmDevResourcesUrl)(t)}return""}S.getDevResourcesUrl=Rx;function Ox(e){return`${e}designer/app/{${S.crmBapSolutionId}}/CreateNewApp}}`}S.getCrmAppDesignerUrl=Ox;function zn(e){let t=hn(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}S.getCrmInstanceUrl=zn;function xx(e){let t=hn(e);return t?t.uniqueName:""}S.getCrmInstanceName=xx;function Fx(e){return hn(e)?he.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?he.EnvironmentType.CDS1:he.EnvironmentType.Empty}S.getEnvironmentType=Fx;function Lx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Developer}S.isDevEnvironment=Lx;function kx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Production}S.isProdEnvironment=kx;function Mx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Sandbox}S.isSandboxEnvironment=Mx;function $o(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Teams}S.isTeamsEnvironment=$o;function Bx(e){return e&&e.properties&&e.properties.environmentSku===he.EnvironmentSkuConstants.Platform}S.isPlatformEnvironment=Bx;var Ux=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===he.EnvironmentSkuConstants.Trial};S.isTrialEnvironment=Ux;function $x(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===he.EnvironmentCreationTypeConstants.DefaultTenant)}S.isDefaultEnvironment=$x;function qx(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}S.isDisabledEnvironment=qx;function Vx(e){return e&&e.properties&&mn(e.properties.permissions,he.environmentPermissions.CreateDatabase)}S.canUserCreateDatabase=Vx;function Gx(e){return!!(e&&e.properties&&e.properties.provisioningState&&Zv(e.properties.provisioningState,he.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}S.isDatabaseInProvisioningState=Gx;function zx(e){return!!e&&!!e.properties&&e.properties.provisioningState===he.EnvironmentProvisioningStates.Creating}S.isEnvironmentInCreatingState=zx;function Wx(e){return e&&e.properties&&(e.properties.provisioningState===he.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===he.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===he.EnvironmentProvisioningStates.FailedDeleting)}S.isEnvironmentInDeletedState=Wx;function jx(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}S.isEnvironmentExpired=jx;function Hx(e){return!!e&&!!e.properties&&!!e.properties.linkedEnvironmentMetadata&&e.properties.linkedEnvironmentMetadata.platformSku==="Lite"&&!!e.properties.states&&!!e.properties.states.management&&e.properties.states.management.id==="Running"&&!!e.properties.ongoingOperation&&!!e.properties.ongoingOperation.type&&e.properties.ongoingOperation.type.id==="Promote"}S.isLiteEnvironmentUpgrading=Hx;function Kx(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}S.isEnvironmentInTestCluster=Kx;function Jx(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}S.isEnvironmentInPreprodCluster=Jx;function Qx(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}S.isEnvironmentInFirstReleaseCluster=Qx;function Xx(e){return e&&e.name||""}S.getEnvironmentName=Xx;function Yx(e){return e&&e.properties&&e.properties.displayName||""}S.getEnvironmentDisplayName=Yx;var Kv="9.1.0.8202";S.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Zx(e){return Xv(e,Kv)}S.doesCds2EnvironmentSupportApiVersion9_1=Zx;function eF(e){return ap(e,Kv)}S.doesCds2VersionSupportApiVersion9_1=eF;function Jv(e){let t=hn(e);if(t)return t.securityGroupId}function Qv(e){return e&&e.properties&&e.properties.connectedGroups}function tF(e,t){let r=Qv(e);return!!r&&!!r.find(n=>n.id===t)||Jv(e)===t}S.hasSecurityGroupId=tF;function rF(e){let t=Qv(e);return t&&t.length>0&&t[0].id?t[0].id:Jv(e)}S.getSecurityOrConnectedGroupId=rF;function Xv(e,t){let r=e.version;return r?ap(r,t):!1}S.isCds2EnvironmentVersionAtLeast=Xv;function ap(e,t){return t?e?(0,Sx.default)(e,t)>=0:!1:!0}S.checkVersions=ap;function nF(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}S.getEnvironmentUpdateCadence=nF;function iF(e){let t=hn(e);return t?Number(t.baseLanguage):0}S.getEnvironmentLanguageCode=iF;function Yv(e){let t=hn(e);return t?t.instanceApiUrl:void 0}S.getEnvironmentInstanceApiUrl=Yv;function aF(e){let t=Yv(e);return t?t+"/api/data/v9.2":""}S.getEnvironmentWebApiUrl=aF;function oF(e){let t=zn(e);if(t==="")return"";let r=t.split("/");if(r.length!==4)return"";let n=r[2].split(".");return n[0]="globaldisco",r[2]=n.join("."),r.join("/")+"api/discovery/v2.0/Instances"}S.getEnvironmentDiscoveryUrl=oF;var sF=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===he.DatabaseType.CommonDataService};S.hasCommonDataServiceDatabase=sF;var lF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.AdminReadEnvironment)};S.doesUserHaveAdminPermission=lF;var uF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreatePowerApp)};S.doesUserHaveCreateAppPermission=uF;var cF=e=>(0,S.doesUserHaveAdminPermission)(e)&&(0,S.hasCommonDataServiceDatabase)(e)?!0:(0,S.doesUserHaveCreateAppPermission)(e)?$o(e)||(0,S.doesUserHaveDatabaseTablePermissions)(e):!1;S.isUserMakerWithDataAccess=cF;var dF=e=>(0,S.doesUserHaveCreateAppPermission)(e)&&!$o(e)&&!(0,S.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,S.doesUserHaveAdminPermission)(e)||!(0,S.hasCommonDataServiceDatabase)(e));S.isUserMakerWithoutDataAccess=dF;var pF=e=>[he.environmentPermissions.CreateDatabaseEntities,he.environmentPermissions.ListDatabaseEntities,he.environmentPermissions.UpdateDatabaseEntities,he.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return mn((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});S.doesUserHaveDatabaseTablePermissions=pF;var fF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreateDatabase)};S.doesUserHaveCreateDatabasePermission=fF;function Zv(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}S.equalsIgnoreCase=Zv;var mF=e=>{var t;return mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreateFlow)};S.doesUserHaveCreateFlowPermission=mF;var hF=e=>(0,S.doesUserHaveAdminPermission)(e)&&(0,S.hasCommonDataServiceDatabase)(e)?!0:(0,S.doesUserHaveCreateFlowPermission)(e)?$o(e)||(0,S.doesUserHaveDatabaseTablePermissions)(e):!1;S.isUserPautoMakerWithDataAccess=hF;var gF=e=>(0,S.doesUserHaveCreateFlowPermission)(e)&&!$o(e)&&!(0,S.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,S.doesUserHaveAdminPermission)(e)||!(0,S.hasCommonDataServiceDatabase)(e));S.isUserPautoMakerWithoutDataAccess=gF;var vF=e=>{var t,r;return!mn((t=e.properties)===null||t===void 0?void 0:t.permissions,he.environmentPermissions.CreateFlow)&&mn((r=e.properties)===null||r===void 0?void 0:r.permissions,he.environmentPermissions.ReadEnvironment)};S.doesUserHaveFlowRunOnlyPermission=vF});var op=y(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var ty=ey();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Vo;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Vo||(Vo={}));function yF(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=yF;function bF(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=bF;function wF(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=wF;function AF(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=AF;function EF(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=EF;function CF(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=CF;function sp(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function SF(e){return sp(e,Vo.AllSolutions)}A.getCrmAllSolutionsUrl=SF;function NF(e){return sp(e,Vo.AllPublishers)}A.getCrmAllPublishersUrl=NF;function DF(e){return sp(e,Vo.DevResources)}A.getCrmDevResourcesUrl=DF;function IF(e,t=ty.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=IF;function _F(e){return`${e}apps`}A.getCrmMyAppsUrl=_F;function TF(e){return ry(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=TF;function PF(e){return`${ry(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=PF;function ry(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function RF(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=RF;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function OF(e,t,r=ty.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=OF;function xF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=xF;function FF(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=FF;function LF(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=LF;function kF(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=kF;function MF(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=MF;function BF(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=BF;function UF(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=UF;function $F(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=$F;function qF(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=qF;function VF(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=VF;function GF(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=GF;function zF(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=zF;function WF(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=WF;function jF(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=jF;function HF(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=HF;function KF(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=KF;function JF(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=JF;function QF(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=QF;function XF(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=XF;function YF(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=YF;function ZF(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=ZF;function eL(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=eL;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function tL(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=tL;function rL(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=rL;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function nL(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=nL;function iL(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=iL;function aL(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=aL;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function oL(e,t,r,n=!1,i=!1,a=!1,o=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns
- ?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${a?"predeploymentstepnotes,":""}validationresults,${o?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value
+`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};Q.ValidationError=zd;var Wd=class extends at{constructor(t){super("INVALID_ARGUMENT",t)}};Q.InvalidArgumentError=Wd;var jd=class extends at{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};Q.StaleArtifactError=jd;var Hd=class extends at{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};Q.LocalEditsWouldBeLostError=Hd;var Kd=class extends at{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};Q.VersionConflictError=Kd;var Jd=class extends at{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};Q.ConnectionError=Jd;var Qd=class extends at{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Q.WorkspaceNotInitializedError=Qd;var Xd=class extends at{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Q.NotImplementedError=Xd;var Yd=class extends at{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Q.JsonPointerError=Yd;var Zd=class extends at{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};Q.AmbiguousArtifactError=Zd;var ep=class extends at{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};Q.PathTraversalError=ep;var tp=class extends at{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};Q.IncompatibleWorkspaceError=tp});var ae=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.odataQuery=Me.normalizeGuid=Me.createSafeXmlElement=Me.assertNoControlChars=Me.assertODataName=Me.assertXmlName=Me.xmlText=Me.odataPathLiteral=Me.odataLiteral=void 0;var Nl=re();function $v(e){return String(e??"").replace(/'/g,"''")}Me.odataLiteral=$v;function Px(e){return encodeURIComponent($v(e))}Me.odataPathLiteral=Px;function Rx(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}Me.xmlText=Rx;function Uv(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new Nl.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Me.assertXmlName=Uv;function Ox(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Nl.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Me.assertODataName=Ox;function xx(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Nl.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Me.assertNoControlChars=xx;function Lx(e,t,r){return e.createElement(Uv(t,r))}Me.createSafeXmlElement=Lx;var kx=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function Fx(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!kx.test(n))throw new Nl.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Me.normalizeGuid=Fx;function Mx(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Me.odataQuery=Mx});var be=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.nowIso=X.isAlreadyDeleted=X.deleteRecord=X.resendDeadlockVictim=X.DEADLOCK_BACKOFF_MS=X.isSqlDeadlockVictim=X.ensureSuccess=X.resolveCreatedId=X.requireCreatedId=X.withClientMintedId=X.readCreatedId=X.readRowEtag=X.readEtag=X.requireEtag=X.echoWrite=X.UPDATE_NO_ETAG_CODE=X.VERSION_CONFLICT_CODE=void 0;var go=re(),vo=ae();X.VERSION_CONFLICT_CODE="VERSION_CONFLICT";X.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function Bx(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}X.echoWrite=Bx;function $x(e,t,r){if(!e)throw new go.SdkError(X.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': no concurrency token is held for it, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}X.requireEtag=$x;function qv(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}X.readEtag=qv;async function Ux(e,t,r,n){let i=`/${t}(${n})${(0,vo.odataQuery)([["$select",r]])}`;return qv(np(await e.get(i),e.apiUrl(i)))}X.readRowEtag=Ux;function rp(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,vo.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,vo.normalizeGuid)(a[1],t)}return null}X.readCreatedId=rp;function qx(e,t,r){return r?{...e,[t]:(0,vo.normalizeGuid)(r,t)}:e}X.withClientMintedId=qx;function Vx(e,t,r){let n=rp(e,t);if(!n)throw new go.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}X.requireCreatedId=Vx;function Gx(e,t,r,n){let i=rp(e,t);if(i)return i;if(n)return(0,vo.normalizeGuid)(n,t);throw new go.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}X.resolveCreatedId=Gx;function np(e,t){if(e.status===412)throw new go.SdkError(X.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new go.ConnectionError(t,e.status,Wx(e.body),e.body);return e}X.ensureSuccess=np;function Vv(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}X.isSqlDeadlockVictim=Vv;X.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];async function zx(e){for(let t=0;;t+=1){let r=await e();if(t>=X.DEADLOCK_BACKOFF_MS.length||!Vv(r))return r;await new Promise(n=>setTimeout(n,X.DEADLOCK_BACKOFF_MS[t]))}}X.resendDeadlockVictim=zx;function Wx(e){if(typeof e=="string"&&e.length>0)return e;if(e!==null&&typeof e=="object"){let t=e;if(t.error&&typeof t.error.message=="string")return t.error.message;if(typeof t.Message=="string")return t.Message;if(typeof t.message=="string")return t.message}return"request failed"}async function jx(e,t,r,n){let i=(0,vo.normalizeGuid)(r,"id"),o=`/${t}(${i})`;np(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}X.deleteRecord=jx;function Hx(e){return e instanceof go.ConnectionError&&e.statusCode===404}X.isAlreadyDeleted=Hx;function Kx(){return new Date().toISOString()}X.nowIso=Kx});var Rt=b(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.describeMalformedValue=yo.collectPages=void 0;var Gv=be(),ip=re();async function Jx(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,Gv.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new ip.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${op(c)}; refusing to return partial results.`);for(let p of c)o.push(p);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new ip.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${op(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new ip.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,Gv.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}yo.collectPages=Jx;function op(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}yo.describeMalformedValue=op});var ap=b(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.businessRuleApi=Ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Ur.WFOM_API_UNAVAILABLE_CODE=void 0;var vn=Ti(),Qx=Rt(),st=be(),Qn=ae(),_l=re();Ur.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function zv(e,t,r,n){let i=`/workflows(${Zx})/Microsoft.Dynamics.CRM.${t}`;try{return(0,st.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new _l.SdkError(Ur.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function Xx(e,t){let r=`/workflows(${t})${(0,Qn.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,st.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function Yx(e,t,r){let n=await Xx(e,t);if(n===null||n.etag===null)throw new _l.SdkError(st.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new _l.SdkError(st.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var Zx="00000000-0000-0000-0000-000000000000",Dl={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},eL="workflowid,name,description,primaryentity,statecode,category,type",tL="category eq 2 and type eq 1";async function Wv(e,t,r){var n;if(r==="Draft")return null;let i=(0,Qn.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?vn.StateCode.Activated:vn.StateCode.Draft,statuscode:o?vn.StatusCode.Activated:vn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,st.ensureSuccess)(await e.patch(s,a,{headers:Dl}),e.apiUrl(s));return(n=(0,st.readEtag)(l))!==null&&n!==void 0?n:await ja(e,i)}async function ja(e,t){let r=`/workflows(${t})${(0,Qn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,st.readEtag)(n):null}catch{return null}}async function rL(e,t,r){let n=await ja(e,t),i=await r(),o=(0,st.readEtag)(i);if(o)return{response:i,etag:o};let a=await ja(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Ur.businessRuleApi={async get(e,t){let r=(0,Qn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await rL(e,r,async()=>(0,st.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[tL];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Qn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Qn.odataQuery)([["$select",eL],["$filter",r.join(" and ")]])}`;return(await(0,Qx.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Qn.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await zv(e,"CreateProcessWithWfomJson",n,Dl),a=(0,st.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await Wv(e,a,n.status)}catch(l){try{await(0,st.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,st.readEtag)(o))!==null&&r!==void 0?r:await ja(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,Qn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Dl,"If-Match":(0,st.requireEtag)(n,"business rule",s)},c=await Yx(e,s,u["If-Match"]),d=c.statecode===vn.StateCode.Activated;d&&(0,st.ensureSuccess)(await e.patch(l,{statecode:vn.StateCode.Draft,statuscode:vn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await zv(e,"UpdateProcessWithWfomJson",a,u)}catch(m){if(d)try{(0,st.ensureSuccess)(await e.patch(l,{statecode:vn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:vn.StatusCode.Activated},{headers:Dl}),e.apiUrl(l))}catch(h){throw new _l.SdkError(Ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let f=await Wv(e,s,a.status);return{id:s,etag:(o=f??(0,st.readEtag)(p))!==null&&o!==void 0?o:await ja(e,s)}},delete(e,t){return(0,st.deleteRecord)(e,"workflows",t)}}});var nr=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.publishBoundEntity=Qe.boundEntityPublishScope=Qe.publishGenPageById=Qe.publishDashboardById=Qe.publishWebResourceById=Qe.publishEntity=Qe.publishAppModule=Qe.publishXml=void 0;var jv=be(),Ha=ae(),Hv="/PublishXml";async function bo(e,t){(0,jv.ensureSuccess)(await(0,jv.resendDeadlockVictim)(()=>e.post(Hv,{ParameterXml:t})),e.apiUrl(Hv))}Qe.publishXml=bo;function nL(e,t){return bo(e,`<importexportxml><appmodules><appmodule>${(0,Ha.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Qe.publishAppModule=nL;function Kv(e,t){return bo(e,`<importexportxml><entities><entity>${(0,Ha.xmlText)(t)}</entity></entities></importexportxml>`)}Qe.publishEntity=Kv;function iL(e,t){return bo(e,`<importexportxml><webresources><webresource>${(0,Ha.xmlText)(t)}</webresource></webresources></importexportxml>`)}Qe.publishWebResourceById=iL;function oL(e,t){return bo(e,`<importexportxml><dashboards><dashboard>${(0,Ha.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Qe.publishDashboardById=oL;function aL(e,t){return bo(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Ha.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Qe.publishGenPageById=aL;function sL(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Qe.boundEntityPublishScope=sL;function lL(e,t){let r=t?.entityLogicalName;return r?Kv(e,r):Promise.resolve()}Qe.publishBoundEntity=lL});var wo=b(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.JsonPointer=void 0;var Kt=re(),Il=class e{static isReservedToken(t){return e.RESERVED_TOKENS.has(t)}static decodeToken(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}static encodeToken(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}static parse(t){if(t==="")return[];if(t[0]!=="/")throw new Kt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Kt.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Kt.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Kt.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Kt.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Kt.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Kt.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Kt.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Kt.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Kt.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Kt.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Kt.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Kt.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Tl.JsonPointer=Il;Il.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var Qv=b(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.findElements=void 0;var Jv=wo();function uL(e,t){let r=[];return sp(e,"",t,r),r}Pl.findElements=uL;function sp(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{sp(i,Jv.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))sp(e[i],Jv.JsonPointer.append(t,i),r,n)}});var lp=b(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.assertMutationResult=qr.assertExistsResult=qr.assertReadResult=qr.assertStorageContract=void 0;var cL=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],dL=["ensureContainer","exists"];function pL(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of cL)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of dL){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}qr.assertStorageContract=pL;function fL(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}qr.assertReadResult=fL;function mL(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}qr.assertExistsResult=mL;function hL(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}qr.assertMutationResult=hL});var up=b(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.retryTransientIoAsync=Ao.retryTransientIo=void 0;var gL=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),vL=5,Xv=10;function yL(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!Yv(r,t))throw r;wL(Xv*t)}}Ao.retryTransientIo=yL;async function bL(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!Yv(r,t))throw r;await new Promise(n=>setTimeout(n,Xv*t))}}Ao.retryTransientIoAsync=bL;function Yv(e,t){let r=e.code;return t<vL&&!!r&&gL.has(r)}function wL(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var ry=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.canonicalArtifactId=Jt.WorkspaceManager=Jt.WORKSPACE_SCHEMA_VERSION=Jt.retryTransientIo=void 0;var Cr=lp(),Rl=re(),AL=up();Object.defineProperty(Jt,"retryTransientIo",{enumerable:!0,get:function(){return AL.retryTransientIo}});function Zv(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Jt.WORKSPACE_SCHEMA_VERSION=1;var Xn={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},EL="manifest.json",Ka=".metadata",ey="entities";function ty(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}var cp=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Xn[t],`${Ja(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ka,Xn[t],`${Ja(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ka,ey,`${t}.json`]}fsStore(){let t=Zv(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=Zv(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Xn[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Rl.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[EL]}async init(){if(this.storage.ensureContainer){let t=this.storage.ensureContainer.bind(this.storage),r=[[Ka,ey]];for(let i of Object.keys(Xn))r.push([Xn[i]],[Ka,Xn[i]]);let n=await Promise.allSettled(r.map(i=>ty(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Cr.assertMutationResult)(i.value,"ensureContainer")}}await this.withManifest(async()=>{if(await this.isInitialized())return;let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(t)})}async isInitialized(){return this.storage.exists?(0,Cr.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Cr.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!await this.isInitialized())throw new Rl.WorkspaceNotInitializedError(this.workspaceLabel)}async clean(){let t=Object.keys(Xn).map(i=>[Xn[i]]);t.push([Ka]);let r=await Promise.allSettled(t.map(i=>ty(()=>this.storage.deleteByPrefix(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,Cr.assertMutationResult)(i.value,"deleteByPrefix")}let n=await this.getManifest();n.artifacts=[],n.lastSyncAt=void 0,await this.init(),await this.writeManifest(n)}async readArtifact(t,r){return await this.ensureInitialized(),this.readJson(this.artifactKey(t,r))}async writeArtifact(t,r,n){await this.ensureInitialized(),await this.writeJson(this.artifactKey(t,r),n),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Cr.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Cr.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ja(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return this.readJson(this.metaKey(t,r))}async writeMeta(t,r,n){await this.writeJson(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJson(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJson(this.entityKey(t),r)}async getManifest(){await this.ensureInitialized();let t=await this.readJson(this.manifestKey);if(!t)throw new Rl.WorkspaceNotInitializedError(this.workspaceLabel);if(t.schemaVersion!==void 0&&t.schemaVersion>Jt.WORKSPACE_SCHEMA_VERSION)throw new Rl.IncompatibleWorkspaceError(t.schemaVersion,Jt.WORKSPACE_SCHEMA_VERSION);return t}async writeManifest(t){await this.writeJson(this.manifestKey,{...t,schemaVersion:Jt.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();await this.writeManifest({...r,...t})})}async upsertManifestEntry(t,r,n){await this.withManifest(async()=>{let i=await this.getManifest(),o=Ja(r),a=n,s=typeof a.name=="string"?a.name:`${t}:${o}`,l=typeof a.entityLogicalName=="string"?a.entityLogicalName:void 0,u=i.artifacts.find(c=>c.type===t&&c.id===o);u?(u.name=s,u.entityLogicalName=l):i.artifacts.push({type:t,id:o,name:s,entityLogicalName:l,isDirty:!1}),await this.writeManifest(i)})}async readJson(t){let r=(0,Cr.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJson(t,r){(0,Cr.assertMutationResult)(await this.storage.writeTextAtomic(t,`${JSON.stringify(r,null,2)}
+`),"writeTextAtomic")}async removeFile(t){(0,Cr.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return this.storage.exists?(0,Cr.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Cr.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}};Jt.WorkspaceManager=cp;function Ja(e){let r=/^\{?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Jt.canonicalArtifactId=Ja});var dp=b(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.deepEqual=Eo.deepDiff=void 0;var CL=wo();function SL(e,t){let r=[];return iy(e,t,"",r,0),r}Eo.deepDiff=SL;var Ol=Symbol("missing"),xl=512;function iy(e,t,r,n,i){if(e===t)return;if(i>xl)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${xl}`);let o=Ll(e),a=Ll(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=NL(e,t);for(let l of s){let u=ny(e,l),c=ny(t,l),d=CL.JsonPointer.append(r,l);u===Ol?n.push({pointer:d,type:"added",newValue:c}):c===Ol?n.push({pointer:d,type:"removed",oldValue:u}):iy(u,c,d,n,i+1)}return}oy(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Ll(e){return e!==null&&typeof e=="object"}function NL(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function ny(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Ol}return t in e?e[t]:Ol}function oy(e,t){return ay(e,t,0)}Eo.deepEqual=oy;function ay(e,t,r){if(e===t)return!0;if(r>xl)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${xl}`);if(!Ll(e)||!Ll(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&ay(e[o],t[o],r+1))}});var ly=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.VersionManager=Co.PROJECTION_VERSION=void 0;var sy=dp();Co.PROJECTION_VERSION=5;var pp=class{constructor(t){this.workspace=t}async storeMeta(t,r,n){var i;let o=await this.getMeta(t,r),a=((i=n.snapshot)===null||i===void 0?void 0:i.status)==="Active",s=o?.everActivated===!0||a;await this.workspace.writeMeta(t,r,s?{...n,everActivated:s}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r){let n=await this.workspace.readArtifact(t,r);if(n===null)return!1;let i=await this.getMeta(t,r);return i?!(0,sy.deepEqual)(i.snapshot,n):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,sy.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};Co.VersionManager=pp});var cy=b((fp,uy)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof fp=="object"?uy.exports=t():e.compareVersions=t()})(fp,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),p=parseInt(u[c]||0,10);if(d>p)return 1;if(p>d)return-1}var f=l[l.length-1],m=u[u.length-1];if(f&&m){var h=f.split(".").map(n),g=m.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(f||m)return f?-1:1;return 0}})});var hy=b(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.EnvironmentFlowHostingType=Re.EnvironmentDisableReasonCode=Re.EnvironmentMigrationConstants=Re.EnvironmentProvisioningStates=Re.EnvironmentLocations=Re.EnvironmentCreationTypeConstants=Re.EnvironmentType=Re.EnvironmentSkuConstants=Re.environmentPermissions=Re.DatabaseType=void 0;var dy;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(dy||(Re.DatabaseType=dy={}));Re.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Re.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var py;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(py||(Re.EnvironmentType=py={}));Re.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Re.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Re.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Re.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var fy;(function(e){e.NotSpecified="NotSpecified",e.NoValidLicense="NoValidLicense",e.SuspendedLicense="SuspendedLicense",e.TrialExpiration="TrialExpiration",e.UserRequested="UserRequested",e.InstanceStateUpdate="InstanceStateUpdated",e.InactivityThreshold="InactivityThreshold",e.OperationsInitiated="OperationsInitiated",e.EnvironmentLifecycleOperation="EnvironmentLifecycleOperation",e.TenantPolicyEvaluation="TenantPolicyEvaluation"})(fy||(Re.EnvironmentDisableReasonCode=fy={}));var my;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(my||(Re.EnvironmentFlowHostingType=my={}))});var Cy=b(N=>{"use strict";var DL=N&&N.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(N,"__esModule",{value:!0});N.hasCommonDataServiceDatabase=N.getEnvironmentDiscoveryUrl=N.getEnvironmentWebApiUrl=N.getEnvironmentInstanceApiUrl=N.getEnvironmentLanguageCode=N.getEnvironmentUpdateCadence=N.checkVersions=N.isCds2EnvironmentVersionAtLeast=N.getSecurityOrConnectedGroupId=N.hasSecurityGroupId=N.doesCds2VersionSupportApiVersion9_1=N.doesCds2EnvironmentSupportApiVersion9_1=N.cdsVersionSupportingOSColorEdit=N.getEnvironmentDisplayName=N.getEnvironmentName=N.isEnvironmentInFirstReleaseCluster=N.isEnvironmentInPreprodCluster=N.isEnvironmentInTestCluster=N.isLiteEnvironmentUpgrading=N.isEnvironmentExpired=N.isEnvironmentInDeletedState=N.isEnvironmentInCreatingState=N.isDatabaseInProvisioningState=N.canUserCreateDatabase=N.isDisabledEnvironment=N.isDefaultEnvironment=N.isTrialEnvironment=N.isPlatformEnvironment=N.isTeamsEnvironment=N.isSandboxEnvironment=N.isProdEnvironment=N.isDevEnvironment=N.getEnvironmentType=N.getCrmInstanceName=N.getCrmInstanceUrl=N.getCrmAppDesignerUrl=N.getDevResourcesUrl=N.isEnvironmentInSuccessfulState=N.getAllThemesUrl=N.getAllPublishersUrl=N.getAllSolutionsUrl=N.getSecurityRolesUrl=N.getSecurityUsersUrl=N.environmentHasCds2Database=N.DEFAULT_SOLUTION_UNIQUE_NAME=N.DEFAULT_SOLUTION_ID=N.crmBapSolutionId=N.doesUserHavePermission=N.getLinkedEnvironmentMetadata=N.getCrmVersion=void 0;N.doesUserHaveFlowRunOnlyPermission=N.isUserPautoMakerWithoutDataAccess=N.isUserPautoMakerWithDataAccess=N.doesUserHaveCreateFlowPermission=N.equalsIgnoreCase=N.doesUserHaveCreateDatabasePermission=N.doesUserHaveDatabaseTablePermissions=N.isUserMakerWithoutDataAccess=N.isUserMakerWithDataAccess=N.doesUserHaveCreateAppPermission=N.doesUserHaveAdminPermission=void 0;var _L=DL(cy()),ge=hy(),Qa=hp();function IL(e){let t=bn(e);return t&&t.version}N.getCrmVersion=IL;function bn(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}N.getLinkedEnvironmentMetadata=bn;function yn(e,t){return e?!!e[t]:!1}N.doesUserHavePermission=yn;N.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";N.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";N.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Pi(e){return!!bn(e)&&gy(e)}N.environmentHasCds2Database=Pi;function TL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmAdminSecurityRolesUrl)(t)}return""}N.getSecurityUsersUrl=TL;function PL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmAdminSecurityUsersUrl)(t)}return""}N.getSecurityRolesUrl=PL;function RL(e){if(e&&Pi(e)){let t=Yn(e);(0,Qa.getCrmAllSolutionsUrl)(t)}return""}N.getAllSolutionsUrl=RL;function OL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmAllPublishersUrl)(t)}return""}N.getAllPublishersUrl=OL;function xL(e){return e&&Pi(e)?Yn(e):""}N.getAllThemesUrl=xL;function gy(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===ge.EnvironmentProvisioningStates.Succeeded.toUpperCase()}N.isEnvironmentInSuccessfulState=gy;function LL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmDevResourcesUrl)(t)}return""}N.getDevResourcesUrl=LL;function kL(e){return`${e}designer/app/{${N.crmBapSolutionId}}/CreateNewApp}}`}N.getCrmAppDesignerUrl=kL;function Yn(e){let t=bn(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}N.getCrmInstanceUrl=Yn;function FL(e){let t=bn(e);return t?t.uniqueName:""}N.getCrmInstanceName=FL;function ML(e){return bn(e)?ge.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?ge.EnvironmentType.CDS1:ge.EnvironmentType.Empty}N.getEnvironmentType=ML;function BL(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Developer}N.isDevEnvironment=BL;function $L(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Production}N.isProdEnvironment=$L;function UL(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Sandbox}N.isSandboxEnvironment=UL;function Xa(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Teams}N.isTeamsEnvironment=Xa;function qL(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Platform}N.isPlatformEnvironment=qL;var VL=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===ge.EnvironmentSkuConstants.Trial};N.isTrialEnvironment=VL;function GL(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===ge.EnvironmentCreationTypeConstants.DefaultTenant)}N.isDefaultEnvironment=GL;function zL(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}N.isDisabledEnvironment=zL;function WL(e){return e&&e.properties&&yn(e.properties.permissions,ge.environmentPermissions.CreateDatabase)}N.canUserCreateDatabase=WL;function jL(e){return!!(e&&e.properties&&e.properties.provisioningState&&Ey(e.properties.provisioningState,ge.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}N.isDatabaseInProvisioningState=jL;function HL(e){return!!e&&!!e.properties&&e.properties.provisioningState===ge.EnvironmentProvisioningStates.Creating}N.isEnvironmentInCreatingState=HL;function KL(e){return e&&e.properties&&(e.properties.provisioningState===ge.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===ge.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===ge.EnvironmentProvisioningStates.FailedDeleting)}N.isEnvironmentInDeletedState=KL;function JL(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}N.isEnvironmentExpired=JL;function QL(e){return!!e&&!!e.properties&&!!e.properties.linkedEnvironmentMetadata&&e.properties.linkedEnvironmentMetadata.platformSku==="Lite"&&!!e.properties.states&&!!e.properties.states.management&&e.properties.states.management.id==="Running"&&!!e.properties.ongoingOperation&&!!e.properties.ongoingOperation.type&&e.properties.ongoingOperation.type.id==="Promote"}N.isLiteEnvironmentUpgrading=QL;function XL(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}N.isEnvironmentInTestCluster=XL;function YL(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}N.isEnvironmentInPreprodCluster=YL;function ZL(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}N.isEnvironmentInFirstReleaseCluster=ZL;function ek(e){return e&&e.name||""}N.getEnvironmentName=ek;function tk(e){return e&&e.properties&&e.properties.displayName||""}N.getEnvironmentDisplayName=tk;var vy="9.1.0.8202";N.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function rk(e){return wy(e,vy)}N.doesCds2EnvironmentSupportApiVersion9_1=rk;function nk(e){return mp(e,vy)}N.doesCds2VersionSupportApiVersion9_1=nk;function yy(e){let t=bn(e);if(t)return t.securityGroupId}function by(e){return e&&e.properties&&e.properties.connectedGroups}function ik(e,t){let r=by(e);return!!r&&!!r.find(n=>n.id===t)||yy(e)===t}N.hasSecurityGroupId=ik;function ok(e){let t=by(e);return t&&t.length>0&&t[0].id?t[0].id:yy(e)}N.getSecurityOrConnectedGroupId=ok;function wy(e,t){let r=e.version;return r?mp(r,t):!1}N.isCds2EnvironmentVersionAtLeast=wy;function mp(e,t){return t?e?(0,_L.default)(e,t)>=0:!1:!0}N.checkVersions=mp;function ak(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}N.getEnvironmentUpdateCadence=ak;function sk(e){let t=bn(e);return t?Number(t.baseLanguage):0}N.getEnvironmentLanguageCode=sk;function Ay(e){let t=bn(e);return t?t.instanceApiUrl:void 0}N.getEnvironmentInstanceApiUrl=Ay;function lk(e){let t=Ay(e);return t?t+"/api/data/v9.2":""}N.getEnvironmentWebApiUrl=lk;function uk(e){let t=Yn(e);if(t==="")return"";let r=t.split("/");if(r.length!==4)return"";let n=r[2].split(".");return n[0]="globaldisco",r[2]=n.join("."),r.join("/")+"api/discovery/v2.0/Instances"}N.getEnvironmentDiscoveryUrl=uk;var ck=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===ge.DatabaseType.CommonDataService};N.hasCommonDataServiceDatabase=ck;var dk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.AdminReadEnvironment)};N.doesUserHaveAdminPermission=dk;var pk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreatePowerApp)};N.doesUserHaveCreateAppPermission=pk;var fk=e=>(0,N.doesUserHaveAdminPermission)(e)&&(0,N.hasCommonDataServiceDatabase)(e)?!0:(0,N.doesUserHaveCreateAppPermission)(e)?Xa(e)||(0,N.doesUserHaveDatabaseTablePermissions)(e):!1;N.isUserMakerWithDataAccess=fk;var mk=e=>(0,N.doesUserHaveCreateAppPermission)(e)&&!Xa(e)&&!(0,N.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,N.doesUserHaveAdminPermission)(e)||!(0,N.hasCommonDataServiceDatabase)(e));N.isUserMakerWithoutDataAccess=mk;var hk=e=>[ge.environmentPermissions.CreateDatabaseEntities,ge.environmentPermissions.ListDatabaseEntities,ge.environmentPermissions.UpdateDatabaseEntities,ge.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return yn((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});N.doesUserHaveDatabaseTablePermissions=hk;var gk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreateDatabase)};N.doesUserHaveCreateDatabasePermission=gk;function Ey(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}N.equalsIgnoreCase=Ey;var vk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreateFlow)};N.doesUserHaveCreateFlowPermission=vk;var yk=e=>(0,N.doesUserHaveAdminPermission)(e)&&(0,N.hasCommonDataServiceDatabase)(e)?!0:(0,N.doesUserHaveCreateFlowPermission)(e)?Xa(e)||(0,N.doesUserHaveDatabaseTablePermissions)(e):!1;N.isUserPautoMakerWithDataAccess=yk;var bk=e=>(0,N.doesUserHaveCreateFlowPermission)(e)&&!Xa(e)&&!(0,N.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,N.doesUserHaveAdminPermission)(e)||!(0,N.hasCommonDataServiceDatabase)(e));N.isUserPautoMakerWithoutDataAccess=bk;var wk=e=>{var t,r;return!yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreateFlow)&&yn((r=e.properties)===null||r===void 0?void 0:r.permissions,ge.environmentPermissions.ReadEnvironment)};N.doesUserHaveFlowRunOnlyPermission=wk});var hp=b(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.getRequiredComponentsQueryUrl=E.solutionComponentCountSummariesQueryUrl=E.solutionComponentSummariesQueryUrl=E.solutionComponentConfigurationsQueryUrl=E.chartsQueryUrl=E.workflowsQueryUrl=E.entityDefinitionsQueryUrl=E.solutionComponentDefinitionsQueryUrl=E.getCreateNewArticleTemplateUrl=E.getCreateNewPublisherUrl=E.getEnableSecurityRolesUrl=E.getArticleTemplateUrl=E.getFieldSecurityProfileDesignerUrl=E.getSecurityRoleDesignerUrl=E.getMailMergeTemplateDesignerUrl=E.getEmailTemplateDesignerUrl=E.getConnectionRoleDesignerUrl=E.getSiteMapDesignerUrl=E.getWebResourceFileUrl=E.getWebResourceDesignerUrl=E.getReportDesignerUrl=E.getBusinessProcessFlowDesignerUrl=E.getProcessShareUrl=E.getProcessDesignerUrl=E.getChartDesignerUrl=E.getOpenModernEntityDashboardUrl=E.getNewModernEntityDashboardUrl=E.getNewModernDashboardUrl=E.getOpenModernDashboardUrl=E.getDashboardDesignerUrl=E.getAppModuleDesignerUrl=E.privilegesQueryUrls=E.xrmApiUrl=E.getPlayAppModuleUrl=E.getCrmAdminSecurityUsersUrl=E.getCrmAdminSecurityRolesUrl=E.getCrmMyAppsUrl=E.getCrmAppDesignerUrl=E.getCrmDevResourcesUrl=E.getCrmAllPublishersUrl=E.getCrmAllSolutionsUrl=E.getSolutionPublisherUrl=E.getExportTranslationFileName=E.getExportSolutionTranslationUrl=E.getImportSolutionTranslationUrl=E.getShowSolutionDependenciesUrl=E.getShowComponentDependenciesUrl=E.cdsServiceUrl=E.ODATA_NEXT_LINK=E.ODATA_MAX_PAGE_SIZE=void 0;E.retrieveOrganizationResources=E.getUCIEntityRecordEditUrl=E.getUCIEntityRecordBaseUrl=E.getBusinessRuleDesignerUri=E.retrieveUnpublishedSuffix=E.getSavePowerSettingUri=E.getPowerSettingUri=E.getPowerSettingsUri=E.RetrievePlatform=E.getAppSettingOverrideUri=E.AppSettingOverrideName=E.getOrgSettingOverrideUri=E.OrgSettingOverrideName=E.getSettingDefinitionsUri=E.retrieveFeatureControlSettingsByNamespaceUrl=E.retrieveDeploymentPipelineConfigAppUrl=E.SPNPrincipalIdUrl=E.retrieveDeploymentEnvironmentInfoUrl=E.devSolutionInfoUrl=E.deployOperationStatusUrl=E.getAIGeneratedDeploymentNotesUrl=E.deploymentStageRunUrl=E.validatePackageAsyncUrl=E.deployPackageAsyncUrl=E.updateDeploymentStageRunUrl=E.createDeploymentStageRunUrl=E.retrieveDeploymentStagesUrl=E.retrievePipelinesUrl=E.retrieveDeploymentPipelineInfoUrl=E.getDeploymentStageRunsUrl=E.appDeploymentUrls=E.getProvisionLanguageUrl=E.getSolutionQueryUrl=E.getSolutionsByUniqueNameQueryUrl=E.solutionsQueryUrl=E.getDependentComponentsWithMetadataQueryUrl=void 0;var Sy=Cy();E.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";E.ODATA_NEXT_LINK="@odata.nextLink";E.cdsServiceUrl="https://cds-org/";var Za;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Za||(Za={}));function Ak(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}E.getShowComponentDependenciesUrl=Ak;function Ek(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}E.getShowSolutionDependenciesUrl=Ek;function Ck(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}E.getImportSolutionTranslationUrl=Ck;function Sk(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}E.getExportSolutionTranslationUrl=Sk;function Nk(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}E.getExportTranslationFileName=Nk;function Dk(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}E.getSolutionPublisherUrl=Dk;function gp(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function _k(e){return gp(e,Za.AllSolutions)}E.getCrmAllSolutionsUrl=_k;function Ik(e){return gp(e,Za.AllPublishers)}E.getCrmAllPublishersUrl=Ik;function Tk(e){return gp(e,Za.DevResources)}E.getCrmDevResourcesUrl=Tk;function Pk(e,t=Sy.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}E.getCrmAppDesignerUrl=Pk;function Rk(e){return`${e}apps`}E.getCrmMyAppsUrl=Rk;function Ok(e){return Ny(e,"role")+"&forceUCI=0"}E.getCrmAdminSecurityRolesUrl=Ok;function xk(e){return`${Ny(e,"systemuser")}&forceclassic=1`}E.getCrmAdminSecurityUsersUrl=xk;function Ny(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function Lk(e,t){return`${e}main.aspx?appid=${t}`}E.getPlayAppModuleUrl=Lk;E.xrmApiUrl="api/data/v9.0";E.privilegesQueryUrls={systemUserInfo:e=>`${e}${E.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${E.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${E.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function kk(e,t,r=Sy.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}E.getAppModuleDesignerUrl=kk;function Fk(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}E.getDashboardDesignerUrl=Fk;function Mk(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}E.getOpenModernDashboardUrl=Mk;function Bk(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}E.getNewModernDashboardUrl=Bk;function $k(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}E.getNewModernEntityDashboardUrl=$k;function Uk(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}E.getOpenModernEntityDashboardUrl=Uk;function qk(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}E.getChartDesignerUrl=qk;function Vk(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getProcessDesignerUrl=Vk;function Gk(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getProcessShareUrl=Gk;function zk(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}E.getBusinessProcessFlowDesignerUrl=zk;function Wk(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}E.getReportDesignerUrl=Wk;function jk(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}E.getWebResourceDesignerUrl=jk;function Hk(e,t){return`${e}WebResources/${t}`}E.getWebResourceFileUrl=Hk;function Kk(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}E.getSiteMapDesignerUrl=Kk;function Jk(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getConnectionRoleDesignerUrl=Jk;function Qk(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getEmailTemplateDesignerUrl=Qk;function Xk(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getMailMergeTemplateDesignerUrl=Xk;function Yk(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getSecurityRoleDesignerUrl=Yk;function Zk(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getFieldSecurityProfileDesignerUrl=Zk;function eF(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}E.getArticleTemplateUrl=eF;function tF(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}E.getEnableSecurityRolesUrl=tF;function rF(e){return`${e}tools/publisher/edit.aspx`}E.getCreateNewPublisherUrl=rF;function nF(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}E.getCreateNewArticleTemplateUrl=nF;E.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";E.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";E.workflowsQueryUrl="api/data/v9.0/workflows";E.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";E.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";E.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";E.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function iF(e,t){return`${E.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}E.getRequiredComponentsQueryUrl=iF;function oF(e,t){return`${E.cdsServiceUrl}${E.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}E.getDependentComponentsWithMetadataQueryUrl=oF;E.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function aF(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}E.getSolutionsByUniqueNameQueryUrl=aF;function sF(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}E.getSolutionQueryUrl=sF;function lF(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}E.getProvisionLanguageUrl=lF;E.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function uF(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns
+ ?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value
&$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}
&$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))
- &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=oL;function sL(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=sL;function lL(e){return`/api/data/v9.0/deploymentenvironments
+ &$orderby=starttime desc`}E.getDeploymentStageRunsUrl=uF;function cF(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}E.retrieveDeploymentPipelineInfoUrl=cF;function dF(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
&$expand=deploymentpipeline_deploymentenvironment($select=name,description,deploymentpipelineid;$orderby=name asc)
- &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=lL;function uL(e){return`/api/data/v9.0/deploymentstages
+ &$filter=(environmentid eq '${e}')`}E.retrievePipelinesUrl=dF;function pF(e){return`/api/data/v9.0/deploymentstages
?$filter=(_deploymentpipelineid_value eq ${e})
&$select=name,description,deploymentstageid,_previousdeploymentstageid_value
- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=uL;function cL(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=cL;function dL(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=dL;function pL(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=pL;function fL(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=fL;function mL(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=mL;function hL(e){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=hL;function gL(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns
+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}E.retrieveDeploymentStagesUrl=pF;function fF(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}E.createDeploymentStageRunUrl=fF;function mF(e){return`/api/data/v9.0/deploymentstageruns(${e})`}E.updateDeploymentStageRunUrl=mF;function hF(){return"/api/data/v9.0/DeployPackageAsync"}E.deployPackageAsyncUrl=hF;function gF(){return"/api/data/v9.0/ValidatePackageAsync"}E.validatePackageAsyncUrl=gF;function vF(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}E.deploymentStageRunUrl=vF;function yF(e){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}E.getAIGeneratedDeploymentNotesUrl=yF;function bF(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns
?$filter=(${t})
- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=gL;function vL(e){return`/api/data/v9.0/solutions(${e})
- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=vL;function yL(e){return`/api/data/v9.0/deploymentenvironments
+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}E.deployOperationStatusUrl=bF;function wF(e){return`/api/data/v9.0/solutions(${e})
+ ?$select=solutionid,uniquename,version`}E.devSolutionInfoUrl=wF;function AF(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=yL;var bL=e=>`/api/data/v9.0/systemusers
+ &$filter=(environmentid eq '${e}')`}E.retrieveDeploymentEnvironmentInfoUrl=AF;var EF=e=>`/api/data/v9.0/systemusers
?$select=azureactivedirectoryobjectid
- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=bL;function wL(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=wL;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function AL(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=AL;A.OrgSettingOverrideName="organizationsettings";function EL(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=EL;A.AppSettingOverrideName="appsettings";function CL(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=CL;var qo;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(qo||(A.RetrievePlatform=qo={}));function SL(e,t,r,n=qo.All,i=!1){let a=[];e&&a.push(`AppUniqueName='${e}'`),t!=null&&a.push(`ReleaseLevel=${t}`),r&&a.push(`RetrieveHiddenSettings=${r}`),n!==qo.All&&a.push(`RetrievePlatformSettings=${n===qo.IsPlatformOnly?1:0}`);let o="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return a.length&&(o=`${o}(${a.join(",")})`),i?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingsUri=SL;function NL(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let a="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(a=`${a}(${i.join(",")})`),n?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingUri=NL;function DL(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=DL;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function IL(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=IL;function ny({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=ny;function _L({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||ny({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=_L;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var ay=y(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.DataverseClient=void 0;var TL=op(),Ci=te(),iy=be(),lp=class{constructor(t,r,n){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${TL.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Ci.SdkError?n:new Ci.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return(0,iy.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,r)))}getAbsolute(t,r){return this.assertSameOrigin(t),(0,iy.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,r)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Ci.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Ci.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Ci.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),a={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,a))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new Ci.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new Ci.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};_l.DataverseClient=lp});var oy=y(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.findColumns=Wn.findTables=Wn.fetchEntityMetadataFromApi=void 0;var cp=be(),ir=ae();function $r(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function ma(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function Go(e,t){return(await dp(e,t)).rows}async function dp(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function qr(e){return`/EntityDefinitions(LogicalName='${(0,ir.odataPathLiteral)(e)}')`}async function PL(e,t,r){let n=await Go(e,`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let a=r.get(i.LogicalName);a&&typeof i.MaxLength=="number"&&(a.maxLength=i.MaxLength)}}async function RL(e,t,r){var n;let i=await Go(e,`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`);for(let a of i){let o=r.get(a.LogicalName);o&&(!((n=a.OptionSet)===null||n===void 0)&&n.Options)&&(o.options=a.OptionSet.Options.map(s=>{var l;return{value:(l=s.Value)!==null&&l!==void 0?l:0,label:$r(s.Label),...ma(s.Label)?{localizedLabel:ma(s.Label)}:{}}}))}}function up(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:$r(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function OL(e,t){var r;let n=l=>dp(e,l).catch(()=>({rows:[],ok:!1})),i=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all(i.map(l=>n(`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.${l}${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))),o=new Map;for(let{rows:l}of a)for(let u of l)!((r=u.OptionSet)===null||r===void 0)&&r.Options&&o.set(u.LogicalName,u.OptionSet.Options.map(up));let s=await n(`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let l of s.rows){let u=l.OptionSet;u?.TrueOption&&u.FalseOption&&o.set(l.LogicalName,[up(u.FalseOption),up(u.TrueOption)])}return{byColumn:o,complete:s.ok&&a.every(l=>l.ok)}}async function xL(e,t,r){let{rows:n,ok:i}=await dp(e,`${qr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let a of n){let o=r.get(a.LogicalName);o&&a.Targets&&(o.targets=a.Targets)}return i}async function FL(e,t){var r,n,i,a;let o=[],s=await Go(e,`${qr(t)}/OneToManyRelationships${(0,ir.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)o.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await Go(e,`${qr(t)}/ManyToOneRelationships${(0,ir.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)o.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(a=c.ReferencedAttribute)!==null&&a!==void 0?a:""});let u=await Go(e,`${qr(t)}/ManyToManyRelationships${(0,ir.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;o.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return o}async function LL(e,t){var r,n,i,a,o;let s=`${qr(t)}`+(0,ir.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,cp.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(h=>{var v,b,E;return{logicalName:h.LogicalName,displayName:$r(h.DisplayName),...ma(h.DisplayName)?{localizedDisplayName:ma(h.DisplayName)}:{},attributeType:(v=h.AttributeType)!==null&&v!==void 0?v:"Unknown",isCustomAttribute:!!h.IsCustomAttribute,attributeTypeName:(E=(b=h.AttributeTypeName)===null||b===void 0?void 0:b.Value)!==null&&E!==void 0?E:"",...typeof h.IsValidForUpdate=="boolean"?{isValidForUpdate:h.IsValidForUpdate}:{},...typeof h.IsValidForRead=="boolean"?{isValidForRead:h.IsValidForRead}:{},...h.AttributeOf?{attributeOf:h.AttributeOf}:{},...$r(h.Description)?{description:$r(h.Description)}:{}}}),d=new Map(c.map(h=>[h.logicalName,h])),[,,p,f,m]=await Promise.all([PL(e,t,d),RL(e,t,d),OL(e,t),xL(e,t,d),FL(e,t)]);for(let h of c){let v=p.byColumn.get(h.logicalName);v&&(h.choices=v)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:$r(u.DisplayName),...ma(u.DisplayName)?{localizedDisplayName:ma(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(a=u.PrimaryNameAttribute)!==null&&a!==void 0?a:"",primaryIdAttribute:(o=u.PrimaryIdAttribute)!==null&&o!==void 0?o:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...$r(u.Description)?{description:$r(u.Description)}:{},columnDetailComplete:p.complete&&f,attributes:c,relationships:m}}Wn.fetchEntityMetadataFromApi=LL;async function kL(e,t,r){var n,i;let a=`/EntityDefinitions${(0,ir.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,cp.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,p;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:$r(c.DisplayName),entitySetName:(p=c.EntitySetName)!==null&&p!==void 0?p:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Wn.findTables=kL;async function ML(e,t,r,n){var i,a;let o=`${qr(t)}/Attributes`+(0,ir.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(a=(i=(0,cp.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[],u=(r??"").toLowerCase(),c=l.map(d=>{var p,f;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:$r(d.DisplayName),attributeType:(f=d.AttributeType)!==null&&f!==void 0?f:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}Wn.findColumns=ML});var mp=y(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.renderTypeRegistrations=Rt.buildGenPageLegacyEnums=Rt.renderGenPageAuthoringTypes=Rt.buildGenPageRuntimeTypes=Rt.toDesignerEntity=Rt.TABLE_LOGICAL_NAME=void 0;Rt.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function pp(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var BL=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Tl(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function uy(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Tl(e)==="boolean",a={};for(let o of n)a[o.value]={text:(r=(t=o.invariantName)!==null&&t!==void 0?t:o.label)!==null&&r!==void 0?r:"",value:o.value,...!i&&o.color?{color:o.color}:{}};return a}function sy(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function cy(e){return!BL.has(e.logicalName)&&(!e.attributeOf||Tl(e)==="image")&&e.isValidForRead!==!1}var ly=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function dy(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(a=>!!a)),n=e.attributes.filter(a=>r.has(a.logicalName)).sort(sy),i=e.attributes.filter(a=>!r.has(a.logicalName)).sort(sy);return[...n,...i]}function fp(e){var t;let r=[],n=new Set,i=dy(e);for(let a of i){let o=Tl(a),s=o==="image";cy(a)&&(s&&a.attributeOf&&n.add(a.attributeOf),r.push({AttributeTypeName:o,IsReadOnly:!a.isValidForUpdate,LogicalName:a.logicalName,OptionSet:uy(a),Targets:a.targets,Description:a.description,MaxLength:a.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(a=>!n.has(a.LogicalName))}}Rt.toDesignerEntity=fp;function py(e,t="None"){let r={};for(let n of e)r[n.logicalName]=fp(n);return hy(r,t)}Rt.buildGenPageRuntimeTypes=py;var fy=`export interface TableRegistrations extends BaseTableRegistrations {
-`,my=`export interface EnumRegistrations extends BaseEnumRegistrations {
-`;function UL(e,t){return e.length>0?py(e,t).text:vy(`${fy}}
-`,`${my}}
-`,"","")}Rt.renderGenPageAuthoringTypes=UL;function $L(e){let t=new Set;for(let n of e)for(let i of fp(n).Attributes)ly.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of dy(n)){let a=`${n.logicalName}_${i.logicalName}`,o=uy(i);if(cy(i)||!ly.has(Tl(i))||!o||t.has(a)||r.has(a))continue;let s={name:a,runtime:{},labels:new Map};r.set(a,{declaration:gy(a,o,!1,s),model:s})}return r}Rt.buildGenPageLegacyEnums=$L;function hy(e,t="None"){var r,n;let i=new Map,a=Object.values(e);if(a.length===0)return{text:"",enums:i};let o=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=fy,u=my,c="",d="";for(let p of a){s&&p.Description&&(c+=`// ${pp(p.Description)}
+ &$filter=(applicationid eq '${e}')`;E.SPNPrincipalIdUrl=EF;function CF(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}E.retrieveDeploymentPipelineConfigAppUrl=CF;E.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function SF(e){return`/api/data/v9.0/settingdefinitions${e}`}E.getSettingDefinitionsUri=SF;E.OrgSettingOverrideName="organizationsettings";function NF(e,t=!1){let r=`/api/data/v9.0/${E.OrgSettingOverrideName}${e}`;return t?`${E.cdsServiceUrl}${r}`:r}E.getOrgSettingOverrideUri=NF;E.AppSettingOverrideName="appsettings";function DF(e,t=!1){let r=`/api/data/v9.0/${E.AppSettingOverrideName}${e}`;return t?`${E.cdsServiceUrl.replace("/$","")}${r}`:r}E.getAppSettingOverrideUri=DF;var Ya;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Ya||(E.RetrievePlatform=Ya={}));function _F(e,t,r,n=Ya.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==Ya.All&&o.push(`RetrievePlatformSettings=${n===Ya.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${E.cdsServiceUrl}${a}`:a}E.getPowerSettingsUri=_F;function IF(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${E.cdsServiceUrl}${o}`:o}E.getPowerSettingUri=IF;function TF(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${E.cdsServiceUrl}${t}`:t}E.getSavePowerSettingUri=TF;E.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function PF(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}E.getBusinessRuleDesignerUri=PF;function Dy({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}E.getUCIEntityRecordBaseUrl=Dy;function RF({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||Dy({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}E.getUCIEntityRecordEditUrl=RF;E.retrieveOrganizationResources=`${E.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var Iy=b(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.DataverseClient=void 0;var OF=hp(),Ri=re(),_y=be(),vp=class{constructor(t,r,n){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${OF.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Ri.SdkError?n:new Ri.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return(0,_y.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,r)))}getAbsolute(t,r){return this.assertSameOrigin(t),(0,_y.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,r)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Ri.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Ri.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Ri.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new Ri.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new Ri.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};kl.DataverseClient=vp});var Ty=b(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.findColumns=Zn.findTables=Zn.fetchEntityMetadataFromApi=void 0;var bp=be(),ir=ae();function Vr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function So(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function Fl(e,t){return(await Ml(e,t)).rows}async function Ml(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Gr(e){return`/EntityDefinitions(LogicalName='${(0,ir.odataPathLiteral)(e)}')`}async function xF(e,t,r){let n=await Fl(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function LF(e){return`${Gr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function kF(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Vr(a.Label),...So(a.Label)?{localizedLabel:So(a.Label)}:{}}}))}}function yp(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Vr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function FF(e,t,r){var n;let i=u=>Ml(e,u).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(u=>i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.${u}${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map;for(let{rows:u}of a)for(let c of u)!((n=c.OptionSet)===null||n===void 0)&&n.Options&&s.set(c.LogicalName,c.OptionSet.Options.map(yp));let l=await i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let u of l.rows){let c=u.OptionSet;c?.TrueOption&&c.FalseOption&&s.set(u.LogicalName,[yp(c.FalseOption),yp(c.TrueOption)])}return{byColumn:s,complete:l.ok&&a.every(u=>u.ok)}}async function MF(e,t,r){let{rows:n,ok:i}=await Ml(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}async function BF(e,t){var r,n,i,o;let a=[],s=await Fl(e,`${Gr(t)}/OneToManyRelationships${(0,ir.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await Fl(e,`${Gr(t)}/ManyToOneRelationships${(0,ir.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Fl(e,`${Gr(t)}/ManyToManyRelationships${(0,ir.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a}async function $F(e,t){var r,n,i,o,a;let s=`${Gr(t)}`+(0,ir.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,bp.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var y,w,C;return{logicalName:g.LogicalName,displayName:Vr(g.DisplayName),...So(g.DisplayName)?{localizedDisplayName:So(g.DisplayName)}:{},attributeType:(y=g.AttributeType)!==null&&y!==void 0?y:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Vr(g.Description)?{description:Vr(g.Description)}:{}}}),d=new Map(c.map(g=>[g.logicalName,g])),p=Ml(e,LF(t)),[,,f,m,h]=await Promise.all([xF(e,t,d),kF(p,d),FF(e,t,p),MF(e,t,d),BF(e,t)]);for(let g of c){let y=f.byColumn.get(g.logicalName);y&&(g.choices=y)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Vr(u.DisplayName),...So(u.DisplayName)?{localizedDisplayName:So(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Vr(u.Description)?{description:Vr(u.Description)}:{},columnDetailComplete:f.complete&&m,attributes:c,relationships:h}}Zn.fetchEntityMetadataFromApi=$F;async function UF(e,t,r){var n,i;let o=`/EntityDefinitions${(0,ir.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,bp.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,p;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Vr(c.DisplayName),entitySetName:(p=c.EntitySetName)!==null&&p!==void 0?p:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Zn.findTables=UF;async function qF(e,t,r,n){var i,o;let a=`${Gr(t)}/Attributes`+(0,ir.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,bp.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var p,f;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:Vr(d.DisplayName),attributeType:(f=d.AttributeType)!==null&&f!==void 0?f:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}Zn.findColumns=qF});var Ep=b(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.renderTypeRegistrations=Ot.buildGenPageLegacyEnums=Ot.renderGenPageAuthoringTypes=Ot.buildGenPageRuntimeTypes=Ot.toDesignerEntity=Ot.TABLE_LOGICAL_NAME=void 0;Ot.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function wp(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var VF=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Bl(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function Oy(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Bl(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function Py(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function xy(e){return!VF.has(e.logicalName)&&(!e.attributeOf||Bl(e)==="image")&&e.isValidForRead!==!1}var Ry=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function Ly(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(Py),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(Py);return[...n,...i]}function Ap(e){var t;let r=[],n=new Set,i=Ly(e);for(let o of i){let a=Bl(o),s=a==="image";xy(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:Oy(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}Ot.toDesignerEntity=Ap;function ky(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Ap(n);return By(r,t)}Ot.buildGenPageRuntimeTypes=ky;var Fy=`export interface TableRegistrations extends BaseTableRegistrations {
+`,My=`export interface EnumRegistrations extends BaseEnumRegistrations {
+`;function GF(e,t){return e.length>0?ky(e,t).text:Uy(`${Fy}}
+`,`${My}}
+`,"","")}Ot.renderGenPageAuthoringTypes=GF;function zF(e){let t=new Set;for(let n of e)for(let i of Ap(n).Attributes)Ry.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of Ly(n)){let o=`${n.logicalName}_${i.logicalName}`,a=Oy(i);if(xy(i)||!Ry.has(Bl(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:$y(o,a,!1,s),model:s})}return r}Ot.buildGenPageLegacyEnums=zF;function By(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=Fy,u=My,c="",d="";for(let p of o){s&&p.Description&&(c+=`// ${wp(p.Description)}
`),c+=`export type ${p.LogicalName} = TableRow<{
// Primary Key Column
readonly ${p.PrimaryIdAttribute}: string,
@@ -59,22 +59,22 @@ var S1=Object.create;var hl=Object.defineProperty;var N1=Object.getOwnPropertyDe
`;for(let f of p.Attributes){if(f.LogicalName===p.PrimaryIdAttribute)continue;let m=`${f.IsReadOnly?" readonly ":""}${f.LogicalName}`,h=!0;switch(f.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":m+=`: string,
`;break;case"integer":case"double":case"decimal":case"money":case"bigint":m+=`: number,
`;break;case"datetime":m+=`: Date,
-`;break;case"customer":case"lookup":{let v=(r=f.Targets)!==null&&r!==void 0?r:f.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!v||v.length===0){h=!1;break}m=` // Foreign Key Column
- ${f.IsReadOnly||v.every(E=>!e[E])?" readonly ":""}_${f.LogicalName}_value: `;let b="";for(let E of v)b+=`${b.length===0?"":" | "}\`/${E}(\${string})\``;m+=`${b},
-`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let v=`${p.LogicalName}_${f.LogicalName}`;m+=`: ${v},
-`;let b=(n=i.get(v))!==null&&n!==void 0?n:{name:v,runtime:{},labels:new Map};i.set(v,b),d+=gy(v,f.OptionSet,o,b),u+=` "${p.LogicalName}-${f.LogicalName}": ${v},
+`;break;case"customer":case"lookup":{let g=(r=f.Targets)!==null&&r!==void 0?r:f.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column
+ ${f.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${f.LogicalName}_value: `;let y="";for(let w of g)y+=`${y.length===0?"":" | "}\`/${w}(\${string})\``;m+=`${y},
+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${p.LogicalName}_${f.LogicalName}`;m+=`: ${g},
+`;let y=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,y),d+=$y(g,f.OptionSet,a,y),u+=` "${p.LogicalName}-${f.LogicalName}": ${g},
`;break}case"image":c+=` // This is an image encoded as a base64 string
`,m+=`: string,
-`;break;default:h=!1}h&&(s&&f.Description&&(c+=` // ${pp(f.Description)}
-`),o&&f.MaxLength&&(c+=" // Maximum length: "+f.MaxLength+`
+`;break;default:h=!1}h&&(s&&f.Description&&(c+=` // ${wp(f.Description)}
+`),a&&f.MaxLength&&(c+=" // Maximum length: "+f.MaxLength+`
`),c+=` ${m}`)}c+=`}>
`}return l+=`}
`,u+=`}
-`,{text:vy(l,u,c,d),enums:i}}Rt.renderTypeRegistrations=hy;function gy(e,t,r,n){var i;let a=`const enum ${e} {
-`;for(let o of Object.values(t??{}))if(o){r&&(a+=`${o.color?`// Option Color: ${pp(o.color)}
-`:""}`),a+=`${JSON.stringify(o.text)} = ${o.value},
-`,n.runtime[o.text]=o.value,n.runtime[String(o.value)]=o.text;let s=(i=n.labels.get(o.text))!==null&&i!==void 0?i:[];s.includes(o.value)||s.push(o.value),n.labels.set(o.text,s)}return`${a}}
-`}function vy(e,t,r,n){return`
+`,{text:Uy(l,u,c,d),enums:i}}Ot.renderTypeRegistrations=By;function $y(e,t,r,n){var i;let o=`const enum ${e} {
+`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${wp(a.color)}
+`:""}`),o+=`${JSON.stringify(a.text)} = ${a.value},
+`,n.runtime[a.text]=a.value,n.runtime[String(a.value)]=a.text;let s=(i=n.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),n.labels.set(a.text,s)}return`${o}}
+`}function Uy(e,t,r,n){return`
// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
${e}
${t}
@@ -345,19 +345,19 @@ export interface GeneratedComponentProps {
dataApi: UxAgentDataApi;
pageInput?: PageInput;
}
-`}});var wy=y(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.generateGenPageRuntimeTypes=void 0;var by=mp(),Si=te(),yy=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Ni="generateGenPageRuntimeTypes";async function qL(e,t,r){let n=VL(t),i=GL(r),a=[];for(let o of n){let s=await e(o);if(s.columnDetailComplete!==!0)throw new Si.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Ni}: the column metadata of data source '${o}' could not be read completely (a choice or lookup request failed), so its RuntimeTypes would lack enums a page can use. Retry.`);a.push(s)}return(0,by.renderGenPageAuthoringTypes)(a,i)}Pl.generateGenPageRuntimeTypes=qL;function VL(e){if(!Array.isArray(e))throw new Si.InvalidArgumentError(`${Ni}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!by.TABLE_LOGICAL_NAME.test(r))throw new Si.InvalidArgumentError(`${Ni}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Si.InvalidArgumentError(`${Ni}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function GL(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Si.InvalidArgumentError(`${Ni}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Si.InvalidArgumentError(`${Ni}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!yy.has(r))throw new Si.InvalidArgumentError(`${Ni}: detail must be one of ${[...yy].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var ha=y(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.DEFAULT_LCID=void 0;Rl.DEFAULT_LCID=1033});var lt=y(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.assignMissingIds=Vr.pointerTouchesValueMap=Vr.isValueMapKey=Vr.newId=void 0;var zL=ca();function Ay(){return globalThis.crypto.randomUUID().toLowerCase()}Vr.newId=Ay;function WL(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var gp=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData"]);function jL(e){return gp.has(e)}Vr.isValueMapKey=jL;function HL(e){return zL.JsonPointer.parse(e).some(t=>gp.has(t))}Vr.pointerTouchesValueMap=HL;function KL(e){return hp(e),e}Vr.assignMissingIds=KL;function hp(e){if(Array.isArray(e)){e.forEach(t=>hp(t));return}if(WL(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=Ay());for(let t of Object.keys(e))t==="id"||gp.has(t)||hp(e[t])}}});var Ol=y(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.postChangeSet=jn.parseChangeSetStatuses=jn.renderChangeSet=void 0;var Di=te(),JL=be(),Ey=lt(),zo=ae();function Cy(e,t){let r=`batch_${(0,Ey.newId)()}`,n=`changeset_${(0,Ey.newId)()}`,i=t.map((s,l)=>String(l+1)),a=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new Di.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new Di.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,zo.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,zo.assertNoControlChars)(s.etag,"batch operation etag");let p=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[f,m]of p)if((0,zo.assertNoControlChars)(f,"batch operation header name"),(0,zo.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(f))throw new Di.InvalidArgumentError(`batch operation header name '${f}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,zo.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...p.map(([f,m])=>`${f}: ${m}`),"",...d===void 0?[]:[d]].join(`\r
-`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...a,`--${n}--`,`--${r}--`,""].join(`\r
-`),batchId:r,contentIds:i}}jn.renderChangeSet=Cy;function Sy(e,t){var r,n,i,a;if(typeof e!="string"||e.length===0)return;let o=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(o===void 0||!e.trimEnd().endsWith(`--${o}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===o)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let p of l.slice(1)){if(p.startsWith("--"))break;let f=p.indexOf(`\r
+`}});var Gy=b($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.generateGenPageRuntimeTypes=void 0;var Vy=Ep(),Oi=re(),qy=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),xi="generateGenPageRuntimeTypes";async function WF(e,t,r){let n=jF(t),i=HF(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Oi.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${xi}: the column metadata of data source '${a}' could not be read completely (a choice or lookup request failed), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,Vy.renderGenPageAuthoringTypes)(o,i)}$l.generateGenPageRuntimeTypes=WF;function jF(e){if(!Array.isArray(e))throw new Oi.InvalidArgumentError(`${xi}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!Vy.TABLE_LOGICAL_NAME.test(r))throw new Oi.InvalidArgumentError(`${xi}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Oi.InvalidArgumentError(`${xi}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function HF(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Oi.InvalidArgumentError(`${xi}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Oi.InvalidArgumentError(`${xi}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!qy.has(r))throw new Oi.InvalidArgumentError(`${xi}: detail must be one of ${[...qy].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var Li=b(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});Ul.DEFAULT_LCID=void 0;Ul.DEFAULT_LCID=1033});var lt=b(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.assignMissingIds=zr.pointerTouchesValueMap=zr.isValueMapKey=zr.newId=void 0;var KF=wo();function zy(){return globalThis.crypto.randomUUID().toLowerCase()}zr.newId=zy;function JF(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Sp=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData"]);function QF(e){return Sp.has(e)}zr.isValueMapKey=QF;function XF(e){return KF.JsonPointer.parse(e).some(t=>Sp.has(t))}zr.pointerTouchesValueMap=XF;function YF(e){return Cp(e),e}zr.assignMissingIds=YF;function Cp(e){if(Array.isArray(e)){e.forEach(t=>Cp(t));return}if(JF(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=zy());for(let t of Object.keys(e))t==="id"||Sp.has(t)||Cp(e[t])}}});var ql=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.postChangeSet=ei.parseChangeSetStatuses=ei.renderChangeSet=void 0;var ki=re(),ZF=be(),Wy=lt(),es=ae();function jy(e,t){let r=`batch_${(0,Wy.newId)()}`,n=`changeset_${(0,Wy.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new ki.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new ki.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,es.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,es.assertNoControlChars)(s.etag,"batch operation etag");let p=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[f,m]of p)if((0,es.assertNoControlChars)(f,"batch operation header name"),(0,es.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(f))throw new ki.InvalidArgumentError(`batch operation header name '${f}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,es.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...p.map(([f,m])=>`${f}: ${m}`),"",...d===void 0?[]:[d]].join(`\r
+`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...o,`--${n}--`,`--${r}--`,""].join(`\r
+`),batchId:r,contentIds:i}}ei.renderChangeSet=jy;function Hy(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let p of l.slice(1)){if(p.startsWith("--"))break;let f=p.indexOf(`\r
\r
-`);if(f===-1)return;let m=p.slice(0,f),h=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let v=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!v||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(a=/^Content-ID:\s*(\S+)/im.exec(m))===null||a===void 0?void 0:a[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push(Number(v[1]))}return c.length===0?void 0:c}jn.parseChangeSetStatuses=Sy;async function QL(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:a}=Cy(e,t),o=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,JL.ensureSuccess)(o,s),typeof o.body!="string"||o.body.length===0)throw new Di.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=Sy(o.body,a);if(l===void 0)throw new Di.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new Di.ConnectionError(s,o.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new Di.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}jn.postChangeSet=QL});var xl=y(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.updateTable=X.deleteAlternateKey=X.createAlternateKey=X.deleteGlobalOptionSet=X.createGlobalOptionSet=X.deleteRelationship=X.deleteColumn=X.updateColumn=X.deleteTable=X.createRelationship=X.insertStatusValue=X.createCustomerColumn=X.createColumns=X.setColumnVisualization=X.getColumnVisualization=X.createColumn=X.createTable=X.resolveEntitySetName=X.pluralFallback=void 0;var de=be(),J=ae(),Gr=ha(),we=te(),XL=Ol(),YL={String:"Microsoft.Dynamics.CRM.StringAttributeMetadata",Memo:"Microsoft.Dynamics.CRM.MemoAttributeMetadata",Integer:"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",Decimal:"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",Money:"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",Boolean:"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",DateTime:"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",Picklist:"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",Lookup:"Microsoft.Dynamics.CRM.LookupAttributeMetadata"};function Fe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:ZL(e,t)}}var Ny=65535;function ZL(e,t){let r=(a,o)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:a,LanguageCode:o});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new we.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([a,o])=>{if(!/^[1-9]\d*$/.test(a))throw new we.InvalidArgumentError(`localized label key '${a}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(a);if(s>Ny)throw new we.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${Ny})`);if(i.has(s))throw new we.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof o!="string")throw new we.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(o,s)})}function Ty(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new we.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}X.pluralFallback=Ty;function Wo(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function bp(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Dy(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jo(e){let t=(0,de.readCreatedId)(e,"MetadataId");if(!t)throw new we.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function ek(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h,v,b,E,C,N,R,O,F,k,P,V;if(t.defaultValue!==void 0&&e!=="boolean")throw new we.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new we.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(a=t.maxLength)!==null&&a!==void 0?a:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(o=t.integerFormat)!==null&&o!==void 0?o:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(p=t.precision)!==null&&p!==void 0?p:2,MinValue:(f=t.minValue)!==null&&f!==void 0?f:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(v=t.minValue)!==null&&v!==void 0?v:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(E=t.defaultValue)!==null&&E!==void 0?E:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Fe((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:Fe((N=t.falseLabel)!==null&&N!==void 0?N:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(R=t.dateFormat)!==null&&R!==void 0?R:"DateAndTime"};case"choice":return Iy(t,r,!1);case"multiChoice":return Iy(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(O=t.maxSizeKb)!==null&&O!==void 0?O:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(F=t.isPrimaryImage)!==null&&F!==void 0?F:!1,MaxSizeInKB:(k=t.maxSizeKb)!==null&&k!==void 0?k:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(P=t.maxLength)!==null&&P!==void 0?P:100,AutoNumberFormat:(V=t.autoNumberFormat)!==null&&V!==void 0?V:""};default:throw new we.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Iy(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,J.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new we.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(a=>({Value:a.value,Label:Fe(a.label,t)}))},i}var vp=new WeakMap;async function tk(e,t){var r,n;let i=(r=vp.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new we.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=vp.get(e);return l||(l=new Map,vp.set(e,l)),l.set(t,s),s}X.resolveEntitySetName=tk;async function rk(e,t){var r,n,i,a,o,s,l,u,c,d,p,f,m,h,v;let b=(r=t.languageCode)!==null&&r!==void 0?r:Gr.DEFAULT_LCID,E=bp(t.schemaName),C=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${E}_Name`,N={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:C,RequiredLevel:Wo("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Fe((a=t.primaryColumnDisplayName)!==null&&a!==void 0?a:"Name",b),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(N.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&Oy(t.columns,"createTable");let R={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Fe(t.displayName,b),DisplayCollectionName:Fe((o=t.pluralName)!==null&&o!==void 0?o:Ty(t.displayName),b),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[N,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Be=>wp(Be,b))]};t.description&&(R.Description=Fe(t.description,b));let O="/EntityDefinitions",F=(0,de.ensureSuccess)(await e.post(O,R),e.apiUrl(O)),k=jo(F),P=`/EntityDefinitions(${k})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),V=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),q=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),ze;for(let Be=1;Be<=V;Be+=1){let Qe=await e.get(P);if(Qe.status>=200&&Qe.status<300){ze=Qe;break}Qe.status!==404&&(0,de.ensureSuccess)(Qe,e.apiUrl(P)),Be<V&&q>0&&await new Promise(Z=>setTimeout(Z,q))}if(!ze)throw new we.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${k}) but its metadata was still not readable after ${V} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${k}) once the environment catches up, or raise 'readBackAttempts'.`);let Tt=ze.body;return{logicalName:(f=Tt.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:k,entitySetName:(m=Tt.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=Tt.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(v=Tt.PrimaryNameAttribute)!==null&&v!==void 0?v:C.toLowerCase()}}X.createTable=rk;function wp(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,a={...ek(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Wo((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Fe(e.displayName,i)};return e.description&&(a.Description=Fe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(a.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(a.FormulaDefinition=e.formulaDefinition)),Py(a,e),a}function Py(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function nk(e,t,r){var n;let i=wp(r,(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID),a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,o=(0,de.ensureSuccess)(await e.post(a,i),e.apiUrl(a)),s={logicalName:r.schemaName.toLowerCase(),metadataId:jo(o)};if(r.visualization&&r.visualization!=="None")try{await Ly(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new we.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw u.cause=l,u}return s}X.createColumn=nk;var ga="/controlconfigurations",Ry="CustomRenderersConfiguration",yp={RadialDial:"c3d4e5f6-a7b8-9012-cdef-345678901234",LineChart:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",HeatMap:"e7f8a9b0-c1d2-4e3f-5a6b-7c8d9e0f1a2b",StarRating:"b5e4c3d2-f1a0-4e2b-8a7c-9d3f5c1e6b04"};function Oy(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new we.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${r.schemaName}') is not supported \u2014 the attribute metadata and its control-configuration row are separate writes. Create the column, then call setColumnVisualization; or use the single-column createColumn.`)}function xy(e){return JSON.stringify({type:yp[e]})}function ik(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(yp).find(i=>yp[i]===r);return n??"None"}async function Fy(e,t,r){var n,i;let a=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,o=`${ga}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",a]])}`,l=(i=(n=(0,de.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,p;return((p=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||p===void 0?void 0:p.toLowerCase())===u})}async function ak(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,o=(n=(0,de.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!o)throw new we.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(o,"MetadataId")}async function Ly(e,t,r,n,i){let a={name:Ry,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:xy(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,de.ensureSuccess)(await e.post(ga,a),e.apiUrl(ga))}async function ok(e,t,r){var n;let i=await Fy(e,t,r);return ik((n=i[0])===null||n===void 0?void 0:n.metadatajson)}X.getColumnVisualization=ok;async function sk(e,t,r,n){let a=(await Fy(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of a){let c=`${ga}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,de.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[o,...s]=a,l=await ak(e,t,r);if(o){let u=`${ga}(${(0,J.normalizeGuid)(o,"controlconfigurationid")})`,c={name:Ry,metadatajson:xy(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,de.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await Ly(e,t,r,l,n);for(let u of s){let c=`${ga}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,de.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}X.setColumnVisualization=sk;async function lk(e,t,r){if(r.length===0)return;if(Oy(r,"createColumns"),!e.supportsAtomicBatch)throw new we.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`;await(0,XL.postChangeSet)(e,r.map(i=>{var a;return{method:"POST",path:n,body:wp(i,(a=i.languageCode)!==null&&a!==void 0?a:Gr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}X.createColumns=lk;async function uk(e,t,r){var n,i,a,o;let s=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,l=bp(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(a=r.contactRelationshipName)!==null&&a!==void 0?a:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Fe(r.displayName,s),RequiredLevel:Wo((o=r.required)!==null&&o!==void 0?o:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,de.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}X.createCustomerColumn=uk;async function ck(e,t,r){var n,i,a,o,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Fe(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,de.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(o=(a=c.body)===null||a===void 0?void 0:a.NewOptionValue)!==null&&o!==void 0?o:r.value)!==null&&s!==void 0?s:0)}X.insertStatusValue=ck;async function dk(e,t){var r,n,i,a,o;let s=(r=t.languageCode)!==null&&r!==void 0?r:Gr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new we.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${bp(t.schemaName)}_${t.referencedEntity}Id`;u=p.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:p,RequiredLevel:Wo((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Fe((a=t.lookupDisplayName)!==null&&a!==void 0?a:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new we.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(o=t.intersectEntityName)!==null&&o!==void 0?o:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,de.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:jo(d),lookupLogicalName:u}}X.createRelationship=dk;async function pk(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`;(0,de.ensureSuccess)(await e.delete(r),e.apiUrl(r))}X.deleteTable=pk;async function fk(e,t,r,n){var i,a;let o=(i=n.languageCode)!==null&&i!==void 0?i:Gr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,de.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=YL[(a=c.AttributeType)!==null&&a!==void 0?a:""];if(!c.MetadataId||!d)throw new we.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,J.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,m=(0,de.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let v of Object.keys(m))v.startsWith("@odata.")&&delete m[v];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=Fe(n.displayName,o)),n.description!==void 0&&(m.Description=Fe(n.description,o)),n.required!==void 0&&(m.RequiredLevel=Wo(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new we.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new we.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),Py(m,n);let h=`${s}(${p})`;(0,de.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}X.updateColumn=fk;async function mk(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,a=`${i}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,de.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteColumn=mk;async function hk(e,t){var r,n,i;let a=`/RelationshipDefinitions${(0,J.odataQuery)([["$filter",`SchemaName eq '${(0,J.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new we.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,de.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteRelationship=hk;async function _y(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let o=(r=(0,de.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return o?(0,J.normalizeGuid)(o,"MetadataId"):void 0}async function gk(e,t){var r;let n=t.name.toLowerCase(),i=await _y(e,n);if(i)return{name:n,metadataId:i};let a=(r=t.languageCode)!==null&&r!==void 0?r:Gr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Fe(t.displayName,a),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Fe(l.label,a)}))};t.description&&(o.Description=Fe(t.description,a));let s="/GlobalOptionSetDefinitions";try{let l=(0,de.ensureSuccess)(await e.post(s,o),e.apiUrl(s));return{name:n,metadataId:jo(l)}}catch(l){let u;try{u=await _y(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}X.createGlobalOptionSet=gk;async function vk(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t.toLowerCase())}')`;(0,de.ensureSuccess)(await e.delete(r),e.apiUrl(r))}X.deleteGlobalOptionSet=vk;async function yk(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Fe(r.displayName,i),KeyAttributes:r.keyAttributes},o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,s=(0,de.ensureSuccess)(await e.post(o,a),e.apiUrl(o));return{logicalName:r.schemaName.toLowerCase(),metadataId:jo(s)}}X.createAlternateKey=yk;async function bk(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,a=`${i}(LogicalName='${(0,J.odataPathLiteral)(r.toLowerCase())}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,de.ensureSuccess)(await e.delete(l),e.apiUrl(l))}X.deleteAlternateKey=bk;async function wk(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Gr.DEFAULT_LCID,a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`,s=(0,de.ensureSuccess)(await e.get(a),e.apiUrl(a)).body,l=s.MetadataId;if(!l)throw new we.InvalidArgumentError(`table '${t}' not found`);let u=(0,J.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=Fe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Fe(r.pluralName,i)),r.description!==void 0&&(s.Description=Fe(r.description,i)),r.auditEnabled!==void 0&&Dy(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Dy(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,de.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}X.updateTable=wk});var Kn=y(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.rebuildRaw=Ot.assembleChildren=Ot.spliceChildren=Ot.mergeAttrs=Ot.rawFromNode=Ot.emptyBag=void 0;var Hn=te(),ky=1e6,Ll=512;function Ak(){return{a:[],c:[]}}Ot.emptyBag=Ak;function My(e,t=0){if(t>Ll)throw new Hn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Ll}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>My(r,t+1))}}Ot.rawFromNode=My;function Ek(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),a=new Set,o=[];for(let[s,l]of e)i.has(s)||(n.has(s)?o.push([s,n.get(s)]):o.push([s,l]),a.add(s));for(let[s,l]of t)a.has(s)||(o.push([s,l]),a.add(s));return o}Ot.mergeAttrs=Ek;function Fl(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>ky)throw new Hn.InvalidArgumentError(`Bag child index must be an integer in [0, ${ky}] (got ${String(l)})`);if(r.has(l))throw new Hn.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],a=0,o=0;for(let s of n){for(;o<s.i&&a<t.length;)i.push(t[a]),a+=1,o+=1;o<s.i&&(o=s.i),i.push(s.node),o+=1}for(;a<t.length;)i.push(t[a]),a+=1;return i}Ot.spliceChildren=Fl;function Ck(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Fl(e.w.c,t)};return Fl(e.c,[r])}return Fl(e.c,t)}Ot.assembleChildren=Ck;function By(e,t,r,n=0){if(n>Ll)throw new Hn.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Ll}`);Sk(e,n);let i=t.make(e.n,r);for(let[a,o]of e.a)t.setProp(i,a,o);for(let a of e.c)t.addChild(i,By(a,t,i,n+1));return i}Ot.rebuildRaw=By;function Sk(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Hn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new Hn.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(r.a)||!Array.isArray(r.c))throw new Hn.InvalidArgumentError(`Malformed hybrid node '${r.n}': 'a' and 'c' must be arrays`);for(let n of r.a)if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")throw new Hn.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var va=y(gn=>{"use strict";function Nk(e,t,r){if(r===void 0&&(r=Array.prototype),e&&typeof r.find=="function")return r.find.call(e,t);for(var n=0;n<e.length;n++)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];if(t.call(void 0,i,n,e))return i}}function Ep(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function Dk(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}var Uy=Ep({HTML:"text/html",isHTML:function(e){return e===Uy.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),$y=Ep({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===$y.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),kl=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,Ap=new RegExp("[\\-\\.0-9"+kl.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),Ik=new RegExp("^"+kl.source+Ap.source+"*(?::"+kl.source+Ap.source+"*)?$");gn.assign=Dk;gn.find=Nk;gn.freeze=Ep;gn.MIME_TYPE=Uy;gn.NAMESPACE=$y;gn.nameStartChar=kl;gn.nameChar=Ap;gn.tagNamePattern=Ik});var Fp=y(wn=>{var Cp=va(),zr=Cp.find,Ko=Cp.NAMESPACE,ya=Cp.tagNamePattern;function _k(e){return e!==""}function Tk(e){return e?e.split(/[\t\n\f\r ]+/).filter(_k):[]}function Pk(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function qy(e){if(!e)return[];var t=Tk(e);return Object.keys(t.reduce(Pk,{}))}function Rk(e){return function(t){return e&&e.indexOf(t)!==-1}}function Qo(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ft(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Qo(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Lt={},ar=Lt.ELEMENT_NODE=1,ba=Lt.ATTRIBUTE_NODE=2,Ho=Lt.TEXT_NODE=3,Jy=Lt.CDATA_SECTION_NODE=4,Qy=Lt.ENTITY_REFERENCE_NODE=5,Ok=Lt.ENTITY_NODE=6,Sp=Lt.PROCESSING_INSTRUCTION_NODE=7,Np=Lt.COMMENT_NODE=8,Xy=Lt.DOCUMENT_NODE=9,Yy=Lt.DOCUMENT_TYPE_NODE=10,vn=Lt.DOCUMENT_FRAGMENT_NODE=11,xk=Lt.NOTATION_NODE=12,pt={},Ye={},RJ=pt.INDEX_SIZE_ERR=(Ye[1]="Index size error",1),OJ=pt.DOMSTRING_SIZE_ERR=(Ye[2]="DOMString size error",2),xt=pt.HIERARCHY_REQUEST_ERR=(Ye[3]="Hierarchy request error",3),xJ=pt.WRONG_DOCUMENT_ERR=(Ye[4]="Wrong document",4),Vy=pt.INVALID_CHARACTER_ERR=(Ye[5]="Invalid character",5),FJ=pt.NO_DATA_ALLOWED_ERR=(Ye[6]="No data allowed",6),LJ=pt.NO_MODIFICATION_ALLOWED_ERR=(Ye[7]="No modification allowed",7),Zy=pt.NOT_FOUND_ERR=(Ye[8]="Not found",8),kJ=pt.NOT_SUPPORTED_ERR=(Ye[9]="Not supported",9),Gy=pt.INUSE_ATTRIBUTE_ERR=(Ye[10]="Attribute in use",10),Er=pt.INVALID_STATE_ERR=(Ye[11]="Invalid state",11),MJ=pt.SYNTAX_ERR=(Ye[12]="Syntax error",12),BJ=pt.INVALID_MODIFICATION_ERR=(Ye[13]="Invalid modification",13),UJ=pt.NAMESPACE_ERR=(Ye[14]="Invalid namespace",14),$J=pt.INVALID_ACCESS_ERR=(Ye[15]="Invalid access",15);function ie(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ye[e]),this.message=Ye[e],Error.captureStackTrace&&Error.captureStackTrace(this,ie);return r.code=e,t&&(this.message=this.message+": "+t),r}ie.prototype=Error.prototype;Qo(pt,ie);function yn(){}yn.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],a=0;a<this.length;a++)xp(this[a],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function wa(e,t){this._node=e,this._refresh=t,Dp(this)}function Dp(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(pb(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];Qo(r,e),e._inc=t}}wa.prototype.item=function(e){return Dp(this),this[e]||null};Ft(wa,yn);function Bl(){this._nameIndex=Object.create(null)}function eb(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function Fk(e,t){e._nameIndex[t.nodeName]=t}function tb(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function zy(e,t,r,n){if(n?(t[eb(t,n)]=r,tb(t,n)):t[t.length++]=r,Fk(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&ib(i,e,n),Lk(i,e,r))}}function Wy(e,t,r){var n=eb(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,tb(t,r),e){var a=e.ownerDocument;a&&(ib(a,e,r),r.ownerElement=null)}}else throw new ie(Zy,new Error(e.tagName+"@"+r))}Bl.prototype={length:0,item:yn.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new ie(Gy);var r=this._nameIndex[e.nodeName];return zy(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new ie(Gy);return r=this.getNamedItemNS(e.namespaceURI,e.localName),zy(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return Wy(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return Wy(this._ownerElement,this,r),r},getNamedItemNS:function(e,t){for(var r=this.length;r--;){var n=this[r];if(n.localName==t&&n.namespaceURI==e)return n}return null}};function rb(){}rb.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Xo;if(n.implementation=this,n.childNodes=new yn,n.doctype=r||null,r&&n.appendChild(r),t){var i=n.createElementNS(e,t);n.appendChild(i)}return n},createDocumentType:function(e,t,r){var n=new Gl;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function pe(){}pe.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return $l(this,e,t)},replaceChild:function(e,t){$l(this,e,t,ob),t&&this.removeChild(t)},removeChild:function(e){return ab(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return db(this.ownerDocument||this,this,e)},normalize:function(){Xe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Ho&&t.nodeType===Ho){for(var n=[],i=r;i!==null&&i.nodeType===Ho;)n.push(i.data),i=i.nextSibling;for(var a=t.nextSibling;a!==i;){var o=a.nextSibling;a.parentNode=null,a.previousSibling=null,a.nextSibling=null,a=o}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Vl(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==ba?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==ba?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function nb(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}Qo(Lt,pe);Qo(Lt,pe.prototype);function Ul(e,t){return Xe(e,null,{enter:function(r){return t(r)?Xe.STOP:!0}})===Xe.STOP}function Xe(e,t,r){for(var n=[{node:e,context:t,phase:Xe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Xe.ENTER){var a=r.enter(i.node,i.context);if(a===Xe.STOP)return Xe.STOP;if(n.push({node:i.node,context:a,phase:Xe.EXIT}),a==null)continue;for(var o=i.node.lastChild;o;)n.push({node:o,context:a,phase:Xe.ENTER}),o=o.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Xe.STOP=Symbol("walkDOM.STOP");Xe.ENTER=0;Xe.EXIT=1;function Xo(){this.ownerDocument=this}function Lk(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ko.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function ib(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ko.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Vl(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,a=0;i;)n[a++]=i,i=i.nextSibling;n.length=a,delete n[n.length]}}}function ab(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,Vl(e.ownerDocument,e),t}function kk(e){return e&&(e.nodeType===pe.DOCUMENT_NODE||e.nodeType===pe.DOCUMENT_FRAGMENT_NODE||e.nodeType===pe.ELEMENT_NODE)}function Mk(e){return e&&(Wr(e)||Ip(e)||bn(e)||e.nodeType===pe.DOCUMENT_FRAGMENT_NODE||e.nodeType===pe.COMMENT_NODE||e.nodeType===pe.PROCESSING_INSTRUCTION_NODE)}function bn(e){return e&&e.nodeType===pe.DOCUMENT_TYPE_NODE}function Wr(e){return e&&e.nodeType===pe.ELEMENT_NODE}function Ip(e){return e&&e.nodeType===pe.TEXT_NODE}function jy(e,t){var r=e.childNodes||[];if(zr(r,Wr)||bn(t))return!1;var n=zr(r,bn);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Hy(e,t){var r=e.childNodes||[];function n(a){return Wr(a)&&a!==t}if(zr(r,n))return!1;var i=zr(r,bn);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Bk(e,t,r){if(!kk(e))throw new ie(xt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new ie(Zy,"child not in parent");if(!Mk(t)||bn(t)&&e.nodeType!==pe.DOCUMENT_NODE)throw new ie(xt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function Uk(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===pe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Wr);if(a.length>1||zr(i,Ip))throw new ie(xt,"More than one element or text in fragment");if(a.length===1&&!jy(e,r))throw new ie(xt,"Element in fragment can not be inserted before doctype")}if(Wr(t)&&!jy(e,r))throw new ie(xt,"Only one element can be added and only after doctype");if(bn(t)){if(zr(n,bn))throw new ie(xt,"Only one doctype is allowed");var o=zr(n,Wr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ie(xt,"Doctype can only be inserted before an element");if(!r&&o)throw new ie(xt,"Doctype can not be appended since element is present")}}function ob(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===pe.DOCUMENT_FRAGMENT_NODE){var a=i.filter(Wr);if(a.length>1||zr(i,Ip))throw new ie(xt,"More than one element or text in fragment");if(a.length===1&&!Hy(e,r))throw new ie(xt,"Element in fragment can not be inserted before doctype")}if(Wr(t)&&!Hy(e,r))throw new ie(xt,"Only one element can be added and only after doctype");if(bn(t)){let l=function(u){return bn(u)&&u!==r};var s=l;if(zr(n,l))throw new ie(xt,"Only one doctype is allowed");var o=zr(n,Wr);if(r&&n.indexOf(o)<n.indexOf(r))throw new ie(xt,"Doctype can only be inserted before an element")}}function $l(e,t,r,n){Bk(e,t,r),e.nodeType===pe.DOCUMENT_NODE&&(n||Uk)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===vn){var a=t.firstChild;if(a==null)return t;var o=t.lastChild}else a=o=t;var s=r?r.previousSibling:e.lastChild;a.previousSibling=s,o.nextSibling=r,s?s.nextSibling=a:e.firstChild=a,r==null?e.lastChild=o:r.previousSibling=o;do{a.parentNode=e;var l=e.ownerDocument||e;Jo(a,l)}while(a!==o&&(a=a.nextSibling));return Vl(e.ownerDocument||e,e),t.nodeType==vn&&(t.firstChild=t.lastChild=null),t}function Jo(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===ar&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)Jo(i,t),i=i.nextSibling}}function $k(e,t){t.parentNode&&t.parentNode.removeChild(t),t.parentNode=e,t.previousSibling=e.lastChild,t.nextSibling=null,t.previousSibling?t.previousSibling.nextSibling=t:e.firstChild=t,e.lastChild=t,Vl(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Jo(t,r),t}Xo.prototype={nodeName:"#document",nodeType:Xy,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==vn){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return $l(this,e,t),Jo(e,this),this.documentElement===null&&e.nodeType===ar&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ab(this,e)},replaceChild:function(e,t){$l(this,e,t,ob),Jo(e,this),t&&this.removeChild(t),Wr(e)&&(this.documentElement=e)},importNode:function(e,t){return qk(this,e,t)},getElementById:function(e){var t=null;return Ul(this.documentElement,function(r){if(r.nodeType==ar&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=qy(e);return new wa(this,function(r){var n=[];return t.length>0&&Ul(r.documentElement,function(i){if(i!==r&&i.nodeType===ar){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=qy(a);o=t.every(Rk(s))}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Ii;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new yn;var r=t.attributes=new Bl;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new zl;return e.ownerDocument=this,e.childNodes=new yn,e},createTextNode:function(e){var t=new _p;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Tp;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new ie(Vy,'data contains "]]>"');var t=new Pp;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Op;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new ql;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ya.test(e))throw new ie(Vy,'not a valid xml name "'+e+'"');var t=new Rp;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Ii,n=t.split(":"),i=r.attributes=new Bl;return r.childNodes=new yn,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new ql,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};Ft(Xo,pe);function Ii(){this._nsMap={}}Ii.prototype={nodeType:ar,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===vn?this.insertBefore(e,null):$k(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new wa(this,function(t){var r=[];return Ul(t,function(n){n!==t&&n.nodeType==ar&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new wa(this,function(r){var n=[];return Ul(r,function(i){i!==r&&i.nodeType===ar&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Xo.prototype.getElementsByTagName=Ii.prototype.getElementsByTagName;Xo.prototype.getElementsByTagNameNS=Ii.prototype.getElementsByTagNameNS;Ft(Ii,pe);function ql(){}ql.prototype.nodeType=ba;Ft(ql,pe);function Yo(){}Yo.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(Ye[xt])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};Ft(Yo,pe);function _p(){}_p.prototype={nodeName:"#text",nodeType:Ho,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};Ft(_p,Yo);function Tp(){}Tp.prototype={nodeName:"#comment",nodeType:Np};Ft(Tp,Yo);function Pp(){}Pp.prototype={nodeName:"#cdata-section",nodeType:Jy};Ft(Pp,Yo);function Gl(){}Gl.prototype.nodeType=Yy;Ft(Gl,pe);function sb(){}sb.prototype.nodeType=xk;Ft(sb,pe);function lb(){}lb.prototype.nodeType=Ok;Ft(lb,pe);function Rp(){}Rp.prototype.nodeType=Qy;Ft(Rp,pe);function zl(){}zl.prototype.nodeName="#document-fragment";zl.prototype.nodeType=vn;Ft(zl,pe);function Op(){}Op.prototype.nodeType=Sp;Ft(Op,pe);function ub(){}ub.prototype.serializeToString=function(e,t,r,n){return cb.call(e,t,r,n)};pe.prototype.toString=cb;function cb(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],a=this.nodeType==9&&this.documentElement||this,o=a.prefix,s=a.namespaceURI;if(s&&o==null){var o=a.lookupPrefix(s);if(o==null)var l=[{namespace:s,prefix:null}]}return xp(this,i,e,t,l,n),i.join("")}function Ky(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ko.XML||i===Ko.XMLNS)return!1;for(var a=r.length;a--;){var o=r[a];if(o.prefix===n)return o.namespace!==i}return!0}function Ml(e,t,r,n){if(n&&!ya.test(t))throw new ie(Er,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,nb),'"')}function xp(e,t,r,n,i,a){i||(i=[]),Xe(e,{ns:i,isHTML:r},{enter:function(o,s){var l=s.ns,u=s.isHTML;if(n)if(o=n(o),o){if(typeof o=="string")return t.push(o),null}else return null;switch(o.nodeType){case ar:var c=o.attributes,d=c.length,p=o.tagName;u=Ko.isHTML(o.namespaceURI)||u;var f=p;if(!u&&!o.prefix&&o.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var v=l.length-1;v>=0;v--){var b=l[v];if(b.prefix===""&&b.namespace===o.namespaceURI){m=b.namespace;break}}if(m!==o.namespaceURI)for(var v=l.length-1;v>=0;v--){var b=l[v];if(b.namespace===o.namespaceURI){b.prefix&&(f=b.prefix+":"+p);break}}}if(a&&!ya.test(f))throw new ie(Er,'The element name "'+f+'" is not a valid XML QName');t.push("<",f);for(var E=l.slice(),C=0;C<d;C++){var N=c.item(C);N.prefix=="xmlns"?E.push({prefix:N.localName,namespace:N.value}):N.nodeName=="xmlns"&&E.push({prefix:"",namespace:N.value})}for(var C=0;C<d;C++){var N=c.item(C);if(Ky(N,u,E)){var R=N.prefix||"",O=N.namespaceURI;Ml(t,R?"xmlns:"+R:"xmlns",O,a),E.push({prefix:R,namespace:O})}var F=n?n(N):N;F&&(typeof F=="string"?t.push(F):Ml(t,F.name,F.value,a))}if(p===f&&Ky(o,u,E)){var k=o.prefix||"",O=o.namespaceURI;Ml(t,k?"xmlns:"+k:"xmlns",O,a),E.push({prefix:k,namespace:O})}var P=o.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;P;)P.data?t.push(P.data):xp(P,t,u,n,E.slice(),a),P=P.nextSibling;return t.push("</",p,">"),null}return{ns:E,isHTML:u,tag:f}}else return t.push("/>"),null;case Xy:case vn:return{ns:l.slice(),isHTML:u,tag:null};case ba:return Ml(t,o.name,o.value,a),null;case Ho:return t.push(o.data.replace(/[<&>]/g,nb)),null;case Jy:if(a&&o.data.indexOf("]]>")!==-1)throw new ie(Er,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",o.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case Np:if(a&&o.data.indexOf("-->")!==-1)throw new ie(Er,'The comment node data contains "-->"');return t.push("<!--",o.data,"-->"),null;case Yy:if(a){if(!ya.test(o.name))throw new ie(Er,'The doctype name "'+o.name+'" is not a valid XML Name');if(o.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(o.publicId))throw new ie(Er,"DocumentType publicId is not a valid PubidLiteral");if(o.systemId&&!/^("[^"]*"|'[^']*')$/.test(o.systemId))throw new ie(Er,"DocumentType systemId is not a valid SystemLiteral");if(o.internalSubset&&o.internalSubset.indexOf("]>")!==-1)throw new ie(Er,'DocumentType internalSubset contains "]>"')}var V=o.publicId,q=o.systemId;if(t.push("<!DOCTYPE ",o.name),V)t.push(" PUBLIC ",V),q&&q!="."&&t.push(" ",q),t.push(">");else if(q&&q!=".")t.push(" SYSTEM ",q,">");else{var ze=o.internalSubset;ze&&t.push(" [",ze,"]"),t.push(">")}return null;case Sp:if(a){if(!ya.test(o.target)||o.target.indexOf(":")!==-1||o.target.toLowerCase()==="xml")throw new ie(Er,'The processing instruction target "'+o.target+'" is not a valid XML NCName or is reserved');if(o.data.indexOf("?>")!==-1)throw new ie(Er,'The ProcessingInstruction data contains "?>"')}return t.push("<?",o.target," ",o.data,"?>"),null;case Qy:if(a&&!ya.test(o.nodeName))throw new ie(Er,'The entity reference name "'+o.nodeName+'" is not a valid XML Name');return t.push("&",o.nodeName,";"),null;default:return t.push("??",o.nodeName),null}},exit:function(o,s){s&&s.tag&&t.push("</",s.tag,">")}})}function qk(e,t,r){var n;return Xe(t,null,{enter:function(i,a){var o=i.cloneNode(!1);o.ownerDocument=e,o.parentNode=null,a===null?n=o:a.appendChild(o);var s=i.nodeType===ba||r;return s?o:null}}),n}function db(e,t,r){var n;return Xe(t,null,{enter:function(i,a){var o=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=o[s]&&(o[s]=l)}i.childNodes&&(o.childNodes=new yn),o.ownerDocument=e;var u=r;switch(o.nodeType){case ar:var c=i.attributes,d=o.attributes=new Bl,p=c.length;d._ownerElement=o;for(var f=0;f<p;f++)o.setAttributeNode(db(e,c.item(f),!0));break;case ba:u=!0}return a!==null?a.appendChild(o):n=o,u?o:null}}),n}function pb(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(wa.prototype,"length",{get:function(){return Dp(this),this.$$length}}),Object.defineProperty(pe.prototype,"textContent",{get:function(){if(this.nodeType===ar||this.nodeType===vn){var e=[];return Xe(this,null,{enter:function(t){if(t.nodeType===ar||t.nodeType===vn)return!0;if(t.nodeType===Sp||t.nodeType===Np)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case ar:case vn:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),pb=function(e,t,r){e["$$"+t]=r})}catch{}wn.DocumentType=Gl;wn.DOMException=ie;wn.DOMImplementation=rb;wn.Element=Ii;wn.Node=pe;wn.NodeList=yn;wn.walkDOM=Xe;wn.XMLSerializer=ub});var mb=y(Zo=>{"use strict";var fb=va().freeze;Zo.XML_ENTITIES=fb({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Zo.HTML_ENTITIES=fb({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`
-`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});Zo.entityMap=Zo.HTML_ENTITIES});var bb=y(kp=>{var rs=va().NAMESPACE,Lp=va().tagNamePattern,Aa=0,Jn=1,Ea=2,es=3,Ca=4,Sa=5,ts=6,Wl=7;function Na(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Na)}Na.prototype=new Error;Na.prototype.name=Na.name;function vb(){}vb.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),jk(t,t={}),Vk(e,t,r,n,this.errorHandler),n.endDocument()}};function Vk(e,t,r,n,i){function a(Z){if(Z>65535){Z-=65536;var ye=55296+(Z>>10),xe=56320+(Z&1023);return String.fromCharCode(ye,xe)}else return String.fromCharCode(Z)}function o(Z){var ye=Z.slice(1,-1);return Object.hasOwnProperty.call(r,ye)?r[ye]:ye.charAt(0)==="#"?a(parseInt(ye.substr(1).replace("x","0x"))):(i.error("entity not found:"+Z),Z)}function s(Z){if(Z>h){var ye=e.substring(h,Z).replace(/&#?\w+;/g,o);p&&l(h),n.characters(ye,0,Z-h),h=Z}}function l(Z,ye){for(;Z>=c&&(ye=d.exec(e));)u=ye.index,c=u+ye[0].length,p.lineNumber++;p.columnNumber=Z-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],m={},h=0;;){try{var v=e.indexOf("<",h);if(v<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,E=b.createTextNode(e.substr(h));b.appendChild(E),n.currentElement=E}return}switch(v>h&&s(v),e.charAt(v+1)){case"/":var q=e.indexOf(">",v+3),C=e.substring(v+2,q).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),N=f.pop();q<0?(C=e.substring(v+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+N.tagName),q=v+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),q=v+1+C.length):/[ \t\n\r]/.test(C)&&Lp.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var R=N.localNSMap,O=N.tagName==C,F=O||N.tagName&&N.tagName.toLowerCase()==C.toLowerCase();if(F){if(n.endElement(N.uri,N.localName,C),R)for(var k in R)Object.prototype.hasOwnProperty.call(R,k)&&n.endPrefixMapping(k);O||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+N.tagName)}else f.push(N);q++;break;case"?":p&&l(v),q=Kk(e,v,n);break;case"!":p&&l(v),q=Hk(e,v,n,i);break;default:p&&l(v);var P=new yb,V=f[f.length-1].currentNSMap,q=Gk(e,v,P,V,o,i),ze=P.length;if(!P.closed&&Wk(e,q,P.tagName,m)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&ze){for(var Tt=hb(p,{}),Be=0;Be<ze;Be++){var Qe=P[Be];l(Qe.offset),Qe.locator=hb(p,{})}n.locator=Tt,gb(P,n,V)&&f.push(P),n.locator=p}else gb(P,n,V)&&f.push(P);rs.isHTML(P.uri)&&!P.closed?q=zk(e,q,P.tagName,o,n):q++}}catch(Z){if(Z instanceof Na)throw Z;i.error("element parse error: "+Z),q=-1}q>h?h=q:s(Math.max(v,h)+1)}}function hb(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function Gk(e,t,r,n,i,a){function o(f,m,h){r.attributeNames.hasOwnProperty(f)&&a.fatalError("Attribute "+f+" redefined"),r.addValue(f,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Aa;;){var d=e.charAt(u);if(c===Aa&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===Jn)s=e.slice(t,u),c=es;else if(c===Ea)c=es;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===es||c===Jn)if(c===Jn&&(a.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),o(s,l,t-1),c=Sa;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ca)l=e.slice(t,u),o(s,l,t),a.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Sa;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Aa:r.setTagName(e.slice(t,u));case Sa:case ts:case Wl:c=Wl,r.closed=!0;case Ca:case Jn:break;case Ea:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return a.error("unexpected end of input"),c==Aa&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Aa:r.setTagName(e.slice(t,u));case Sa:case ts:case Wl:break;case Ca:case Jn:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ea:c===Ea&&(l=s),c==Ca?(a.warning('attribute "'+l+'" missed quot(")!'),o(s,l,t)):((!rs.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),o(l,l,t));break;case es:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Aa:r.setTagName(e.slice(t,u)),c=ts;break;case Jn:s=e.slice(t,u),c=Ea;break;case Ca:var l=e.slice(t,u);a.warning('attribute "'+l+'" missed quot(")!!'),o(s,l,t);case Sa:c=ts;break}else switch(c){case Ea:var p=r.tagName;(!rs.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&a.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),o(s,s,t),t=u,c=Jn;break;case Sa:a.warning('attribute space is required"'+s+'"!!');case ts:c=Jn,t=u;break;case es:c=Ca,t=u;break;case Wl:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function gb(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var a=e[d],o=a.qName,s=a.value,p=o.indexOf(":");if(p>0)var l=a.prefix=o.slice(0,p),u=o.slice(p+1),c=l==="xmlns"&&u;else u=o,l=null,c=o==="xmlns"&&"";a.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,a.uri=rs.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){a=e[d];var l=a.prefix;l&&(l==="xml"&&(a.uri=rs.XML),l!=="xmlns"&&(a.uri=r[l||""]))}var p=n.indexOf(":");p>0?(l=e.prefix=n.slice(0,p),u=e.localName=n.slice(p+1)):(l=null,u=e.localName=n);var f=e.uri=r[l||""];if(t.startElement(f,u,n,e),e.closed){if(t.endElement(f,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function zk(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var a=e.indexOf("</"+r+">",t),o=e.substring(t+1,a);if(/[&<]/.test(o))return/^script$/i.test(r)?(i.characters(o,0,o.length),a):(o=o.replace(/&#?\w+;/g,n),i.characters(o,0,o.length),a)}return t+1}function Wk(e,t,r,n){var i=n[r];return i==null&&(i=e.lastIndexOf("</"+r+">"),i<t&&(i=e.lastIndexOf("</"+r)),n[r]=i),i<t}function jk(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Hk(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var a=e.indexOf("-->",t+4);return a>t?(r.comment(e,t+4,a-t-4),a+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var a=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,a-t-9),r.endCDATA(),a+3}var o=Jk(e,t),s=o.length;if(s>1&&/!doctype/i.test(o[0][0])){var l=o[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(o[2][0])?(u=o[3][0],c=s>4&&o[4][0]):/^system$/i.test(o[2][0])&&(c=o[3][0]));var d=o[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function Kk(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var a=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function yb(){this.attributeNames={}}yb.prototype={setTagName:function(e){if(!Lp.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Lp.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function Jk(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}kp.XMLReader=vb;kp.ParseError=Na});var Db=y(Hl=>{var Qk=va(),Xk=Fp(),wb=mb(),Cb=bb(),Yk=Xk.DOMImplementation,Ab=Qk.NAMESPACE,Zk=Cb.ParseError,eM=Cb.XMLReader;function Sb(e){return e.replace(/\r[\n\u0085]/g,`
+`);if(f===-1)return;let m=p.slice(0,f),h=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let y=(o=/^Content-ID:\s*(\S+)/im.exec(m))===null||o===void 0?void 0:o[1];if(y===void 0||d.has(y)||!u.has(y))return;d.add(y),c.push(Number(g[1]))}return c.length===0?void 0:c}ei.parseChangeSetStatuses=Hy;async function eM(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=jy(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,ZF.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new ki.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=Hy(a.body,o);if(l===void 0)throw new ki.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new ki.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new ki.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}ei.postChangeSet=eM});var Vl=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.updateTable=Y.deleteAlternateKey=Y.createAlternateKey=Y.deleteGlobalOptionSet=Y.createGlobalOptionSet=Y.deleteRelationship=Y.deleteColumn=Y.updateColumn=Y.deleteTable=Y.createRelationship=Y.insertStatusValue=Y.createCustomerColumn=Y.createColumns=Y.setColumnVisualization=Y.getColumnVisualization=Y.createColumn=Y.createTable=Y.resolveEntitySetName=Y.pluralFallback=void 0;var pe=be(),J=ae(),Wr=Li(),we=re(),tM=ql(),rM={String:"Microsoft.Dynamics.CRM.StringAttributeMetadata",Memo:"Microsoft.Dynamics.CRM.MemoAttributeMetadata",Integer:"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",Decimal:"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",Money:"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",Boolean:"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",DateTime:"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",Picklist:"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",Lookup:"Microsoft.Dynamics.CRM.LookupAttributeMetadata"};function xe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:nM(e,t)}}var Ky=65535;function nM(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new we.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new we.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>Ky)throw new we.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${Ky})`);if(i.has(s))throw new we.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new we.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function Yy(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new we.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}Y.pluralFallback=Yy;function ts(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function _p(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Jy(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function rs(e){let t=(0,pe.readCreatedId)(e,"MetadataId");if(!t)throw new we.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function iM(e,t,r){var n,i,o,a,s,l,u,c,d,p,f,m,h,g,y,w,C,S,T,O,k,F,P,q;if(t.defaultValue!==void 0&&e!=="boolean")throw new we.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new we.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(p=t.precision)!==null&&p!==void 0?p:2,MinValue:(f=t.minValue)!==null&&f!==void 0?f:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(y=t.maxValue)!==null&&y!==void 0?y:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:xe((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:xe((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(T=t.dateFormat)!==null&&T!==void 0?T:"DateAndTime"};case"choice":return Qy(t,r,!1);case"multiChoice":return Qy(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(O=t.maxSizeKb)!==null&&O!==void 0?O:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(k=t.isPrimaryImage)!==null&&k!==void 0?k:!1,MaxSizeInKB:(F=t.maxSizeKb)!==null&&F!==void 0?F:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(P=t.maxLength)!==null&&P!==void 0?P:100,AutoNumberFormat:(q=t.autoNumberFormat)!==null&&q!==void 0?q:""};default:throw new we.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Qy(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,J.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new we.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:xe(o.label,t)}))},i}var Np=new WeakMap;async function oM(e,t){var r,n;let i=(r=Np.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new we.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Np.get(e);return l||(l=new Map,Np.set(e,l)),l.set(t,s),s}Y.resolveEntitySetName=oM;async function aM(e,t){var r,n,i,o,a,s,l,u,c,d,p,f,m,h,g;let y=(r=t.languageCode)!==null&&r!==void 0?r:Wr.DEFAULT_LCID,w=_p(t.schemaName),C=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${w}_Name`,S={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:C,RequiredLevel:ts("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:xe((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",y),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(S.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&tb(t.columns,"createTable");let T={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:xe(t.displayName,y),DisplayCollectionName:xe((a=t.pluralName)!==null&&a!==void 0?a:Yy(t.displayName),y),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[S,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Je=>Ip(Je,y))]};t.description&&(T.Description=xe(t.description,y));let O="/EntityDefinitions",k=(0,pe.ensureSuccess)(await e.post(O,T),e.apiUrl(O)),F=rs(k),P=`/EntityDefinitions(${F})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),q=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),V=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),Ve;for(let Je=1;Je<=q;Je+=1){let Ge=await e.get(P);if(Ge.status>=200&&Ge.status<300){Ve=Ge;break}Ge.status!==404&&(0,pe.ensureSuccess)(Ge,e.apiUrl(P)),Je<q&&V>0&&await new Promise(Z=>setTimeout(Z,V))}if(!Ve)throw new we.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${F}) but its metadata was still not readable after ${q} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${F}) once the environment catches up, or raise 'readBackAttempts'.`);let Pt=Ve.body;return{logicalName:(f=Pt.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:F,entitySetName:(m=Pt.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=Pt.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=Pt.PrimaryNameAttribute)!==null&&g!==void 0?g:C.toLowerCase()}}Y.createTable=aM;function Ip(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...iM(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:ts((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:xe(e.displayName,i)};return e.description&&(o.Description=xe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),Zy(o,e),o}function Zy(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function sM(e,t,r){var n;let i=Ip(r,(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,a=(0,pe.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:rs(a)};if(r.visualization&&r.visualization!=="None")try{await ib(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new we.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw u.cause=l,u}return s}Y.createColumn=sM;var No="/controlconfigurations",eb="CustomRenderersConfiguration",Dp={RadialDial:"c3d4e5f6-a7b8-9012-cdef-345678901234",LineChart:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",HeatMap:"e7f8a9b0-c1d2-4e3f-5a6b-7c8d9e0f1a2b",StarRating:"b5e4c3d2-f1a0-4e2b-8a7c-9d3f5c1e6b04"};function tb(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new we.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${r.schemaName}') is not supported \u2014 the attribute metadata and its control-configuration row are separate writes. Create the column, then call setColumnVisualization; or use the single-column createColumn.`)}function rb(e){return JSON.stringify({type:Dp[e]})}function lM(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Dp).find(i=>Dp[i]===r);return n??"None"}async function nb(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,a=`${No}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,pe.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,p;return((p=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||p===void 0?void 0:p.toLowerCase())===u})}async function uM(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,pe.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new we.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(a,"MetadataId")}async function ib(e,t,r,n,i){let o={name:eb,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:rb(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,pe.ensureSuccess)(await e.post(No,o),e.apiUrl(No))}async function cM(e,t,r){var n;let i=await nb(e,t,r);return lM((n=i[0])===null||n===void 0?void 0:n.metadatajson)}Y.getColumnVisualization=cM;async function dM(e,t,r,n){let o=(await nb(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${No}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,pe.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await uM(e,t,r);if(a){let u=`${No}(${(0,J.normalizeGuid)(a,"controlconfigurationid")})`,c={name:eb,metadatajson:rb(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,pe.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await ib(e,t,r,l,n);for(let u of s){let c=`${No}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,pe.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Y.setColumnVisualization=dM;async function pM(e,t,r){if(r.length===0)return;if(tb(r,"createColumns"),!e.supportsAtomicBatch)throw new we.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`;await(0,tM.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Ip(i,(o=i.languageCode)!==null&&o!==void 0?o:Wr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}Y.createColumns=pM;async function fM(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,l=_p(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:xe(r.displayName,s),RequiredLevel:ts((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,pe.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}Y.createCustomerColumn=fM;async function mM(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:xe(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,pe.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}Y.insertStatusValue=mM;async function hM(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Wr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new we.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${_p(t.schemaName)}_${t.referencedEntity}Id`;u=p.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:p,RequiredLevel:ts((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:xe((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new we.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,pe.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:rs(d),lookupLogicalName:u}}Y.createRelationship=hM;async function gM(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`;(0,pe.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Y.deleteTable=gM;async function vM(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Wr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,pe.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=rM[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d)throw new we.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,J.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,m=(0,pe.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let g of Object.keys(m))g.startsWith("@odata.")&&delete m[g];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=xe(n.displayName,a)),n.description!==void 0&&(m.Description=xe(n.description,a)),n.required!==void 0&&(m.RequiredLevel=ts(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new we.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new we.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),Zy(m,n);let h=`${s}(${p})`;(0,pe.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}Y.updateColumn=vM;async function yM(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,pe.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Y.deleteColumn=yM;async function bM(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,J.odataQuery)([["$filter",`SchemaName eq '${(0,J.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new we.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,pe.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Y.deleteRelationship=bM;async function Xy(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,pe.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,J.normalizeGuid)(a,"MetadataId"):void 0}async function wM(e,t){var r;let n=t.name.toLowerCase(),i=await Xy(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Wr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:xe(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:xe(l.label,o)}))};t.description&&(a.Description=xe(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,pe.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:rs(l)}}catch(l){let u;try{u=await Xy(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}Y.createGlobalOptionSet=wM;async function AM(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t.toLowerCase())}')`;(0,pe.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Y.deleteGlobalOptionSet=AM;async function EM(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:xe(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,s=(0,pe.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:rs(s)}}Y.createAlternateKey=EM;async function CM(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,J.odataPathLiteral)(r.toLowerCase())}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,pe.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Y.deleteAlternateKey=CM;async function SM(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`,s=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new we.InvalidArgumentError(`table '${t}' not found`);let u=(0,J.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=xe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=xe(r.pluralName,i)),r.description!==void 0&&(s.Description=xe(r.description,i)),r.auditEnabled!==void 0&&Jy(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Jy(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,pe.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Y.updateTable=SM});var ri=b(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.rebuildRaw=xt.assembleChildren=xt.spliceChildren=xt.mergeAttrs=xt.rawFromNode=xt.emptyBag=void 0;var ti=re(),ob=1e6,zl=512;function NM(){return{a:[],c:[]}}xt.emptyBag=NM;function ab(e,t=0){if(t>zl)throw new ti.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${zl}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>ab(r,t+1))}}xt.rawFromNode=ab;function DM(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}xt.mergeAttrs=DM;function Gl(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>ob)throw new ti.InvalidArgumentError(`Bag child index must be an integer in [0, ${ob}] (got ${String(l)})`);if(r.has(l))throw new ti.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}xt.spliceChildren=Gl;function _M(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Gl(e.w.c,t)};return Gl(e.c,[r])}return Gl(e.c,t)}xt.assembleChildren=_M;function sb(e,t,r,n=0){if(n>zl)throw new ti.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${zl}`);IM(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,sb(o,t,i,n+1));return i}xt.rebuildRaw=sb;function IM(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ti.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ti.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(r.a)||!Array.isArray(r.c))throw new ti.InvalidArgumentError(`Malformed hybrid node '${r.n}': 'a' and 'c' must be arrays`);for(let n of r.a)if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")throw new ti.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Do=b(wn=>{"use strict";function TM(e,t,r){if(r===void 0&&(r=Array.prototype),e&&typeof r.find=="function")return r.find.call(e,t);for(var n=0;n<e.length;n++)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];if(t.call(void 0,i,n,e))return i}}function Pp(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function PM(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}var lb=Pp({HTML:"text/html",isHTML:function(e){return e===lb.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),ub=Pp({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===ub.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Wl=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,Tp=new RegExp("[\\-\\.0-9"+Wl.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),RM=new RegExp("^"+Wl.source+Tp.source+"*(?::"+Wl.source+Tp.source+"*)?$");wn.assign=PM;wn.find=TM;wn.freeze=Pp;wn.MIME_TYPE=lb;wn.NAMESPACE=ub;wn.nameStartChar=Wl;wn.nameChar=Tp;wn.tagNamePattern=RM});var Vp=b(Sn=>{var Rp=Do(),jr=Rp.find,is=Rp.NAMESPACE,_o=Rp.tagNamePattern;function OM(e){return e!==""}function xM(e){return e?e.split(/[\t\n\f\r ]+/).filter(OM):[]}function LM(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function cb(e){if(!e)return[];var t=xM(e);return Object.keys(t.reduce(LM,{}))}function kM(e){return function(t){return e&&e.indexOf(t)!==-1}}function as(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function kt(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,as(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Ft={},or=Ft.ELEMENT_NODE=1,Io=Ft.ATTRIBUTE_NODE=2,ns=Ft.TEXT_NODE=3,yb=Ft.CDATA_SECTION_NODE=4,bb=Ft.ENTITY_REFERENCE_NODE=5,FM=Ft.ENTITY_NODE=6,Op=Ft.PROCESSING_INSTRUCTION_NODE=7,xp=Ft.COMMENT_NODE=8,wb=Ft.DOCUMENT_NODE=9,Ab=Ft.DOCUMENT_TYPE_NODE=10,An=Ft.DOCUMENT_FRAGMENT_NODE=11,MM=Ft.NOTATION_NODE=12,pt={},Ye={},aX=pt.INDEX_SIZE_ERR=(Ye[1]="Index size error",1),sX=pt.DOMSTRING_SIZE_ERR=(Ye[2]="DOMString size error",2),Lt=pt.HIERARCHY_REQUEST_ERR=(Ye[3]="Hierarchy request error",3),lX=pt.WRONG_DOCUMENT_ERR=(Ye[4]="Wrong document",4),db=pt.INVALID_CHARACTER_ERR=(Ye[5]="Invalid character",5),uX=pt.NO_DATA_ALLOWED_ERR=(Ye[6]="No data allowed",6),cX=pt.NO_MODIFICATION_ALLOWED_ERR=(Ye[7]="No modification allowed",7),Eb=pt.NOT_FOUND_ERR=(Ye[8]="Not found",8),dX=pt.NOT_SUPPORTED_ERR=(Ye[9]="Not supported",9),pb=pt.INUSE_ATTRIBUTE_ERR=(Ye[10]="Attribute in use",10),Sr=pt.INVALID_STATE_ERR=(Ye[11]="Invalid state",11),pX=pt.SYNTAX_ERR=(Ye[12]="Syntax error",12),fX=pt.INVALID_MODIFICATION_ERR=(Ye[13]="Invalid modification",13),mX=pt.NAMESPACE_ERR=(Ye[14]="Invalid namespace",14),hX=pt.INVALID_ACCESS_ERR=(Ye[15]="Invalid access",15);function ie(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ye[e]),this.message=Ye[e],Error.captureStackTrace&&Error.captureStackTrace(this,ie);return r.code=e,t&&(this.message=this.message+": "+t),r}ie.prototype=Error.prototype;as(pt,ie);function En(){}En.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)qp(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function To(e,t){this._node=e,this._refresh=t,Lp(this)}function Lp(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(kb(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];as(r,e),e._inc=t}}To.prototype.item=function(e){return Lp(this),this[e]||null};kt(To,En);function Hl(){this._nameIndex=Object.create(null)}function Cb(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function BM(e,t){e._nameIndex[t.nodeName]=t}function Sb(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function fb(e,t,r,n){if(n?(t[Cb(t,n)]=r,Sb(t,n)):t[t.length++]=r,BM(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&_b(i,e,n),$M(i,e,r))}}function mb(e,t,r){var n=Cb(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,Sb(t,r),e){var o=e.ownerDocument;o&&(_b(o,e,r),r.ownerElement=null)}}else throw new ie(Eb,new Error(e.tagName+"@"+r))}Hl.prototype={length:0,item:En.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new ie(pb);var r=this._nameIndex[e.nodeName];return fb(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new ie(pb);return r=this.getNamedItemNS(e.namespaceURI,e.localName),fb(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return mb(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return mb(this._ownerElement,this,r),r},getNamedItemNS:function(e,t){for(var r=this.length;r--;){var n=this[r];if(n.localName==t&&n.namespaceURI==e)return n}return null}};function Nb(){}Nb.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new ss;if(n.implementation=this,n.childNodes=new En,n.doctype=r||null,r&&n.appendChild(r),t){var i=n.createElementNS(e,t);n.appendChild(i)}return n},createDocumentType:function(e,t,r){var n=new Yl;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function me(){}me.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Jl(this,e,t)},replaceChild:function(e,t){Jl(this,e,t,Tb),t&&this.removeChild(t)},removeChild:function(e){return Ib(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return Lb(this.ownerDocument||this,this,e)},normalize:function(){Xe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===ns&&t.nodeType===ns){for(var n=[],i=r;i!==null&&i.nodeType===ns;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Xl(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Io?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==Io?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function Db(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}as(Ft,me);as(Ft,me.prototype);function Kl(e,t){return Xe(e,null,{enter:function(r){return t(r)?Xe.STOP:!0}})===Xe.STOP}function Xe(e,t,r){for(var n=[{node:e,context:t,phase:Xe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Xe.ENTER){var o=r.enter(i.node,i.context);if(o===Xe.STOP)return Xe.STOP;if(n.push({node:i.node,context:o,phase:Xe.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:Xe.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Xe.STOP=Symbol("walkDOM.STOP");Xe.ENTER=0;Xe.EXIT=1;function ss(){this.ownerDocument=this}function $M(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===is.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function _b(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===is.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Xl(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function Ib(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,Xl(e.ownerDocument,e),t}function UM(e){return e&&(e.nodeType===me.DOCUMENT_NODE||e.nodeType===me.DOCUMENT_FRAGMENT_NODE||e.nodeType===me.ELEMENT_NODE)}function qM(e){return e&&(Hr(e)||kp(e)||Cn(e)||e.nodeType===me.DOCUMENT_FRAGMENT_NODE||e.nodeType===me.COMMENT_NODE||e.nodeType===me.PROCESSING_INSTRUCTION_NODE)}function Cn(e){return e&&e.nodeType===me.DOCUMENT_TYPE_NODE}function Hr(e){return e&&e.nodeType===me.ELEMENT_NODE}function kp(e){return e&&e.nodeType===me.TEXT_NODE}function hb(e,t){var r=e.childNodes||[];if(jr(r,Hr)||Cn(t))return!1;var n=jr(r,Cn);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function gb(e,t){var r=e.childNodes||[];function n(o){return Hr(o)&&o!==t}if(jr(r,n))return!1;var i=jr(r,Cn);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function VM(e,t,r){if(!UM(e))throw new ie(Lt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new ie(Eb,"child not in parent");if(!qM(t)||Cn(t)&&e.nodeType!==me.DOCUMENT_NODE)throw new ie(Lt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function GM(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===me.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Hr);if(o.length>1||jr(i,kp))throw new ie(Lt,"More than one element or text in fragment");if(o.length===1&&!hb(e,r))throw new ie(Lt,"Element in fragment can not be inserted before doctype")}if(Hr(t)&&!hb(e,r))throw new ie(Lt,"Only one element can be added and only after doctype");if(Cn(t)){if(jr(n,Cn))throw new ie(Lt,"Only one doctype is allowed");var a=jr(n,Hr);if(r&&n.indexOf(a)<n.indexOf(r))throw new ie(Lt,"Doctype can only be inserted before an element");if(!r&&a)throw new ie(Lt,"Doctype can not be appended since element is present")}}function Tb(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===me.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Hr);if(o.length>1||jr(i,kp))throw new ie(Lt,"More than one element or text in fragment");if(o.length===1&&!gb(e,r))throw new ie(Lt,"Element in fragment can not be inserted before doctype")}if(Hr(t)&&!gb(e,r))throw new ie(Lt,"Only one element can be added and only after doctype");if(Cn(t)){let l=function(u){return Cn(u)&&u!==r};var s=l;if(jr(n,l))throw new ie(Lt,"Only one doctype is allowed");var a=jr(n,Hr);if(r&&n.indexOf(a)<n.indexOf(r))throw new ie(Lt,"Doctype can only be inserted before an element")}}function Jl(e,t,r,n){VM(e,t,r),e.nodeType===me.DOCUMENT_NODE&&(n||GM)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===An){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;os(o,l)}while(o!==a&&(o=o.nextSibling));return Xl(e.ownerDocument||e,e),t.nodeType==An&&(t.firstChild=t.lastChild=null),t}function os(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===or&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)os(i,t),i=i.nextSibling}}function zM(e,t){t.parentNode&&t.parentNode.removeChild(t),t.parentNode=e,t.previousSibling=e.lastChild,t.nextSibling=null,t.previousSibling?t.previousSibling.nextSibling=t:e.firstChild=t,e.lastChild=t,Xl(e.ownerDocument,e,t);var r=e.ownerDocument||e;return os(t,r),t}ss.prototype={nodeName:"#document",nodeType:wb,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==An){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Jl(this,e,t),os(e,this),this.documentElement===null&&e.nodeType===or&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),Ib(this,e)},replaceChild:function(e,t){Jl(this,e,t,Tb),os(e,this),t&&this.removeChild(t),Hr(e)&&(this.documentElement=e)},importNode:function(e,t){return WM(this,e,t)},getElementById:function(e){var t=null;return Kl(this.documentElement,function(r){if(r.nodeType==or&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=cb(e);return new To(this,function(r){var n=[];return t.length>0&&Kl(r.documentElement,function(i){if(i!==r&&i.nodeType===or){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=cb(o);a=t.every(kM(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Fi;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new En;var r=t.attributes=new Hl;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Zl;return e.ownerDocument=this,e.childNodes=new En,e},createTextNode:function(e){var t=new Fp;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Mp;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new ie(db,'data contains "]]>"');var t=new Bp;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Up;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ql;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!_o.test(e))throw new ie(db,'not a valid xml name "'+e+'"');var t=new $p;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Fi,n=t.split(":"),i=r.attributes=new Hl;return r.childNodes=new En,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new Ql,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};kt(ss,me);function Fi(){this._nsMap={}}Fi.prototype={nodeType:or,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===An?this.insertBefore(e,null):zM(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new To(this,function(t){var r=[];return Kl(t,function(n){n!==t&&n.nodeType==or&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new To(this,function(r){var n=[];return Kl(r,function(i){i!==r&&i.nodeType===or&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};ss.prototype.getElementsByTagName=Fi.prototype.getElementsByTagName;ss.prototype.getElementsByTagNameNS=Fi.prototype.getElementsByTagNameNS;kt(Fi,me);function Ql(){}Ql.prototype.nodeType=Io;kt(Ql,me);function ls(){}ls.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(Ye[Lt])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};kt(ls,me);function Fp(){}Fp.prototype={nodeName:"#text",nodeType:ns,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};kt(Fp,ls);function Mp(){}Mp.prototype={nodeName:"#comment",nodeType:xp};kt(Mp,ls);function Bp(){}Bp.prototype={nodeName:"#cdata-section",nodeType:yb};kt(Bp,ls);function Yl(){}Yl.prototype.nodeType=Ab;kt(Yl,me);function Pb(){}Pb.prototype.nodeType=MM;kt(Pb,me);function Rb(){}Rb.prototype.nodeType=FM;kt(Rb,me);function $p(){}$p.prototype.nodeType=bb;kt($p,me);function Zl(){}Zl.prototype.nodeName="#document-fragment";Zl.prototype.nodeType=An;kt(Zl,me);function Up(){}Up.prototype.nodeType=Op;kt(Up,me);function Ob(){}Ob.prototype.serializeToString=function(e,t,r,n){return xb.call(e,t,r,n)};me.prototype.toString=xb;function xb(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return qp(this,i,e,t,l,n),i.join("")}function vb(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===is.XML||i===is.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function jl(e,t,r,n){if(n&&!_o.test(t))throw new ie(Sr,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,Db),'"')}function qp(e,t,r,n,i,o){i||(i=[]),Xe(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case or:var c=a.attributes,d=c.length,p=a.tagName;u=is.isHTML(a.namespaceURI)||u;var f=p;if(!u&&!a.prefix&&a.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var g=l.length-1;g>=0;g--){var y=l[g];if(y.prefix===""&&y.namespace===a.namespaceURI){m=y.namespace;break}}if(m!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var y=l[g];if(y.namespace===a.namespaceURI){y.prefix&&(f=y.prefix+":"+p);break}}}if(o&&!_o.test(f))throw new ie(Sr,'The element name "'+f+'" is not a valid XML QName');t.push("<",f);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(vb(S,u,w)){var T=S.prefix||"",O=S.namespaceURI;jl(t,T?"xmlns:"+T:"xmlns",O,o),w.push({prefix:T,namespace:O})}var k=n?n(S):S;k&&(typeof k=="string"?t.push(k):jl(t,k.name,k.value,o))}if(p===f&&vb(a,u,w)){var F=a.prefix||"",O=a.namespaceURI;jl(t,F?"xmlns:"+F:"xmlns",O,o),w.push({prefix:F,namespace:O})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;P;)P.data?t.push(P.data):qp(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",p,">"),null}return{ns:w,isHTML:u,tag:f}}else return t.push("/>"),null;case wb:case An:return{ns:l.slice(),isHTML:u,tag:null};case Io:return jl(t,a.name,a.value,o),null;case ns:return t.push(a.data.replace(/[<&>]/g,Db)),null;case yb:if(o&&a.data.indexOf("]]>")!==-1)throw new ie(Sr,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case xp:if(o&&a.data.indexOf("-->")!==-1)throw new ie(Sr,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case Ab:if(o){if(!_o.test(a.name))throw new ie(Sr,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new ie(Sr,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new ie(Sr,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new ie(Sr,'DocumentType internalSubset contains "]>"')}var q=a.publicId,V=a.systemId;if(t.push("<!DOCTYPE ",a.name),q)t.push(" PUBLIC ",q),V&&V!="."&&t.push(" ",V),t.push(">");else if(V&&V!=".")t.push(" SYSTEM ",V,">");else{var Ve=a.internalSubset;Ve&&t.push(" [",Ve,"]"),t.push(">")}return null;case Op:if(o){if(!_o.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new ie(Sr,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new ie(Sr,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case bb:if(o&&!_o.test(a.nodeName))throw new ie(Sr,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function WM(e,t,r){var n;return Xe(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===Io||r;return s?a:null}}),n}function Lb(e,t,r){var n;return Xe(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new En),a.ownerDocument=e;var u=r;switch(a.nodeType){case or:var c=i.attributes,d=a.attributes=new Hl,p=c.length;d._ownerElement=a;for(var f=0;f<p;f++)a.setAttributeNode(Lb(e,c.item(f),!0));break;case Io:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function kb(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(To.prototype,"length",{get:function(){return Lp(this),this.$$length}}),Object.defineProperty(me.prototype,"textContent",{get:function(){if(this.nodeType===or||this.nodeType===An){var e=[];return Xe(this,null,{enter:function(t){if(t.nodeType===or||t.nodeType===An)return!0;if(t.nodeType===Op||t.nodeType===xp)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case or:case An:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),kb=function(e,t,r){e["$$"+t]=r})}catch{}Sn.DocumentType=Yl;Sn.DOMException=ie;Sn.DOMImplementation=Nb;Sn.Element=Fi;Sn.Node=me;Sn.NodeList=En;Sn.walkDOM=Xe;Sn.XMLSerializer=Ob});var Mb=b(us=>{"use strict";var Fb=Do().freeze;us.XML_ENTITIES=Fb({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});us.HTML_ENTITIES=Fb({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`
+`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});us.entityMap=us.HTML_ENTITIES});var Vb=b(zp=>{var ps=Do().NAMESPACE,Gp=Do().tagNamePattern,Po=0,ni=1,Ro=2,cs=3,Oo=4,xo=5,ds=6,eu=7;function Lo(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Lo)}Lo.prototype=new Error;Lo.prototype.name=Lo.name;function Ub(){}Ub.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),QM(t,t={}),jM(e,t,r,n,this.errorHandler),n.endDocument()}};function jM(e,t,r,n,i){function o(Z){if(Z>65535){Z-=65536;var ye=55296+(Z>>10),hn=56320+(Z&1023);return String.fromCharCode(ye,hn)}else return String.fromCharCode(Z)}function a(Z){var ye=Z.slice(1,-1);return Object.hasOwnProperty.call(r,ye)?r[ye]:ye.charAt(0)==="#"?o(parseInt(ye.substr(1).replace("x","0x"))):(i.error("entity not found:"+Z),Z)}function s(Z){if(Z>h){var ye=e.substring(h,Z).replace(/&#?\w+;/g,a);p&&l(h),n.characters(ye,0,Z-h),h=Z}}function l(Z,ye){for(;Z>=c&&(ye=d.exec(e));)u=ye.index,c=u+ye[0].length,p.lineNumber++;p.columnNumber=Z-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var y=n.doc,w=y.createTextNode(e.substr(h));y.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var V=e.indexOf(">",g+3),C=e.substring(g+2,V).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=f.pop();V<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),V=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),V=g+1+C.length):/[ \t\n\r]/.test(C)&&Gp.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var T=S.localNSMap,O=S.tagName==C,k=O||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(k){if(n.endElement(S.uri,S.localName,C),T)for(var F in T)Object.prototype.hasOwnProperty.call(T,F)&&n.endPrefixMapping(F);O||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else f.push(S);V++;break;case"?":p&&l(g),V=YM(e,g,n);break;case"!":p&&l(g),V=XM(e,g,n,i);break;default:p&&l(g);var P=new qb,q=f[f.length-1].currentNSMap,V=HM(e,g,P,q,a,i),Ve=P.length;if(!P.closed&&JM(e,V,P.tagName,m)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Ve){for(var Pt=Bb(p,{}),Je=0;Je<Ve;Je++){var Ge=P[Je];l(Ge.offset),Ge.locator=Bb(p,{})}n.locator=Pt,$b(P,n,q)&&f.push(P),n.locator=p}else $b(P,n,q)&&f.push(P);ps.isHTML(P.uri)&&!P.closed?V=KM(e,V,P.tagName,a,n):V++}}catch(Z){if(Z instanceof Lo)throw Z;i.error("element parse error: "+Z),V=-1}V>h?h=V:s(Math.max(g,h)+1)}}function Bb(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function HM(e,t,r,n,i,o){function a(f,m,h){r.attributeNames.hasOwnProperty(f)&&o.fatalError("Attribute "+f+" redefined"),r.addValue(f,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Po;;){var d=e.charAt(u);if(c===Po&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ni)s=e.slice(t,u),c=cs;else if(c===Ro)c=cs;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===cs||c===ni)if(c===ni&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=xo;else throw new Error("attribute value no end '"+d+"' match");else if(c==Oo)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=xo;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Po:r.setTagName(e.slice(t,u));case xo:case ds:case eu:c=eu,r.closed=!0;case Oo:case ni:break;case Ro:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Po&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Po:r.setTagName(e.slice(t,u));case xo:case ds:case eu:break;case Oo:case ni:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ro:c===Ro&&(l=s),c==Oo?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!ps.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case cs:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Po:r.setTagName(e.slice(t,u)),c=ds;break;case ni:s=e.slice(t,u),c=Ro;break;case Oo:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case xo:c=ds;break}else switch(c){case Ro:var p=r.tagName;(!ps.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ni;break;case xo:o.warning('attribute space is required"'+s+'"!!');case ds:c=ni,t=u;break;case cs:c=Oo,t=u;break;case eu:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function $b(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,p=a.indexOf(":");if(p>0)var l=o.prefix=a.slice(0,p),u=a.slice(p+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=ps.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=ps.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var p=n.indexOf(":");p>0?(l=e.prefix=n.slice(0,p),u=e.localName=n.slice(p+1)):(l=null,u=e.localName=n);var f=e.uri=r[l||""];if(t.startElement(f,u,n,e),e.closed){if(t.endElement(f,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function KM(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function JM(e,t,r,n){var i=n[r];return i==null&&(i=e.lastIndexOf("</"+r+">"),i<t&&(i=e.lastIndexOf("</"+r)),n[r]=i),i<t}function QM(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function XM(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=ZM(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function YM(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function qb(){this.attributeNames={}}qb.prototype={setTagName:function(e){if(!Gp.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Gp.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function ZM(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}zp.XMLReader=Ub;zp.ParseError=Lo});var Jb=b(ru=>{var eB=Do(),tB=Vp(),Gb=Mb(),jb=Vb(),rB=tB.DOMImplementation,zb=eB.NAMESPACE,nB=jb.ParseError,iB=jb.XMLReader;function Hb(e){return e.replace(/\r[\n\u0085]/g,`
`).replace(/[\r\u0085\u2028]/g,`
-`)}function Nb(e){this.options=e||{locator:{}}}Nb.prototype.parseFromString=function(e,t){var r=this.options,n=new eM,i=r.domBuilder||new ns,a=r.errorHandler,o=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?wb.HTML_ENTITIES:wb.XML_ENTITIES;o&&i.setDocumentLocator(o),n.errorHandler=tM(a,i,o),n.domBuilder=r.domBuilder||i,l&&(s[""]=Ab.HTML),s.xml=s.xml||Ab.XML;var c=r.normalizeLineEndings||Sb;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function tM(e,t,r){if(!e){if(t instanceof ns)return t;e=t}var n={},i=e instanceof Function;r=r||{};function a(o){var s=e[o];!s&&i&&(s=e.length==2?function(l){e(o,l)}:e),n[o]=s&&function(l){s("[xmldom "+o+"] "+l+Mp(r))}||function(){}}return a("warning"),a("error"),a("fatalError"),n}function ns(){this.cdata=!1}function Da(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}ns.prototype={startDocument:function(){this.doc=new Yk().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,a=i.createElementNS(e,r||t),o=n.length;jl(this,a),this.currentElement=a,this.locator&&Da(this.locator,a);for(var s=0;s<o;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&Da(n.getLocator(s),u),u.value=u.nodeValue=l,a.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&Da(this.locator,r),jl(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Eb.apply(this,arguments),e){if(this.cdata)var n=this.doc.createCDATASection(e);else var n=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(n):/^\s*$/.test(e)&&this.doc.appendChild(n),this.locator&&Da(this.locator,n)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,r){e=Eb.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Da(this.locator,n),jl(this,n)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,r){var n=this.doc.implementation;if(n&&n.createDocumentType){var i=n.createDocumentType(e,t,r);this.locator&&Da(this.locator,i),jl(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Mp(this.locator))},error:function(e){console.error("[xmldom error] "+e,Mp(this.locator))},fatalError:function(e){throw new Zk(e,this.locator)}};function Mp(e){if(e)return`
-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Eb(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){ns.prototype[e]=function(){return null}});function jl(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Hl.__DOMHandler=ns;Hl.normalizeLineEndings=Sb;Hl.DOMParser=Nb});var Jl=y(Kl=>{var Ib=Fp();Kl.DOMImplementation=Ib.DOMImplementation;Kl.XMLSerializer=Ib.XMLSerializer;Kl.DOMParser=Db().DOMParser});var Qn=y(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.installDomShim=void 0;var _b=Jl(),Tb=!1,rM={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};function nM(){if(Tb)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=_b.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=_b.XMLSerializer),typeof e.Node>"u"&&(e.Node=rM),Tb=!0}Ql.installDomShim=nM});var _i=y(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.projectElementBag=Le.serializeNode=Le.domEngine=Le.nodeLikeFromDom=Le.parseXmlRoot=Le.EMPTY_FORM_SENTINEL=Le.TEXT_SENTINEL=void 0;var iM=Kn(),is=te(),aM=Qn();Le.TEXT_SENTINEL="#text";Le.EMPTY_FORM_SENTINEL="#empty";var Yl=new WeakSet;function oM(e,t){(0,aM.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new is.InvalidArgumentError("XML source has no root element (empty or malformed input)");return lM(i),uM(i),pM(i,r),i}Le.parseXmlRoot=oM;var sM=new Set([1,3]);function lM(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];if(!sM.has(a.nodeType))throw new is.InvalidArgumentError(`Unsupported XML node type ${a.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);a.nodeType===1&&t.push(a)}}}function uM(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];if(o!==e&&!(o.nodeType===3&&((r=o.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new is.InvalidArgumentError(`Unsupported document-level XML node (type ${o.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function cM(e){let t=[],r=/<([^>]*)>/g;for(let n=r.exec(e);n!==null;n=r.exec(e)){let i=n[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function dM(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let a=i.length-1;a>=0;a-=1){let o=i[a];o.nodeType===1&&r.push(o)}}return t}function Rb(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function pM(e,t){let r=cM(t),n=dM(e),i=Math.min(r.length,n.length);for(let a=0;a<i;a+=1){if(r[a])continue;let o=n[a];Rb(o)||Yl.add(o)}}function Bp(e){let t=e.nodeType===3;return{getNodeName:()=>t?Le.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Le.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let a=0;a<n.length;a+=1)i.push({key:n[a].name,value:n[a].value});return Yl.has(e)&&!Rb(e)&&i.push({key:Le.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];(a.nodeType===1||a.nodeType===3)&&r.push(Bp(a))}return r}}}Le.nodeLikeFromDom=Bp;function fM(e){return{make:t=>t===Le.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Le.EMPTY_FORM_SENTINEL?Yl.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Le.domEngine=fM;function Ob(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=31&&r!==9&&r!==10&&r!==13||r===65534||r===65535)throw Xl(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Xl(r);t+=1;continue}if(r>=56320&&r<=57343)throw Xl(r)}}function Xl(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new is.InvalidArgumentError(`Value contains U+${t}, a character not permitted in XML 1.0 (control char / lone surrogate / non-character); it cannot be serialized losslessly`)}function mM(e){return Ob(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function hM(e){return Ob(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gM(e){return xb(e,0)}Le.serializeNode=gM;var Pb=512;function xb(e,t){var r;if(t>Pb)throw new is.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${Pb}`);if(e.nodeType===3)return hM((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,a=n.attributes;for(let l=0;l<a.length;l+=1)i+=" "+a[l].name+'="'+mM(a[l].value)+'"';let o=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&o.push(u)}if(o.length===0)return Yl.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of o)i+=xb(l,t+1);return i+"</"+n.tagName+">"}function vM(e){let t=Bp(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,iM.rawFromNode)(r)}))}}Le.projectElementBag=vM});var Cr=y(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.rejectUnknownKeys=ft.childObjects=ft.optionalGuidId=ft.optionalEnum=ft.eachObject=ft.issue=ft.isJsonObject=void 0;function Fb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}ft.isJsonObject=Fb;function Ia(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}ft.issue=Ia;function Lb(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((a,o)=>{Fb(a)?i.push({node:a,index:o}):n.push(Ia(`${t}/${o}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${a===null?"null":typeof a}`))}),i}ft.eachObject=Lb;function yM(e,t,r,n,i,a){let o=e[t];o!==void 0&&(typeof o!="string"||!r.includes(o))&&a.push(Ia(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(o)}`))}ft.optionalEnum=yM;var bM=/^(?:\{[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\}|[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})$/;function wM(e,t,r,n,i){let a=e[t];typeof a=="string"&&a!==""&&!bM.test(a)&&i.push(Ia(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${a}'`))}ft.optionalGuidId=wM;function AM(e,t,r,n,i){let a=e[t],o=`${r}/${t}`;return a===void 0?[]:Array.isArray(a)?Lb(a,o,n,i):(i.push(Ia(o,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof a}`)),[])}ft.childObjects=AM;function EM(e,t,r,n,i,a={}){var o,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(o=a.elsewhere)===null||o===void 0?void 0:o[l],c=(s=a.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Ia(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}ft.rejectUnknownKeys=EM});var Xp=y(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.mintEmbedIdentity=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var CM=Jl(),SM=ca(),Up=lt(),or=Cr();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var NM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function kt(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),NM.test(t)?t:""}B.normGuid=kt;function Xn(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=Xn;function os(e){return le(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=os;function le(e){return Array.isArray(e)?e:[]}function Wp(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function Bb(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function Ub(e){return jr(e).map(t=>t.cell)}B.typedCells=Ub;function jr(e){let t=[];return le(e?.tabs).forEach((r,n)=>{le(ge(r)?r.columns:void 0).forEach((i,a)=>{le(ge(i)?i.sections:void 0).forEach((o,s)=>{le(ge(o)?o.rows:void 0).forEach((l,u)=>{le(ge(l)?l.cells:void 0).forEach((c,d)=>{ge(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${a}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}function An(e){return ge(e)?kt(Wp(e.bag,"uniqueid")):""}B.controlUniqueId=An;function DM(e){let t=new Set;for(let{cell:r}of jr(e)){let n=Ri(r.control)?An(r.control):"";n&&t.add(n)}return t}function IM(e){let t=new Map;for(let{cell:r}of jr(e)){let n=ge(r.control)?An(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function _M(e){return e!==void 0&&e.genPage===void 0&&(Kp(e)!==B.CUSTOM_CONTROL_CLASS_ID||!ru(e))}function $p(e,t){if(ge(e)){t(e);for(let r of le(e.c))$p(r,t)}}function Ti(e,t){var r;if(ge(e)){for(let n of le(e.c))$p(n?.node,t);for(let n of le((r=e.w)===null||r===void 0?void 0:r.c))$p(n?.node,t)}}function eu(e){let t=new Map,r=i=>{var a;i&&t.set(i,((a=t.get(i))!==null&&a!==void 0?a:0)+1)},n=i=>{i.n==="control"&&r(kt(Xn(i,"uniqueid")))};return Ti(e?.bag,n),le(e?.tabs).forEach(i=>{ge(i)&&(Ti(i.bag,n),le(i.columns).forEach(a=>{ge(a)&&(Ti(a.bag,n),le(a.sections).forEach(o=>{ge(o)&&(Ti(o.bag,n),le(o.rows).forEach(s=>{ge(s)&&(Ti(s.bag,n),le(s.cells).forEach(l=>{ge(l)&&(Ti(l.bag,n),ge(l.control)&&(r(An(l.control)),Ti(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=eu;function _a(e){return le(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=_a;function Pi(e,t){var r;let n=kt(t);if(n)return le((r=_a(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&kt(Xn(i,"forControl"))===n)}B.descriptionFor=Pi;function ss(e){return le(e.c).filter($b)}B.pageEntries=ss;function $b(e){return e?.n==="customControl"&&Xn(e,"name")===B.GENPAGE_CONTROL_NAME}function qp(e,t){let r=le(e.c).find(n=>n?.n==="parameters");return le(r?.c).find(n=>n?.n===t)}B.entryParameter=qp;function Vp(e){return Xn(e,"static")==="true"}B.isStaticParameter=Vp;function ls(e){let t=ss(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let a=qp(t[i],"RefId");if(!a||!Vp(a))return{kind:"unsupported"};let o=kt(os(a));if(!o)return{kind:"unsupported"};let s=qp(t[i],"PageInput");if(s&&!Vp(s))return{kind:"unsupported"};let l=s?os(s):void 0;if(i===0)r=o,n=l;else if(o!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=ls;function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jp(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return ge(t)&&ge(t.data)?t.data:void 0}B.inputDataFrom=jp;function Hp(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Hp;function Kp(e){return Bb(e.classId!==void 0?e.classId:Wp(e.bag,"classid"))}B.effectiveClassId=Kp;function ru(e){return!e.fieldName}B.isUnbound=ru;function Jp(e,t){if(Hp(e)!=="Main"||!ru(t)||Kp(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=An(t),n=r?Pi(e.bag,r):void 0;return n!==void 0&&ls(n).kind==="projectable"}B.isRecognizedEmbed=Jp;function TM(e){for(let t of Ub(e)){let r=t.control;if(!r||!Jp(e,r))continue;let n=ls(Pi(e.bag,An(r)));if(n.kind!=="projectable")continue;let i=jp(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=TM;var PM=new Set(["pageId","inputData"]);function as(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function RM(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new CM.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let a=new Set,o=i.getElementsByTagName("control");for(let u=0;u<o.length;u+=1){let c=kt(o[u].getAttribute("uniqueid"));c&&a.add(c)}let s=as(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?as(s):[]){let c=kt(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!a.has(c)))for(let d of as(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let p=as(d).find(h=>h.nodeName==="parameters"),f=p?as(p).find(h=>h.nodeName==="RefId"):void 0,m=f&&f.getAttribute("static")==="true"?kt(f.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=RM;function Zl(e){return{n:`<${e}`,a:[],c:[]}}function Gp(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[Zl(t)]}}function zp(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);ge(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function OM(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[Gp("RefId",t),...r===void 0?[]:[Gp("PageInput",zp(r))]]}]}))}}function tu(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>tu(r,t[n]));if(ge(e)&&ge(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&tu(e[n],t[n]))}return e===t}function xM(e,t,r){let n=le(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&kt(os(i))!==t&&(i.c=[Zl(t)]);let a=n.c.findIndex(u=>u?.n==="PageInput"),o=a>=0?n.c[a]:void 0,s=o?os(o):void 0;if(tu(jp(s),r))return;if(r!==void 0){o?o.c=[Zl(zp(r,s))]:n.c.push(Gp("PageInput",zp(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(a,1):o.c=[Zl(JSON.stringify(l))]}function Qp(e){let t=le(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Qp;function FM(e,t){var r;let n=e.bag,i=_a(n);if(i&&t){let a=eu(t),o=eu(e),s=DM(t),l=IM(e),u=le(i.node.c),c=[];for(let d of u){let p=d?.n==="controlDescription"&&ss(d).length>0?kt(Xn(d,"forControl")):"";if(!p||!a.has(p))c.push(d);else if(o.has(p))if(s.has(p)&&_M(l.get(p))&&tu(d,Pi(t.bag,p))){let f=le(d.c).filter(m=>!$b(m));f.length>0&&c.push({...d,c:f})}else c.push(d)}(c.length!==u.length||c.some((d,p)=>d!==u[p]))&&(i.node.c=c)}for(let{cell:a}of jr(e)){let o=a.control;if(!Ri(o)||!ge(o.genPage))continue;let s=kt(o.genPage.pageId),l=o.genPage.inputData,u=An(o);if(!u){if(nu(o)!==void 0)continue;u=Gb(o)}let c=Pi(n,u);if(c){for(let f of ss(c))xM(f,s,l);continue}i||(i={i:Qp(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Wp(o.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),p=d.startsWith("{")?d:`{${u}}`;i.node.c.push(OM(p,s,l))}}B.reconcileEmbedDescriptions=FM;function LM(e,t){let r=_a(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=jr(e).some(({cell:o})=>Ri(o.control)&&(o.rowspan===void 0||o.control.classId===void 0||o.control.showLabel===void 0||o.control.label===void 0||o.control.fieldName===void 0));if(!n&&!i)return e;let a=JSON.parse(JSON.stringify(e));if(n){let o=JSON.parse(JSON.stringify(t)),s=_a(a.bag);s?s.node=o:(a.bag=ge(a.bag)?a.bag:{a:[],c:[]},a.bag.c=le(a.bag.c),a.bag.c.push({i:Qp(e.bag),node:o}))}for(let{cell:o}of jr(a))Ri(o.control)&&(qb(o.control),Vb(o));return a}B.commitEmbedState=LM;function kM(e){if(jr(e).some(({cell:r})=>Ri(r.control)))return!0;let t=_a(e.bag);return le(t?.node.c).some(r=>r?.n==="controlDescription"&&ss(r).length>0)}B.mayCommitEmbedState=kM;function qb(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=qb;function Vb(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=Vb;function Ri(e){return ge(e)&&e.genPage!==void 0}B.hasGenPage=Ri;function kb(e){return Ri(e.control)&&(!e.control.id||!e.id||nu(e.control)===void 0)}function nu(e){let t=le(ge(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}function MM(e){if(!jr(e).some(({cell:r})=>kb(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of jr(t)){if(!kb(r))continue;let n=r.control;n.id||(n.id=(0,Up.newId)()),r.id||(r.id=(0,Up.newId)()),nu(n)===void 0&&Gb(n)}return t}B.mintEmbedIdentity=MM;function Gb(e){let t=(0,Up.newId)(),r=`{${t}}`;if(!ge(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=le(e.bag.a),i=n.find(a=>Array.isArray(a)&&a[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=le(e.bag.c),t}function Mb(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function BM(e){let t=le(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=Xn(r,"name"))!==null&&n!==void 0?n:Xn(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function UM(e){let t=[],r;for(let{cell:n,pointer:i}of jr(e)){let a=n.control;if(!ge(a))continue;let o=`${i}/control`;if(a.genPage===void 0){$M(e,a,o,t);continue}r=r??eu(e),qM(e,a,o,r,t)}return t}B.genPageEmbedIssues=UM;function $M(e,t,r,n){if(!Jp(e,t))return;let i=ls(Pi(e.bag,An(t)));n.push((0,or.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function qM(e,t,r,n,i){var a;let o=`${r}/genPage`,s=t.genPage;if(!ge(s))i.push((0,or.issue)(o,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${Mb(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!kt(s.pageId))&&i.push((0,or.issue)(`${o}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!ge(s.inputData)&&i.push((0,or.issue)(`${o}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${Mb(s.inputData)}`));for(let f of Object.keys(s))PM.has(f)||i.push((0,or.issue)(SM.JsonPointer.append(o,f),"genpage-embed-unknown-key",`'${f}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}ru(t)||i.push((0,or.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&Bb(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,or.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Hp(e);l!=="Main"&&i.push((0,or.issue)(o,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=nu(t);u!==void 0&&!kt(u)&&i.push((0,or.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=An(t);if(!c)return;let d=Pi(e.bag,c),p=d?ls(d):void 0;d&&p?.kind==="none"?i.push((0,or.issue)(o,"genpage-embed-other-control",`this control is already bound to another custom control (${BM(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):p?.kind==="unsupported"&&i.push((0,or.issue)(o,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((a=n.get(c))!==null&&a!==void 0?a:0)>1&&i.push((0,or.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var Zp=y(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.findMissingGenPages=Yn.GENPAGE_LOOKUP_CHUNK=void 0;var VM=Pt(),Yp=ae();Yn.GENPAGE_LOOKUP_CHUNK=50;async function GM(e,t,r){let n=[...new Set(t.map(a=>(0,Yp.normalizeGuid)(a,"uxagentprojectid")))],i=new Set;for(let a=0;a<n.length;a+=Yn.GENPAGE_LOOKUP_CHUNK){let o=n.slice(a,a+Yn.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Yp.odataQuery)([["$select","uxagentprojectid"],["$filter",o.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,VM.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,Yp.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(a=>!i.has(a))}Yn.findMissingGenPages=GM});var tf=y(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.patchSystemForm=sr.assertSystemFormContentUnchanged=sr.readSystemFormContentEtag=sr.readSystemFormRowEtag=sr.unpublishedSystemFormPath=void 0;var Mt=be(),zM=ae(),ef=te();function iu(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,zM.odataQuery)([["$select",t]])}sr.unpublishedSystemFormPath=iu;function zb(e,t){return(0,Mt.readRowEtag)(e,"systemforms","formid",t)}sr.readSystemFormRowEtag=zb;async function WM(e,t){let r=iu(t);return(0,Mt.readEtag)((0,Mt.ensureSuccess)(await e.get(r),e.apiUrl(r)))}sr.readSystemFormContentEtag=WM;async function Wb(e,t,r,n,i){(0,Mt.requireEtag)(i,r,t);let a=(0,Mt.readEtag)((0,Mt.ensureSuccess)(await e.get(n),e.apiUrl(n)));if(a===null)throw new ef.SdkError(Mt.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(a!==i)throw new ef.SdkError(Mt.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${a}). Re-fetch the ${r} and re-apply the change.`)}sr.assertSystemFormContentUnchanged=Wb;async function jM(e,t,r,n,i,a){(0,Mt.requireEtag)(i,r,t);let o=await zb(e,t);if(o===null)throw new ef.SdkError(Mt.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);await Wb(e,t,r,iu(t),i);let s=(0,Mt.echoWrite)("formid",{"If-Match":o}),l=`/systemforms(${t})${s.query}`;return(0,Mt.ensureSuccess)(await e.patch(l,n,s.options),e.apiUrl(l)),HM(e,t,r,a)}sr.patchSystemForm=jM;async function HM(e,t,r,n){let i;try{let a=iu(t,n.select),o=(0,Mt.ensureSuccess)(await e.get(a),e.apiUrl(a)),s=o.body,l=(0,Mt.readEtag)(o),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null);if(l&&u&&c&&d.length===0)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:`the read did not return its ${d.join(", ")}`:"the read returned no version"}catch(a){i=a instanceof Error?a.message:String(a)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var of=y(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.getFormSecurityRoles=Bt.setFormSecurityRoles=Bt.formApi=Bt.FORM_GENPAGE_TARGET_UNVERIFIABLE=Bt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var KM=Pt(),ut=be(),lr=ae(),Oi=te(),rf=_i(),Hb=Xp(),JM=Zp(),au=tf();Bt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";Bt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var Kb="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",QM={select:Kb,required:["name","type","objecttypecode"]},XM="formid,name,type,objecttypecode",YM=2,ZM={Main:YM,QuickView:6,QuickCreate:7,Card:11};Bt.formApi={async get(e,t){let n=`/systemforms(${(0,lr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select",Kb]]),i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>ZM[u]))],o=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&o.push(`objecttypecode eq '${(0,lr.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,lr.odataQuery)([["$select",XM],["$filter",o.join(" and ")]])}`;return(await(0,KM.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=jb(t);n!==void 0&&await Jb(e,af(n,"payload"),[]);let i=(0,ut.echoWrite)("formid"),a=`/systemforms${i.query}`,o=(0,ut.ensureSuccess)(await e.post(a,(0,ut.withClientMintedId)(t,"formid",r),i.options),e.apiUrl(a));return{id:(0,ut.resolveCreatedId)(o,"formid","form",r),etag:(0,ut.readEtag)(o)}},async update(e,t,r,n){let i=(0,lr.normalizeGuid)(t,"id"),a=jb(r);return a!==void 0&&await tB(e,i,a,n),(0,au.patchSystemForm)(e,i,"form",r,n,QM)},readToken(e,t){return(0,au.readSystemFormContentEtag)(e,(0,lr.normalizeGuid)(t,"id"))},delete(e,t){return(0,ut.deleteRecord)(e,"systemforms",t)}};var nf="DisplayConditions";async function eB(e,t,r){var n,i,a,o;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Oi.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,lr.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),u=(0,ut.ensureSuccess)(await e.get(l),e.apiUrl(l)),c=(0,ut.readEtag)(u),d=u.body,p=d?.formxml;if(!p)throw new Oi.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let f=(0,rf.parseXmlRoot)(p,"<form/>"),m=f.ownerDocument;if(!m)throw new Oi.InvalidArgumentError(`form '${s}' produced no owner document`);let h=Qb(f,nf),v=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&f.removeChild(h);let E=!!r.everyone||((a=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0)>0;if(!E&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Oi.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),f.appendChild(h)}else if(E){let F=m.createElement(nf),k=r.order!==void 0?String(r.order):v;k!==void 0&&F.setAttribute("Order",k);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(F.setAttribute("FallbackForm",P),r.everyone)F.appendChild(m.createElement("Everyone"));else for(let V of(o=r.roleIds)!==null&&o!==void 0?o:[]){let q=m.createElement("Role");q.setAttribute("Id",`{${(0,lr.normalizeGuid)(V,"roleId")}}`),F.appendChild(q)}f.appendChild(F)}let N=(0,rf.serializeNode)(f);await(0,au.assertSystemFormContentUnchanged)(e,s,"form",l,c);let R=await(0,au.readSystemFormRowEtag)(e,s),O=`/systemforms(${s})`;(0,ut.ensureSuccess)(await e.patch(O,{formxml:N},{headers:{"Content-Type":"application/json","If-Match":(0,ut.requireEtag)(R,"form",s)}}),e.apiUrl(O))}Bt.setFormSecurityRoles=eB;function jb(e){let t=e?.formxml;return typeof t=="string"&&t.includes(Hb.GENPAGE_CONTROL_NAME)?t:void 0}function af(e,t){try{return(0,Hb.activeEmbedBindings)(e)}catch(r){throw new Oi.SdkError(Bt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function Jb(e,t,r){let n=new Set(r.map(([o,s])=>`${o}|${s}`)),i=t.filter(([o,s])=>!n.has(`${o}|${s}`)).map(([,o])=>o);if(i.length===0)return;let a=await(0,JM.findMissingGenPages)(e,i,"form generative-page preflight");if(a.length>0)throw new Oi.SdkError(Bt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${a.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function tB(e,t,r,n){var i;(0,ut.requireEtag)(n,"form",t);let a=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),o=(0,ut.ensureSuccess)(await e.get(a),e.apiUrl(a)),s=(0,ut.readEtag)(o);if(s===null||s!==n)throw new Oi.SdkError(ut.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=o.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?af(l,"server"):[];await Jb(e,af(r,"payload"),u)}function Qb(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function rB(e,t){var r,n;let a=`/systemforms(${(0,lr.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,ut.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,rf.parseXmlRoot)(s,"<form/>"),u=Qb(l,nf);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let m=0;m<p.length;m+=1){let h=p[m];if(h.nodeType!==1)continue;let v=h;if(v.tagName==="Everyone")d=!0;else if(v.tagName==="Role"){let b=(n=v.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.replace(/[{}]/g,"").toLowerCase())}}let f=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...f!==null&&f!==""?{order:Number(f)}:{}}}Bt.getFormSecurityRoles=rB});var lu=y(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.disassociateRecords=Oe.associateRecords=Oe.createRecordsBulk=Oe.upsertRecord=Oe.queryAllRecords=Oe.queryRecords=Oe.getRecord=Oe.deleteRecord=Oe.updateRecord=Oe.createRecord=void 0;var nB=Pt(),Sr=be(),mt=ae(),ou=te(),Hr=xl();function su(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let a=t[i];Array.isArray(a)&&a.every(o=>typeof o=="number")?(n[i]=a.join(","),r=!0):n[i]=a}return r?n:e}async function iB(e,t,r){let i=`/${await(0,Hr.resolveEntitySetName)(e,t)}`,a=(0,Sr.ensureSuccess)(await e.post(i,su(r)),e.apiUrl(i)),o=(0,Sr.readCreatedId)(a,`${t}id`);if(!o)throw new ou.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:o,entityType:t}}Oe.createRecord=iB;async function aB(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),o=`/${await(0,Hr.resolveEntitySetName)(e,t)}(${i})`;(0,Sr.ensureSuccess)(await e.patch(o,su(n)),e.apiUrl(o))}Oe.updateRecord=aB;async function oB(e,t,r){let n=(0,mt.normalizeGuid)(r,"id"),a=`/${await(0,Hr.resolveEntitySetName)(e,t)}(${n})`;(0,Sr.ensureSuccess)(await e.delete(a),e.apiUrl(a))}Oe.deleteRecord=oB;async function sB(e,t,r,n){var i;let a=(0,mt.normalizeGuid)(r,"id"),o=await(0,Hr.resolveEntitySetName)(e,t),s=(0,mt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${o}(${a})${s}`;return(i=(0,Sr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Oe.getRecord=sB;function lB(e){return e?.fetchXml?(0,mt.odataQuery)([["fetchXml",e.fetchXml]]):(0,mt.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function Xb(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new ou.InvalidArgumentError("queryRecords: `paginate` cannot be combined with `top` \u2014 Dataverse honors $top as a hard cap and omits @odata.nextLink, so the result would be silently capped at one page.");if(r.fetchXml)throw new ou.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let o=`/${await(0,Hr.resolveEntitySetName)(e,t)}${lB(r)}`;return r?.paginate?(0,nB.collectPages)(e,o,"queryRecords"):(i=(n=(0,Sr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Oe.queryRecords=Xb;async function uB(e,t,r){return Xb(e,t,{...r,paginate:!0})}Oe.queryAllRecords=uB;function cB(e){if("id"in e)return`(${(0,mt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,mt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,mt.assertODataName)(e.key,"alternate key name")}=${t})`}async function dB(e,t,r,n){let i=cB(r),o=`/${await(0,Hr.resolveEntitySetName)(e,t)}${i}`,s=(0,Sr.ensureSuccess)(await e.patch(o,su(n)),e.apiUrl(o)),l=s.status===201,u=(0,Sr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,mt.normalizeGuid)(r.id,"id"):""),created:l}}Oe.upsertRecord=dB;async function pB(e,t,r){var n,i;if(r.length===0)return[];let a=await(0,Hr.resolveEntitySetName)(e,t),o=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...su(c)})),s=`/${a}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Sr.ensureSuccess)(await e.post(s,{Targets:o}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new ou.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Oe.createRecordsBulk=pB;async function fB(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),a=(0,mt.normalizeGuid)(n.targetId,"targetId"),o=await(0,Hr.resolveEntitySetName)(e,t),s=await(0,Hr.resolveEntitySetName)(e,n.targetEntity),l=(0,mt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${o}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${a})`)};(0,Sr.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Oe.associateRecords=fB;async function mB(e,t,r,n,i){let a=(0,mt.normalizeGuid)(r,"id"),o=(0,mt.normalizeGuid)(i,"targetId"),s=await(0,Hr.resolveEntitySetName)(e,t),l=(0,mt.assertODataName)(n,"relationshipName"),u=`/${s}(${a})/${l}(${o})/$ref`;(0,Sr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Oe.disassociateRecords=mB});var Nr=y(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.publishBoundEntity=Ze.boundEntityPublishScope=Ze.publishGenPageById=Ze.publishDashboardById=Ze.publishWebResourceById=Ze.publishEntity=Ze.publishAppModule=Ze.publishXml=void 0;var Yb=be(),us=ae(),Zb="/PublishXml";async function Ta(e,t){(0,Yb.ensureSuccess)(await(0,Yb.resendDeadlockVictim)(()=>e.post(Zb,{ParameterXml:t})),e.apiUrl(Zb))}Ze.publishXml=Ta;function hB(e,t){return Ta(e,`<importexportxml><appmodules><appmodule>${(0,us.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ze.publishAppModule=hB;function ew(e,t){return Ta(e,`<importexportxml><entities><entity>${(0,us.xmlText)(t)}</entity></entities></importexportxml>`)}Ze.publishEntity=ew;function gB(e,t){return Ta(e,`<importexportxml><webresources><webresource>${(0,us.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ze.publishWebResourceById=gB;function vB(e,t){return Ta(e,`<importexportxml><dashboards><dashboard>${(0,us.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ze.publishDashboardById=vB;function yB(e,t){return Ta(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,us.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ze.publishGenPageById=yB;function bB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ze.boundEntityPublishScope=bB;function wB(e,t){let r=t?.entityLogicalName;return r?ew(e,r):Promise.resolve()}Ze.publishBoundEntity=wB});var cu=y(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.base64ToUtf8=Kr.base64ToBytes=Kr.bytesToBase64=Kr.utf8ToBase64=void 0;var sf=32768,Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function uu(){return globalThis}function AB(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function EB(e){let t="";for(let r=0;r<e.length;r+=sf)t+=String.fromCharCode(...e.subarray(r,r+sf));return t}function CB(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Ut.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function SB(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Ut[i>>18&63]+Ut[i>>12&63]+Ut[i>>6&63]+Ut[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Ut[i>>18&63]}${Ut[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,a=Ut[i>>18&63],o=Ut[i>>12&63],s=Ut[i>>6&63];t+=`${a}${o}${s}=`}return t}function NB(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let a=0;a<e.length;a+=4){let o=Ut.indexOf(e[a])<<18|Ut.indexOf(e[a+1])<<12|(e[a+2]==="="?0:Ut.indexOf(e[a+2]))<<6|(e[a+3]==="="?0:Ut.indexOf(e[a+3]));i<r&&(n[i++]=o>>16&255),i<r&&(n[i++]=o>>8&255),i<r&&(n[i++]=o&255)}return n}function DB(e){let t=uu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return tw(r?new r().encode(e):AB(e))}Kr.utf8ToBase64=DB;function tw(e){let t=uu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(EB(e)):SB(e)}Kr.bytesToBase64=tw;function rw(e){let t=uu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=CB(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return NB(r)}Kr.base64ToBytes=rw;function IB(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=o=>{if(o>65535){let s=o-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(o);t.length>=sf&&n()},a=0;for(;a<e.length;){let o=e[a],s=0,l=0,u=128,c=191;if(o<128){i(o),a+=1;continue}else if(o>=194&&o<=223)s=1,l=o&31;else if(o>=224&&o<=239)s=2,l=o&15,u=o===224?160:128,c=o===237?159:191;else if(o>=240&&o<=244)s=3,l=o&7,u=o===240?144:128,c=o===244?143:191;else{i(65533),a+=1;continue}let d=a+1,p=!0;for(let f=0;f<s;f+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){p=!1;break}u=128,c=191,l=l<<6|m&63}p?(i(l),a=d):(i(65533),a=d)}return n(),r}function _B(e){let t=uu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):IB(rw(e))}Kr.base64ToUtf8=_B});var ow=y(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.deleteWebResource=Jr.getWebResource=Jr.updateWebResource=Jr.createWebResource=void 0;var TB=Nr(),cs=be(),du=ae(),PB=cu(),nw=te(),RB={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function iw(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,PB.utf8ToBase64)(e.content)}async function aw(e,t){return(0,TB.publishWebResourceById)(e,t)}async function OB(e,t){var r;let n=iw(t);if(n===void 0)throw new nw.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(r=t.displayName)!==null&&r!==void 0?r:t.name,webresourcetype:RB[t.type],content:n};t.description&&(i.description=t.description);let a=(0,cs.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),o=(0,cs.readCreatedId)(a,"webresourceid");if(!o)throw new nw.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await aw(e,o),{id:o,name:t.name}}Jr.createWebResource=OB;async function xB(e,t,r){let n=(0,du.normalizeGuid)(t,"id"),i={},a=iw(r);a!==void 0&&(i.content=a),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let o=`/webresourceset(${n})`;(0,cs.ensureSuccess)(await e.patch(o,i),e.apiUrl(o)),r.publish!==!1&&await aw(e,n)}Jr.updateWebResource=xB;async function FB(e,t){var r;let i=`/webresourceset(${(0,du.normalizeGuid)(t,"id")})${(0,du.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,cs.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Jr.getWebResource=FB;async function LB(e,t){let n=`/webresourceset(${(0,du.normalizeGuid)(t,"id")})`;(0,cs.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Jr.deleteWebResource=LB});var pu=y(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.applyAppSettings=et.setAppSetting=et.readAppSettings=et.resolveSettingDefinitions=et.APP_SETTING_UNSET=et.APP_SETTING_OFF=et.APP_SETTING_ON=et.HEADER_AND_NAVIGATION_REFRESH=void 0;var Pa=be(),En=ae();et.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";et.APP_SETTING_ON="2";et.APP_SETTING_OFF="1";et.APP_SETTING_UNSET="0";function uw(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,En.odataQuery)([["$select",e],["$filter",t]])}async function cw(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],a=new Map;if(i.length===0)return a;let o=i.map(c=>`uniquename eq '${(0,En.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,En.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",o]])}`,u=((n=(r=(0,Pa.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&a.set(c.uniquename,c);return a}et.resolveSettingDefinitions=cw;async function kB(e,t){var r,n,i,a;let o=(0,En.normalizeGuid)(t,"App id"),s=uw("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${o}`),u=((n=(r=(0,Pa.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(p=>p._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let p=c.map(h=>`settingdefinitionid eq ${(0,En.normalizeGuid)(h,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,En.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,m=(0,Pa.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let h of((a=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&a!==void 0?a:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(p=>{var f,m,h,v,b;let E=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(m=p.appsettingid)!==null&&m!==void 0?m:"",name:(v=(h=E?.uniquename)!==null&&h!==void 0?h:p._settingdefinitionid_value)!==null&&v!==void 0?v:"",value:(b=p.value)!==null&&b!==void 0?b:"",...E?.displayname?{displayName:E.displayname}:{}}})}et.readAppSettings=kB;async function sw(e,t,r){var n,i,a;let o=uw("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Pa.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(a=l.value)!==null&&a!==void 0?a:""}:void 0}async function dw(e,t,r,n){let i=(0,En.normalizeGuid)(t,"App id"),o=(await cw(e,[r])).get(r),s=o?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,En.normalizeGuid)(s,"Setting definition id"),u=await sw(e,i,l);if(u)return lw(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,f;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(h){f=h}let m;try{m=await sw(e,i,l)}catch{m=void 0}if(m)return lw(e,m,n);throw p&&(0,Pa.ensureSuccess)(p,e.apiUrl(c)),f}et.setAppSetting=dw;async function lw(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,En.normalizeGuid)(t.id,"App setting id")})`;return(0,Pa.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function MB(e,t,r){var n;let i=[];for(let[a,o]of Object.entries(r??{}))try{await dw(e,t,a,o)}catch(s){i.push(`App setting '${a}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}et.applyAppSettings=MB});var mu=y(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.HEADER_NAV_BOOLEAN_RULE=void 0;fu.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var fw=y(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.deleteSolution=oe.importSolution=oe.exportSolution=oe.removeSolutionComponent=oe.addSolutionComponent=oe.setSolutionVersion=oe.createSolution=oe.createPublisher=oe.getSolution=oe.fetchSolutionComponents=oe.SolutionComponentType=void 0;var pw=Pt(),Dr=be(),$t=ae(),xi=te();oe.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,UxAgentProject:10372};var BB=[oe.SolutionComponentType.SavedQuery,oe.SolutionComponentType.Workflow,oe.SolutionComponentType.SavedQueryVisualization,oe.SolutionComponentType.SystemForm,oe.SolutionComponentType.AppModule,oe.SolutionComponentType.UxAgentProject];async function UB(e,t){let r=(0,$t.normalizeGuid)(t,"solutionId"),n=BB.map(s=>`msdyn_componenttype eq ${s}`).join(" or "),i=`/msdyn_solutioncomponentsummaries${(0,$t.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${n})`]])}`,o=(await(0,pw.collectPages)(e,i,"fetchSolutionComponents")).filter(s=>typeof s.msdyn_objectid=="string").map(s=>({objectId:s.msdyn_objectid,componentType:Number(s.msdyn_componenttype),workflowCategory:s.msdyn_workflowcategory==null?void 0:Number(s.msdyn_workflowcategory),displayName:s.msdyn_displayname,name:s.msdyn_name}));return[...o,...await $B(e,r,o)]}oe.fetchSolutionComponents=UB;async function $B(e,t,r){let n=new Set(r.map(s=>s.objectId.toLowerCase())),i=`/solutioncomponents${(0,$t.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${oe.SolutionComponentType.UxAgentProject}`]])}`,a=await(0,pw.collectPages)(e,i,"fetchSolutionComponents(draft pages)"),o=[];for(let s of a){let l=typeof s.objectid=="string"?s.objectid:void 0;l&&!n.has(l.toLowerCase())&&(n.add(l.toLowerCase()),o.push({objectId:l,componentType:oe.SolutionComponentType.UxAgentProject}))}return o}function qB(e){let t=e.length===38&&e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e;return/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(t)}async function VB(e,t){var r,n,i,a,o,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new xi.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=qB(p)?`solutionid eq ${(0,$t.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,$t.odataLiteral)(p)}'`,m=`/solutions${(0,$t.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,b=((n=(r=(0,Dr.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new xi.InvalidArgumentError(`No solution found for '${t}'.`);let E=b.publisherid;if(!E?.publisherid)throw new xi.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in E))throw new xi.InvalidArgumentError(`Solution '${(a=b.uniquename)!==null&&a!==void 0?a:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,$t.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(o=b.uniquename)!==null&&o!==void 0?o:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,$t.normalizeGuid)(E.publisherid,"publisherId"),publisherUniqueName:(u=E.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=E.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=E.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}oe.getSolution=VB;async function GB(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,Dr.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),a=(0,Dr.readCreatedId)(i,"publisherid");if(!a)throw new xi.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}oe.createPublisher=GB;async function zB(e,t){var r;let n=(0,$t.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let a=(0,Dr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),o=(0,Dr.readCreatedId)(a,"solutionid");if(!o)throw new xi.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}oe.createSolution=zB;async function WB(e,t,r){let i=`/solutions(${(0,$t.normalizeGuid)(t,"solutionId")})`;(0,Dr.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}oe.setSolutionVersion=WB;async function jB(e,t){var r;let i={ComponentId:(0,$t.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(r=t.addRequiredComponents)!==null&&r!==void 0?r:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,Dr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}oe.addSolutionComponent=jB;async function HB(e,t,r,n){let a={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,$t.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Dr.ensureSuccess)(await e.post("/RemoveSolutionComponent",a),e.apiUrl("/RemoveSolutionComponent"))}oe.removeSolutionComponent=HB;async function KB(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},o=(n=(0,Dr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!o)throw new xi.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:o}}oe.exportSolution=KB;async function JB(e,t){var r,n;let i={OverwriteUnmanagedCustomizations:(r=t.overwriteUnmanagedCustomizations)!==null&&r!==void 0?r:!0,PublishWorkflows:(n=t.publishWorkflows)!==null&&n!==void 0?n:!0,CustomizationFile:t.base64};t.importJobId&&(i.ImportJobId=(0,$t.normalizeGuid)(t.importJobId,"importJobId")),(0,Dr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}oe.importSolution=JB;async function QB(e,t){let n=`/solutions(${(0,$t.normalizeGuid)(t,"solutionId")})`;(0,Dr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}oe.deleteSolution=QB});var df=y(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.compileGenPage=Ee.legacyEnumsNeeded=Ee.createGenPageTypeScriptLoader=Ee.acceptGenPageTypeScript=Ee.isLoadableGenPageOutput=Ee.GENPAGE_RUNTIME_TYPES_END=Ee.GENPAGE_RUNTIME_TYPES_BEGIN=Ee.GENPAGE_TYPESCRIPT_VERSION=void 0;var Ra=te();Ee.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Ee.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Ee.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var XB=/(import\s+[^'"]+)(['"`])(\.\/RuntimeTypes)\2;?\s*/g,Zn="./RuntimeTypes",YB=/\b(import\s.+from\s+['"]|import\s*['"]|export\s)/;function ZB(e){return e!==void 0&&e!==""&&YB.test(e)}Ee.isLoadableGenPageOutput=ZB;var mw=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function vw(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?mw.filter(s=>typeof n?.[s]!="function"):[...mw];if(!n||i.length>0)throw new Ra.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let a=typeof n.version=="string"?n.version:"",o=Ee.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(a.split(".").slice(0,2).join(".")!==o)throw new Ra.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${a||"unknown"}', but generative pages are compiled with ${o}.x \u2014 the version the maker portal itself uses (${Ee.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Ee.acceptGenPageTypeScript=vw;function eU(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new Ra.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(vw).catch(r=>{throw t=void 0,r instanceof Ra.SdkError?r:new Ra.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Ee.createGenPageTypeScriptLoader=eU;var yw=e=>`${e.kind}:${e.pos}:${e.end}`;function tU(e,t){return()=>r=>{let n=i=>{let a=e.getParseTreeNode(i);a&&t.add(yw(a)),e.forEachChild(i,n)};return n(r),r}}function cf(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}function hw(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:cf(e),reportDiagnostics:!0,...r?{transformers:{after:[tU(e,r)]}}:{}}),a=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(o=>o.category===e.DiagnosticCategory.Error).map(o=>{let s=o.file&&typeof o.start=="number"?o.file.getLineAndCharacterOfPosition(o.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:o.code,message:e.flattenDiagnosticMessageText(o.messageText,`
-`)}});return{code:i.outputText,diagnostics:a}}var gw=e=>e.startsWith(".")||e.startsWith("/"),lf={line:1,column:1};function uf(e,t){let r=a=>{let o=t.getLineAndCharacterOfPosition(a.getStart(t));return{line:o.line+1,column:o.character+1}},n=a=>(e.isImportDeclaration(a)||e.isExportDeclaration(a))&&a.moduleSpecifier&&e.isStringLiteral(a.moduleSpecifier)?a.moduleSpecifier.text:void 0,i=a=>t.statements.filter(o=>e.isImportDeclaration(o)&&n(o)===a);return{statement(a,o){let s=t.statements.find(l=>n(l)===a&&(o==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):lf},element(a,o){var s;for(let l of i(a)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===o):void 0;if(c)return r(c)}return this.statement(a,"import")},binding(a){var o,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((o=u.name)===null||o===void 0?void 0:o.text)===a?u.name:c&&e.isNamespaceImport(c)&&c.name.text===a?c.name:c&&e.isNamedImports(c)?c.elements.find(p=>p.name.text===a):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===a)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===a);if(u)return r(u.name)}}return lf}}}function rU(e,t,r,n){var i,a;let o=[],s=uf(e,r),l=(m,h,v)=>{o.push({...m,rule:h,code:0,message:v})},u=(m,h)=>{var v;return(e.canHaveModifiers(m)?(v=e.getModifiers(m))!==null&&v!==void 0?v:[]:[]).some(b=>b.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",p=!1,f=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){p=p||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(p=!0),m.name&&f.add(m.name.text);continue}if(e.isExportDeclaration(m)){let E=m.exportClause;E&&e.isNamedExports(E)&&E.elements.some(N=>N.name.text==="default")&&(p=!0);let C=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;C===Zn?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&gw(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,v=m.importClause;if(h!==Zn){gw(h)&&c(s.statement(h,"import"),h),v?.name&&f.add(v.name.text);let E=v?.namedBindings;E&&e.isNamespaceImport(E)?f.add(E.name.text):E&&e.isNamedImports(E)&&E.elements.forEach(C=>f.add(C.name.text));continue}if(!v){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}v.name&&l(s.binding(v.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=v.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let E of b.elements){let C=E.name.text,N=(a=(i=E.propertyName)===null||i===void 0?void 0:i.text)!==null&&a!==void 0?a:C,R=s.element(h,C);N!==C?l(R,d,`'${N} as ${C}' would be undefined at runtime: the enum is inlined as '${N}', so import it under its own name`):n?.text?n.enums.has(C)||l(R,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(R,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(p||l(lf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of f)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return o}function bw(e,t,r){let n,i=()=>{if(!n){let c={getSourceFile:p=>p===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:p=>p,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
-`,fileExists:p=>p===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},d={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:d,host:c}).getTypeChecker()}return n},a=c=>e.isImportSpecifier(c)?c.parent.parent.parent:e.isImportClause(c)?c.parent:e.isNamespaceImport(c)?c.parent.parent:void 0,o=c=>{let d=a(c);return d!==void 0&&e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Zn},s=c=>{var d;for(let p=c;p;p=p.parent)if(e.canHaveModifiers(p)&&((d=e.getModifiers(p))!==null&&d!==void 0?d:[]).some(f=>f.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},l=c=>s(c)||e.isImportEqualsDeclaration(c)&&(c.isTypeOnly||e.isExternalModuleReference(c.moduleReference))||e.isImportClause(c)&&c.isTypeOnly||e.isNamespaceImport(c)&&c.parent.isTypeOnly||e.isImportSpecifier(c)&&(c.isTypeOnly||c.parent.parent.isTypeOnly),u=c=>{var d;return((d=c?.declarations)!==null&&d!==void 0?d:[]).some(p=>!o(p)&&!l(p))};return{pageOwns:c=>{let d=c.parent;return u(e.isShorthandPropertyAssignment(d)&&d.name===c?i().getShorthandAssignmentValueSymbol(d):i().getSymbolAtLocation(c))},pageOwnsLocalExport:c=>u(i().getExportSpecifierLocalTargetSymbol(c))}}function nU(e,t,r,n){let i=[],a=r?.enums;if(!a||a.size===0)return i;let o=(u,c,d)=>{let p=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:p.line+1,column:p.character+1,rule:c,code:0,message:d})},s=bw(e,t,cf(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let f=u.argumentExpression;e.isStringLiteral(f)||e.isNoSubstitutionTemplateLiteral(f)?(c=u.expression,d=f.text):e.isNumericLiteral(f)&&(c=u.expression,d=String(Number(f.text)))}let p=c&&a.has(c.text)&&n.has(yw(u))&&!s.pageOwns(c)?a.get(c.text):void 0;if(c&&p&&d!==void 0){let f=e.isPropertyAccessExpression(u)?`${p.name}.${d}`:`${p.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(p.runtime,d)?p.runtime[d]:void 0,h=p.labels.get(d);m===void 0?o(u,"genpage-enum-member-unknown",`${f} is undefined at runtime: '${p.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...p.labels.keys()].map(v=>`'${v}'`).join(", ")}`):h&&typeof m!="number"?o(u,"genpage-enum-member-clobbered",`${f} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`):h&&h.length>1&&o(u,"genpage-enum-member-ambiguous",`${f} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`)}e.forEachChild(u,l)};return l(t),i}function iU(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Zn)}function aU(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(o=>e.isImportDeclaration(o)&&e.isStringLiteral(o.moduleSpecifier)&&o.moduleSpecifier.text===Zn).map(o=>o.getStart(r))),i=!0;return{code:t.replace(XB,(...o)=>(n.has(o[o.length-2])||(i=!1),"")),exact:i}}function ww(e,t,r){if(!r||r.size===0)return[];let n=bw(e,t,{...cf(e),target:e.ScriptTarget.ESNext}),i=new Set,a=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Zn&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},o=s=>{e.isIdentifier(s)&&r.has(s.text)&&a(s),e.forEachChild(s,o)};return o(t),[...r.keys()].filter(s=>i.has(s))}Ee.legacyEnumsNeeded=ww;function oU(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let a of r){let o=t.get(a);o&&(i+=o.declaration,n.set(a,o.model))}return{text:i,enums:n}}function sU(e,t,r,n){let i=new Set,a=hw(e,t,i);if(a.diagnostics.length>0)return a;let o=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=oU(r,n,ww(e,s,n)),u=[...rU(e,s,o,l),...nU(e,o,l,i)];if(!l?.text)return{code:a.code,diagnostics:u};let c=hw(e,l.text);if(c.diagnostics.length>0)throw new Ra.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=aU(e,a.code),p=d.code;return u.length===0&&!d.exact?u.push({...uf(e,o).statement(Zn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&iU(e,p)&&u.push({...uf(e,o).statement(Zn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[Ee.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,Ee.GENPAGE_RUNTIME_TYPES_END,p].join(`
+`)}function Kb(e){this.options=e||{locator:{}}}Kb.prototype.parseFromString=function(e,t){var r=this.options,n=new iB,i=r.domBuilder||new fs,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?Gb.HTML_ENTITIES:Gb.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=oB(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=zb.HTML),s.xml=s.xml||zb.XML;var c=r.normalizeLineEndings||Hb;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function oB(e,t,r){if(!e){if(t instanceof fs)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Wp(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function fs(){this.cdata=!1}function ko(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}fs.prototype={startDocument:function(){this.doc=new rB().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;tu(this,o),this.currentElement=o,this.locator&&ko(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&ko(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&ko(this.locator,r),tu(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Wb.apply(this,arguments),e){if(this.cdata)var n=this.doc.createCDATASection(e);else var n=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(n):/^\s*$/.test(e)&&this.doc.appendChild(n),this.locator&&ko(this.locator,n)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,r){e=Wb.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&ko(this.locator,n),tu(this,n)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,r){var n=this.doc.implementation;if(n&&n.createDocumentType){var i=n.createDocumentType(e,t,r);this.locator&&ko(this.locator,i),tu(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Wp(this.locator))},error:function(e){console.error("[xmldom error] "+e,Wp(this.locator))},fatalError:function(e){throw new nB(e,this.locator)}};function Wp(e){if(e)return`
+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Wb(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){fs.prototype[e]=function(){return null}});function tu(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}ru.__DOMHandler=fs;ru.normalizeLineEndings=Hb;ru.DOMParser=Kb});var iu=b(nu=>{var Qb=Vp();nu.DOMImplementation=Qb.DOMImplementation;nu.XMLSerializer=Qb.XMLSerializer;nu.DOMParser=Jb().DOMParser});var ii=b(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.installDomShim=void 0;var Xb=iu(),Yb=!1,aB={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};function sB(){if(Yb)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=Xb.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=Xb.XMLSerializer),typeof e.Node>"u"&&(e.Node=aB),Yb=!0}ou.installDomShim=sB});var oi=b(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.projectElementBag=Le.serializeNode=Le.domEngine=Le.nodeLikeFromDom=Le.parseXmlRoot=Le.EMPTY_FORM_SENTINEL=Le.TEXT_SENTINEL=void 0;var lB=ri(),ms=re(),uB=ii();Le.TEXT_SENTINEL="#text";Le.EMPTY_FORM_SENTINEL="#empty";var su=new WeakSet;function cB(e,t){(0,uB.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new ms.InvalidArgumentError("XML source has no root element (empty or malformed input)");return pB(i),fB(i),gB(i,r),i}Le.parseXmlRoot=cB;var dB=new Set([1,3]);function pB(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!dB.has(o.nodeType))throw new ms.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function fB(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new ms.InvalidArgumentError(`Unsupported document-level XML node (type ${a.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function mB(e){let t=[],r=/<([^>]*)>/g;for(let n=r.exec(e);n!==null;n=r.exec(e)){let i=n[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function hB(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function ew(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function gB(e,t){let r=mB(t),n=hB(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];ew(a)||su.add(a)}}function jp(e){let t=e.nodeType===3;return{getNodeName:()=>t?Le.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Le.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return su.has(e)&&!ew(e)&&i.push({key:Le.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(jp(o))}return r}}}Le.nodeLikeFromDom=jp;function vB(e){return{make:t=>t===Le.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Le.EMPTY_FORM_SENTINEL?su.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Le.domEngine=vB;function tw(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=31&&r!==9&&r!==10&&r!==13||r===65534||r===65535)throw au(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw au(r);t+=1;continue}if(r>=56320&&r<=57343)throw au(r)}}function au(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new ms.InvalidArgumentError(`Value contains U+${t}, a character not permitted in XML 1.0 (control char / lone surrogate / non-character); it cannot be serialized losslessly`)}function yB(e){return tw(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function bB(e){return tw(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function wB(e){return rw(e,0)}Le.serializeNode=wB;var Zb=512;function rw(e,t){var r;if(t>Zb)throw new ms.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${Zb}`);if(e.nodeType===3)return bB((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+yB(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return su.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=rw(l,t+1);return i+"</"+n.tagName+">"}function AB(e){let t=jp(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,lB.rawFromNode)(r)}))}}Le.projectElementBag=AB});var Nr=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.rejectUnknownKeys=ft.childObjects=ft.optionalGuidId=ft.optionalEnum=ft.eachObject=ft.issue=ft.isJsonObject=void 0;function nw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}ft.isJsonObject=nw;function Fo(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}ft.issue=Fo;function iw(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{nw(o)?i.push({node:o,index:a}):n.push(Fo(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}ft.eachObject=iw;function EB(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Fo(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}ft.optionalEnum=EB;var CB=/^(?:\{[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\}|[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})$/;function SB(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!CB.test(o)&&i.push(Fo(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}ft.optionalGuidId=SB;function NB(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?iw(o,a,n,i):(i.push(Fo(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}ft.childObjects=NB;function DB(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Fo(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}ft.rejectUnknownKeys=DB});var af=b(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.mintEmbedIdentity=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var _B=iu(),IB=wo(),Hp=lt(),ar=Nr();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var TB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Mt(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),TB.test(t)?t:""}B.normGuid=Mt;function ai(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=ai;function gs(e){return le(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=gs;function le(e){return Array.isArray(e)?e:[]}function Zp(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function sw(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function lw(e){return Kr(e).map(t=>t.cell)}B.typedCells=lw;function Kr(e){let t=[];return le(e?.tabs).forEach((r,n)=>{le(ve(r)?r.columns:void 0).forEach((i,o)=>{le(ve(i)?i.sections:void 0).forEach((a,s)=>{le(ve(a)?a.rows:void 0).forEach((l,u)=>{le(ve(l)?l.cells:void 0).forEach((c,d)=>{ve(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}function Nn(e){return ve(e)?Mt(Zp(e.bag,"uniqueid")):""}B.controlUniqueId=Nn;function PB(e){let t=new Set;for(let{cell:r}of Kr(e)){let n=$i(r.control)?Nn(r.control):"";n&&t.add(n)}return t}function RB(e){let t=new Map;for(let{cell:r}of Kr(e)){let n=ve(r.control)?Nn(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function OB(e){return e!==void 0&&e.genPage===void 0&&(rf(e)!==B.CUSTOM_CONTROL_CLASS_ID||!du(e))}function Kp(e,t){if(ve(e)){t(e);for(let r of le(e.c))Kp(r,t)}}function Mi(e,t){var r;if(ve(e)){for(let n of le(e.c))Kp(n?.node,t);for(let n of le((r=e.w)===null||r===void 0?void 0:r.c))Kp(n?.node,t)}}function uu(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Mt(ai(i,"uniqueid")))};return Mi(e?.bag,n),le(e?.tabs).forEach(i=>{ve(i)&&(Mi(i.bag,n),le(i.columns).forEach(o=>{ve(o)&&(Mi(o.bag,n),le(o.sections).forEach(a=>{ve(a)&&(Mi(a.bag,n),le(a.rows).forEach(s=>{ve(s)&&(Mi(s.bag,n),le(s.cells).forEach(l=>{ve(l)&&(Mi(l.bag,n),ve(l.control)&&(r(Nn(l.control)),Mi(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=uu;function Mo(e){return le(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=Mo;function Bi(e,t){var r;let n=Mt(t);if(n)return le((r=Mo(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Mt(ai(i,"forControl"))===n)}B.descriptionFor=Bi;function vs(e){return le(e.c).filter(uw)}B.pageEntries=vs;function uw(e){return e?.n==="customControl"&&ai(e,"name")===B.GENPAGE_CONTROL_NAME}function Jp(e,t){let r=le(e.c).find(n=>n?.n==="parameters");return le(r?.c).find(n=>n?.n===t)}B.entryParameter=Jp;function Qp(e){return ai(e,"static")==="true"}B.isStaticParameter=Qp;function ys(e){let t=vs(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Jp(t[i],"RefId");if(!o||!Qp(o))return{kind:"unsupported"};let a=Mt(gs(o));if(!a)return{kind:"unsupported"};let s=Jp(t[i],"PageInput");if(s&&!Qp(s))return{kind:"unsupported"};let l=s?gs(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=ys;function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ef(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return ve(t)&&ve(t.data)?t.data:void 0}B.inputDataFrom=ef;function tf(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=tf;function rf(e){return sw(e.classId!==void 0?e.classId:Zp(e.bag,"classid"))}B.effectiveClassId=rf;function du(e){return!e.fieldName}B.isUnbound=du;function nf(e,t){if(tf(e)!=="Main"||!du(t)||rf(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Nn(t),n=r?Bi(e.bag,r):void 0;return n!==void 0&&ys(n).kind==="projectable"}B.isRecognizedEmbed=nf;function xB(e){for(let t of lw(e)){let r=t.control;if(!r||!nf(e,r))continue;let n=ys(Bi(e.bag,Nn(r)));if(n.kind!=="projectable")continue;let i=ef(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=xB;var LB=new Set(["pageId","inputData"]);function hs(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function kB(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new _B.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let o=new Set,a=i.getElementsByTagName("control");for(let u=0;u<a.length;u+=1){let c=Mt(a[u].getAttribute("uniqueid"));c&&o.add(c)}let s=hs(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?hs(s):[]){let c=Mt(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!o.has(c)))for(let d of hs(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let p=hs(d).find(h=>h.nodeName==="parameters"),f=p?hs(p).find(h=>h.nodeName==="RefId"):void 0,m=f&&f.getAttribute("static")==="true"?Mt(f.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=kB;function lu(e){return{n:`<${e}`,a:[],c:[]}}function Xp(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[lu(t)]}}function Yp(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);ve(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function FB(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[Xp("RefId",t),...r===void 0?[]:[Xp("PageInput",Yp(r))]]}]}))}}function cu(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>cu(r,t[n]));if(ve(e)&&ve(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&cu(e[n],t[n]))}return e===t}function MB(e,t,r){let n=le(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Mt(gs(i))!==t&&(i.c=[lu(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?gs(a):void 0;if(cu(ef(s),r))return;if(r!==void 0){a?a.c=[lu(Yp(r,s))]:n.c.push(Xp("PageInput",Yp(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[lu(JSON.stringify(l))]}function of(e){let t=le(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=of;function BB(e,t){var r;let n=e.bag,i=Mo(n);if(i&&t){let o=uu(t),a=uu(e),s=PB(t),l=RB(e),u=le(i.node.c),c=[];for(let d of u){let p=d?.n==="controlDescription"&&vs(d).length>0?Mt(ai(d,"forControl")):"";if(!p||!o.has(p))c.push(d);else if(a.has(p))if(s.has(p)&&OB(l.get(p))&&cu(d,Bi(t.bag,p))){let f=le(d.c).filter(m=>!uw(m));f.length>0&&c.push({...d,c:f})}else c.push(d)}(c.length!==u.length||c.some((d,p)=>d!==u[p]))&&(i.node.c=c)}for(let{cell:o}of Kr(e)){let a=o.control;if(!$i(a)||!ve(a.genPage))continue;let s=Mt(a.genPage.pageId),l=a.genPage.inputData,u=Nn(a);if(!u){if(pu(a)!==void 0)continue;u=pw(a)}let c=Bi(n,u);if(c){for(let f of vs(c))MB(f,s,l);continue}i||(i={i:of(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Zp(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),p=d.startsWith("{")?d:`{${u}}`;i.node.c.push(FB(p,s,l))}}B.reconcileEmbedDescriptions=BB;function $B(e,t){let r=Mo(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Kr(e).some(({cell:a})=>$i(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=Mo(o.bag);s?s.node=a:(o.bag=ve(o.bag)?o.bag:{a:[],c:[]},o.bag.c=le(o.bag.c),o.bag.c.push({i:of(e.bag),node:a}))}for(let{cell:a}of Kr(o))$i(a.control)&&(cw(a.control),dw(a));return o}B.commitEmbedState=$B;function UB(e){if(Kr(e).some(({cell:r})=>$i(r.control)))return!0;let t=Mo(e.bag);return le(t?.node.c).some(r=>r?.n==="controlDescription"&&vs(r).length>0)}B.mayCommitEmbedState=UB;function cw(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=cw;function dw(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=dw;function $i(e){return ve(e)&&e.genPage!==void 0}B.hasGenPage=$i;function ow(e){return $i(e.control)&&(!e.control.id||!e.id||pu(e.control)===void 0)}function pu(e){let t=le(ve(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}function qB(e){if(!Kr(e).some(({cell:r})=>ow(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Kr(t)){if(!ow(r))continue;let n=r.control;n.id||(n.id=(0,Hp.newId)()),r.id||(r.id=(0,Hp.newId)()),pu(n)===void 0&&pw(n)}return t}B.mintEmbedIdentity=qB;function pw(e){let t=(0,Hp.newId)(),r=`{${t}}`;if(!ve(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=le(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=le(e.bag.c),t}function aw(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function VB(e){let t=le(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=ai(r,"name"))!==null&&n!==void 0?n:ai(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function GB(e){let t=[],r;for(let{cell:n,pointer:i}of Kr(e)){let o=n.control;if(!ve(o))continue;let a=`${i}/control`;if(o.genPage===void 0){zB(e,o,a,t);continue}r=r??uu(e),WB(e,o,a,r,t)}return t}B.genPageEmbedIssues=GB;function zB(e,t,r,n){if(!nf(e,t))return;let i=ys(Bi(e.bag,Nn(t)));n.push((0,ar.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function WB(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!ve(s))i.push((0,ar.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${aw(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Mt(s.pageId))&&i.push((0,ar.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!ve(s.inputData)&&i.push((0,ar.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${aw(s.inputData)}`));for(let f of Object.keys(s))LB.has(f)||i.push((0,ar.issue)(IB.JsonPointer.append(a,f),"genpage-embed-unknown-key",`'${f}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}du(t)||i.push((0,ar.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&sw(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,ar.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=tf(e);l!=="Main"&&i.push((0,ar.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=pu(t);u!==void 0&&!Mt(u)&&i.push((0,ar.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Nn(t);if(!c)return;let d=Bi(e.bag,c),p=d?ys(d):void 0;d&&p?.kind==="none"?i.push((0,ar.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${VB(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):p?.kind==="unsupported"&&i.push((0,ar.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,ar.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var lf=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.findMissingGenPages=si.GENPAGE_LOOKUP_CHUNK=void 0;var jB=Rt(),sf=ae();si.GENPAGE_LOOKUP_CHUNK=50;async function HB(e,t,r){let n=[...new Set(t.map(o=>(0,sf.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=si.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+si.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,sf.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,jB.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,sf.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}si.findMissingGenPages=HB});var cf=b(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.patchSystemForm=sr.assertSystemFormContentUnchanged=sr.readSystemFormContentEtag=sr.readSystemFormRowEtag=sr.unpublishedSystemFormPath=void 0;var Bt=be(),KB=ae(),uf=re();function fu(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,KB.odataQuery)([["$select",t]])}sr.unpublishedSystemFormPath=fu;function fw(e,t){return(0,Bt.readRowEtag)(e,"systemforms","formid",t)}sr.readSystemFormRowEtag=fw;async function JB(e,t){let r=fu(t);return(0,Bt.readEtag)((0,Bt.ensureSuccess)(await e.get(r),e.apiUrl(r)))}sr.readSystemFormContentEtag=JB;async function mw(e,t,r,n,i){(0,Bt.requireEtag)(i,r,t);let o=(0,Bt.readEtag)((0,Bt.ensureSuccess)(await e.get(n),e.apiUrl(n)));if(o===null)throw new uf.SdkError(Bt.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(o!==i)throw new uf.SdkError(Bt.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${o}). Re-fetch the ${r} and re-apply the change.`)}sr.assertSystemFormContentUnchanged=mw;async function QB(e,t,r,n,i,o){(0,Bt.requireEtag)(i,r,t);let a=await fw(e,t);if(a===null)throw new uf.SdkError(Bt.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);await mw(e,t,r,fu(t),i);let s=(0,Bt.echoWrite)("formid",{"If-Match":a}),l=`/systemforms(${t})${s.query}`;return(0,Bt.ensureSuccess)(await e.patch(l,n,s.options),e.apiUrl(l)),XB(e,t,r,o)}sr.patchSystemForm=QB;async function XB(e,t,r,n){let i;try{let o=fu(t,n.select),a=(0,Bt.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,Bt.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null);if(l&&u&&c&&d.length===0)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:`the read did not return its ${d.join(", ")}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var mf=b($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getFormSecurityRoles=$t.setFormSecurityRoles=$t.formApi=$t.FORM_GENPAGE_TARGET_UNVERIFIABLE=$t.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var YB=Rt(),ut=be(),lr=ae(),Ui=re(),df=oi(),gw=af(),ZB=lf(),mu=cf();$t.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";$t.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var vw="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",e$={select:vw,required:["name","type","objecttypecode"]},t$="formid,name,type,objecttypecode",r$=2,n$={Main:r$,QuickView:6,QuickCreate:7,Card:11};$t.formApi={async get(e,t){let n=`/systemforms(${(0,lr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select",vw]]),i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>n$[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,lr.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,lr.odataQuery)([["$select",t$],["$filter",a.join(" and ")]])}`;return(await(0,YB.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=hw(t);n!==void 0&&await yw(e,ff(n,"payload"),[]);let i=(0,ut.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,ut.ensureSuccess)(await e.post(o,(0,ut.withClientMintedId)(t,"formid",r),i.options),e.apiUrl(o));return{id:(0,ut.resolveCreatedId)(a,"formid","form",r),etag:(0,ut.readEtag)(a)}},async update(e,t,r,n){let i=(0,lr.normalizeGuid)(t,"id"),o=hw(r);return o!==void 0&&await o$(e,i,o,n),(0,mu.patchSystemForm)(e,i,"form",r,n,e$)},readToken(e,t){return(0,mu.readSystemFormContentEtag)(e,(0,lr.normalizeGuid)(t,"id"))},delete(e,t){return(0,ut.deleteRecord)(e,"systemforms",t)}};var pf="DisplayConditions";async function i$(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Ui.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,lr.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),u=(0,ut.ensureSuccess)(await e.get(l),e.apiUrl(l)),c=(0,ut.readEtag)(u),d=u.body,p=d?.formxml;if(!p)throw new Ui.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let f=(0,df.parseXmlRoot)(p,"<form/>"),m=f.ownerDocument;if(!m)throw new Ui.InvalidArgumentError(`form '${s}' produced no owner document`);let h=bw(f,pf),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,y=h?.getAttribute("FallbackForm")||void 0;h&&f.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Ui.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),f.appendChild(h)}else if(w){let k=m.createElement(pf),F=r.order!==void 0?String(r.order):g;F!==void 0&&k.setAttribute("Order",F);let P=r.fallbackForm!==void 0?String(r.fallbackForm):y??"false";if(k.setAttribute("FallbackForm",P),r.everyone)k.appendChild(m.createElement("Everyone"));else for(let q of(a=r.roleIds)!==null&&a!==void 0?a:[]){let V=m.createElement("Role");V.setAttribute("Id",`{${(0,lr.normalizeGuid)(q,"roleId")}}`),k.appendChild(V)}f.appendChild(k)}let S=(0,df.serializeNode)(f);await(0,mu.assertSystemFormContentUnchanged)(e,s,"form",l,c);let T=await(0,mu.readSystemFormRowEtag)(e,s),O=`/systemforms(${s})`;(0,ut.ensureSuccess)(await e.patch(O,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,ut.requireEtag)(T,"form",s)}}),e.apiUrl(O))}$t.setFormSecurityRoles=i$;function hw(e){let t=e?.formxml;return typeof t=="string"&&t.includes(gw.GENPAGE_CONTROL_NAME)?t:void 0}function ff(e,t){try{return(0,gw.activeEmbedBindings)(e)}catch(r){throw new Ui.SdkError($t.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function yw(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,ZB.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Ui.SdkError($t.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function o$(e,t,r,n){var i;(0,ut.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),a=(0,ut.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(0,ut.readEtag)(a);if(s===null||s!==n)throw new Ui.SdkError(ut.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?ff(l,"server"):[];await yw(e,ff(r,"payload"),u)}function bw(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function a$(e,t){var r,n;let o=`/systemforms(${(0,lr.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,ut.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,df.parseXmlRoot)(s,"<form/>"),u=bw(l,pf);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let m=0;m<p.length;m+=1){let h=p[m];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let y=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";y&&c.push(y.replace(/[{}]/g,"").toLowerCase())}}let f=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...f!==null&&f!==""?{order:Number(f)}:{}}}$t.getFormSecurityRoles=a$});var vu=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.disassociateRecords=Oe.associateRecords=Oe.createRecordsBulk=Oe.upsertRecord=Oe.queryAllRecords=Oe.queryRecords=Oe.getRecord=Oe.deleteRecord=Oe.updateRecord=Oe.createRecord=void 0;var s$=Rt(),Dr=be(),mt=ae(),hu=re(),Jr=Vl();function gu(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function l$(e,t,r){let i=`/${await(0,Jr.resolveEntitySetName)(e,t)}`,o=(0,Dr.ensureSuccess)(await e.post(i,gu(r)),e.apiUrl(i)),a=(0,Dr.readCreatedId)(o,`${t}id`);if(!a)throw new hu.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Oe.createRecord=l$;async function u$(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),a=`/${await(0,Jr.resolveEntitySetName)(e,t)}(${i})`;(0,Dr.ensureSuccess)(await e.patch(a,gu(n)),e.apiUrl(a))}Oe.updateRecord=u$;async function c$(e,t,r){let n=(0,mt.normalizeGuid)(r,"id"),o=`/${await(0,Jr.resolveEntitySetName)(e,t)}(${n})`;(0,Dr.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Oe.deleteRecord=c$;async function d$(e,t,r,n){var i;let o=(0,mt.normalizeGuid)(r,"id"),a=await(0,Jr.resolveEntitySetName)(e,t),s=(0,mt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${a}(${o})${s}`;return(i=(0,Dr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Oe.getRecord=d$;function p$(e){return e?.fetchXml?(0,mt.odataQuery)([["fetchXml",e.fetchXml]]):(0,mt.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function ww(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new hu.InvalidArgumentError("queryRecords: `paginate` cannot be combined with `top` \u2014 Dataverse honors $top as a hard cap and omits @odata.nextLink, so the result would be silently capped at one page.");if(r.fetchXml)throw new hu.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let a=`/${await(0,Jr.resolveEntitySetName)(e,t)}${p$(r)}`;return r?.paginate?(0,s$.collectPages)(e,a,"queryRecords"):(i=(n=(0,Dr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Oe.queryRecords=ww;async function f$(e,t,r){return ww(e,t,{...r,paginate:!0})}Oe.queryAllRecords=f$;function m$(e){if("id"in e)return`(${(0,mt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,mt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,mt.assertODataName)(e.key,"alternate key name")}=${t})`}async function h$(e,t,r,n){let i=m$(r),a=`/${await(0,Jr.resolveEntitySetName)(e,t)}${i}`,s=(0,Dr.ensureSuccess)(await e.patch(a,gu(n)),e.apiUrl(a)),l=s.status===201,u=(0,Dr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,mt.normalizeGuid)(r.id,"id"):""),created:l}}Oe.upsertRecord=h$;async function g$(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Jr.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...gu(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Dr.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new hu.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Oe.createRecordsBulk=g$;async function v$(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),o=(0,mt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Jr.resolveEntitySetName)(e,t),s=await(0,Jr.resolveEntitySetName)(e,n.targetEntity),l=(0,mt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Dr.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Oe.associateRecords=v$;async function y$(e,t,r,n,i){let o=(0,mt.normalizeGuid)(r,"id"),a=(0,mt.normalizeGuid)(i,"targetId"),s=await(0,Jr.resolveEntitySetName)(e,t),l=(0,mt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Dr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Oe.disassociateRecords=y$});var bu=b(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.base64ToUtf8=Qr.base64ToBytes=Qr.bytesToBase64=Qr.utf8ToBase64=void 0;var hf=32768,Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function yu(){return globalThis}function b$(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function w$(e){let t="";for(let r=0;r<e.length;r+=hf)t+=String.fromCharCode(...e.subarray(r,r+hf));return t}function A$(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Ut.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function E$(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Ut[i>>18&63]+Ut[i>>12&63]+Ut[i>>6&63]+Ut[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Ut[i>>18&63]}${Ut[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Ut[i>>18&63],a=Ut[i>>12&63],s=Ut[i>>6&63];t+=`${o}${a}${s}=`}return t}function C$(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Ut.indexOf(e[o])<<18|Ut.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Ut.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Ut.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function S$(e){let t=yu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return Aw(r?new r().encode(e):b$(e))}Qr.utf8ToBase64=S$;function Aw(e){let t=yu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(w$(e)):E$(e)}Qr.bytesToBase64=Aw;function Ew(e){let t=yu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=A$(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return C$(r)}Qr.base64ToBytes=Ew;function N$(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=hf&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,p=!0;for(let f=0;f<s;f+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){p=!1;break}u=128,c=191,l=l<<6|m&63}p?(i(l),o=d):(i(65533),o=d)}return n(),r}function D$(e){let t=yu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):N$(Ew(e))}Qr.base64ToUtf8=D$});var Dw=b(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.deleteWebResource=Xr.getWebResource=Xr.updateWebResource=Xr.createWebResource=void 0;var _$=nr(),bs=be(),wu=ae(),I$=bu(),Cw=re(),T$={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function Sw(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,I$.utf8ToBase64)(e.content)}async function Nw(e,t){return(0,_$.publishWebResourceById)(e,t)}async function P$(e,t){var r;let n=Sw(t);if(n===void 0)throw new Cw.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(r=t.displayName)!==null&&r!==void 0?r:t.name,webresourcetype:T$[t.type],content:n};t.description&&(i.description=t.description);let o=(0,bs.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,bs.readCreatedId)(o,"webresourceid");if(!a)throw new Cw.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await Nw(e,a),{id:a,name:t.name}}Xr.createWebResource=P$;async function R$(e,t,r){let n=(0,wu.normalizeGuid)(t,"id"),i={},o=Sw(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,bs.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await Nw(e,n)}Xr.updateWebResource=R$;async function O$(e,t){var r;let i=`/webresourceset(${(0,wu.normalizeGuid)(t,"id")})${(0,wu.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,bs.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Xr.getWebResource=O$;async function x$(e,t){let n=`/webresourceset(${(0,wu.normalizeGuid)(t,"id")})`;(0,bs.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Xr.deleteWebResource=x$});var Au=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.applyAppSettings=Ze.setAppSetting=Ze.readAppSettings=Ze.resolveSettingDefinitions=Ze.APP_SETTING_UNSET=Ze.APP_SETTING_OFF=Ze.APP_SETTING_ON=Ze.HEADER_AND_NAVIGATION_REFRESH=void 0;var Bo=be(),Dn=ae();Ze.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Ze.APP_SETTING_ON="2";Ze.APP_SETTING_OFF="1";Ze.APP_SETTING_UNSET="0";function Tw(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Dn.odataQuery)([["$select",e],["$filter",t]])}async function Pw(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Dn.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Dn.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Bo.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Ze.resolveSettingDefinitions=Pw;async function L$(e,t){var r,n,i,o;let a=(0,Dn.normalizeGuid)(t,"App id"),s=Tw("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Bo.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(p=>p._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let p=c.map(h=>`settingdefinitionid eq ${(0,Dn.normalizeGuid)(h,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,Dn.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,m=(0,Bo.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let h of((o=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(p=>{var f,m,h,g,y;let w=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(m=p.appsettingid)!==null&&m!==void 0?m:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:p._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(y=p.value)!==null&&y!==void 0?y:"",...w?.displayname?{displayName:w.displayname}:{}}})}Ze.readAppSettings=L$;async function _w(e,t,r){var n,i,o;let a=Tw("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Bo.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function Rw(e,t,r,n){let i=(0,Dn.normalizeGuid)(t,"App id"),a=(await Pw(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,Dn.normalizeGuid)(s,"Setting definition id"),u=await _w(e,i,l);if(u)return Iw(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,f;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(h){f=h}let m;try{m=await _w(e,i,l)}catch{m=void 0}if(m)return Iw(e,m,n);throw p&&(0,Bo.ensureSuccess)(p,e.apiUrl(c)),f}Ze.setAppSetting=Rw;async function Iw(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Dn.normalizeGuid)(t.id,"App setting id")})`;return(0,Bo.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function k$(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await Rw(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Ze.applyAppSettings=k$});var Cu=b(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.HEADER_NAV_BOOLEAN_RULE=void 0;Eu.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Mw=b(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.deleteSolution=ue.importSolution=ue.exportSolution=ue.removeSolutionComponent=ue.addSolutionComponent=ue.setSolutionVersion=ue.createSolution=ue.createPublisher=ue.getSolution=ue.fetchSolutionComponents=ue.resolveGenPageComponentType=ue.SolutionComponentType=void 0;var kw=Rt(),ur=be(),At=ae(),li=re();ue.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var Ow=[ue.SolutionComponentType.SavedQuery,ue.SolutionComponentType.Workflow,ue.SolutionComponentType.SavedQueryVisualization,ue.SolutionComponentType.SystemForm,ue.SolutionComponentType.AppModule],xw="uxagentproject",Lw=new WeakMap;async function Fw(e){var t;let r=Lw.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${xw}')${(0,At.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,ur.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new li.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${xw}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return Lw.set(e,o),o}ue.resolveGenPageComponentType=Fw;async function F$(e,t){let r=(0,At.normalizeGuid)(t,"solutionId"),n=await Fw(e),o=(n===void 0?Ow:[...Ow,n]).map(u=>`msdyn_componenttype eq ${u}`).join(" or "),a=`/msdyn_solutioncomponentsummaries${(0,At.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${o})`]])}`,l=(await(0,kw.collectPages)(e,a,"fetchSolutionComponents")).filter(u=>typeof u.msdyn_objectid=="string").map(u=>{let c=Number(u.msdyn_componenttype);return{objectId:u.msdyn_objectid,componentType:c,...n!==void 0&&c===n?{genPage:!0}:{},workflowCategory:u.msdyn_workflowcategory==null?void 0:Number(u.msdyn_workflowcategory),displayName:u.msdyn_displayname,name:u.msdyn_name}});return n===void 0?l:[...l,...await M$(e,r,l,n)]}ue.fetchSolutionComponents=F$;async function M$(e,t,r,n){let i=new Set(r.map(l=>l.objectId.toLowerCase())),o=`/solutioncomponents${(0,At.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${n}`]])}`,a=await(0,kw.collectPages)(e,o,"fetchSolutionComponents(draft pages)"),s=[];for(let l of a){let u=typeof l.objectid=="string"?l.objectid:void 0;u&&!i.has(u.toLowerCase())&&(i.add(u.toLowerCase()),s.push({objectId:u,componentType:n,genPage:!0}))}return s}function B$(e){let t=e.length===38&&e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e;return/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(t)}async function $$(e,t){var r,n,i,o,a,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new li.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=B$(p)?`solutionid eq ${(0,At.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,At.odataLiteral)(p)}'`,m=`/solutions${(0,At.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,y=((n=(r=(0,ur.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!y?.solutionid)throw new li.InvalidArgumentError(`No solution found for '${t}'.`);let w=y.publisherid;if(!w?.publisherid)throw new li.InvalidArgumentError(`Solution '${(i=y.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new li.InvalidArgumentError(`Solution '${(o=y.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,At.normalizeGuid)(y.solutionid,"solutionId"),uniqueName:(a=y.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=y.friendlyname)!==null&&s!==void 0?s:"",version:(l=y.version)!==null&&l!==void 0?l:"",isManaged:!!y.ismanaged,publisherId:(0,At.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}ue.getSolution=$$;async function U$(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,ur.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),o=(0,ur.readCreatedId)(i,"publisherid");if(!o)throw new li.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ue.createPublisher=U$;async function q$(e,t){var r;let n=(0,At.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,ur.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,ur.readCreatedId)(o,"solutionid");if(!a)throw new li.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ue.createSolution=q$;async function V$(e,t,r){let i=`/solutions(${(0,At.normalizeGuid)(t,"solutionId")})`;(0,ur.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ue.setSolutionVersion=V$;async function G$(e,t){var r;let i={ComponentId:(0,At.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(r=t.addRequiredComponents)!==null&&r!==void 0?r:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,ur.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ue.addSolutionComponent=G$;async function z$(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,At.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,ur.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}ue.removeSolutionComponent=z$;async function W$(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,ur.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new li.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}ue.exportSolution=W$;async function j$(e,t){var r,n;let i={OverwriteUnmanagedCustomizations:(r=t.overwriteUnmanagedCustomizations)!==null&&r!==void 0?r:!0,PublishWorkflows:(n=t.publishWorkflows)!==null&&n!==void 0?n:!0,CustomizationFile:t.base64};t.importJobId&&(i.ImportJobId=(0,At.normalizeGuid)(t.importJobId,"importJobId")),(0,ur.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}ue.importSolution=j$;async function H$(e,t){let n=`/solutions(${(0,At.normalizeGuid)(t,"solutionId")})`;(0,ur.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ue.deleteSolution=H$});var bf=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.compileGenPage=Ee.legacyEnumsNeeded=Ee.createGenPageTypeScriptLoader=Ee.acceptGenPageTypeScript=Ee.isLoadableGenPageOutput=Ee.GENPAGE_RUNTIME_TYPES_END=Ee.GENPAGE_RUNTIME_TYPES_BEGIN=Ee.GENPAGE_TYPESCRIPT_VERSION=void 0;var $o=re();Ee.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Ee.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Ee.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var K$=/(import\s+[^'"]+)(['"`])(\.\/RuntimeTypes)\2;?\s*/g,ui="./RuntimeTypes",J$=/\b(import\s.+from\s+['"]|import\s*['"]|export\s)/;function Q$(e){return e!==void 0&&e!==""&&J$.test(e)}Ee.isLoadableGenPageOutput=Q$;var Bw=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function qw(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?Bw.filter(s=>typeof n?.[s]!="function"):[...Bw];if(!n||i.length>0)throw new $o.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Ee.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new $o.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Ee.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Ee.acceptGenPageTypeScript=qw;function X$(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new $o.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(qw).catch(r=>{throw t=void 0,r instanceof $o.SdkError?r:new $o.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Ee.createGenPageTypeScriptLoader=X$;var Vw=e=>`${e.kind}:${e.pos}:${e.end}`;function Y$(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(Vw(o)),e.forEachChild(i,n)};return n(r),r}}function yf(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var Z$=2301;function $w(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:yf(e),reportDiagnostics:!0,...r?{transformers:{after:[Y$(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`
+`)}});return{code:i.outputText,diagnostics:o}}var Uw=e=>e.startsWith(".")||e.startsWith("/"),gf={line:1,column:1};function vf(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):gf},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(p=>p.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return gf}}}function eU(e,t,r,n){var i,o;let a=[],s=vf(e,r),l=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},u=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(y=>y.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",p=!1,f=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){p=p||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(p=!0),m.name&&f.add(m.name.text);continue}if(e.isExportDeclaration(m)){let w=m.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(p=!0);let C=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;C===ui?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&Uw(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,g=m.importClause;if(h!==ui){Uw(h)&&c(s.statement(h,"import"),h),g?.name&&f.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?f.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>f.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let y=g.namedBindings;if(y&&e.isNamespaceImport(y))l(s.binding(y.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(y&&e.isNamedImports(y))for(let w of y.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,T=s.element(h,C);S!==C?l(T,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(T,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(T,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(p||l(gf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of f)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function Gw(e,t,r){let n,i=()=>{if(!n){let m={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
+`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===Z$&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch{}}return s},u=m=>e.isImportSpecifier(m)?m.parent.parent.parent:e.isImportClause(m)?m.parent:e.isNamespaceImport(m)?m.parent.parent:void 0,c=m=>{let h=u(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===ui},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(y=>y.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},p=m=>d(m)||e.isImportEqualsDeclaration(m)&&(m.isTypeOnly||e.isExternalModuleReference(m.moduleReference))||e.isImportClause(m)&&m.isTypeOnly||e.isNamespaceImport(m)&&m.parent.isTypeOnly||e.isImportSpecifier(m)&&(m.isTypeOnly||m.parent.parent.isTypeOnly),f=m=>{var h;return((h=m?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!p(g))};return{pageOwns:m=>{let h=m.parent;return f(e.isShorthandPropertyAssignment(h)&&h.name===m?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(m))},pageOwnsLocalExport:m=>f(a().getExportSpecifierLocalTargetSymbol(m)),initializerShadow:m=>l().get(m.getStart(t))}}function tU(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let p=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:p.line+1,column:p.character+1,rule:c,code:0,message:d})},s=Gw(e,t,yf(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let f=u.argumentExpression;e.isStringLiteral(f)||e.isNoSubstitutionTemplateLiteral(f)?(c=u.expression,d=f.text):e.isNumericLiteral(f)&&(c=u.expression,d=String(Number(f.text)))}let p=c&&o.has(c.text)&&n.has(Vw(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&p&&d!==void 0){let f=e.isPropertyAccessExpression(u)?`${p.name}.${d}`:`${p.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(p.runtime,d)?p.runtime[d]:void 0,h=p.labels.get(d),g;m===void 0?g={rule:"genpage-enum-member-unknown",message:`${f} is undefined at runtime: '${p.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...p.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof m!="number"?g={rule:"genpage-enum-member-clobbered",message:`${f} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${f} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let y=g?s.initializerShadow(c):void 0;g&&y!==void 0?a(u,"genpage-enum-initializer-shadowed",`${f} does not read the choice enum at runtime. ${y} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function rU(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===ui)}function nU(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(a=>e.isImportDeclaration(a)&&e.isStringLiteral(a.moduleSpecifier)&&a.moduleSpecifier.text===ui).map(a=>a.getStart(r))),i=!0;return{code:t.replace(K$,(...a)=>(n.has(a[a.length-2])||(i=!1),"")),exact:i}}function zw(e,t,r){if(!r||r.size===0)return[];let n=Gw(e,t,{...yf(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===ui&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Ee.legacyEnumsNeeded=zw;function iU(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function oU(e,t,r,n){let i=new Set,o=$w(e,t,i);if(o.diagnostics.length>0)return o;let a=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",o.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=iU(r,n,zw(e,s,n)),u=[...eU(e,s,a,l),...tU(e,a,l,i)];if(!l?.text)return{code:o.code,diagnostics:u};let c=$w(e,l.text);if(c.diagnostics.length>0)throw new $o.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=nU(e,o.code),p=d.code;return u.length===0&&!d.exact?u.push({...vf(e,a).statement(ui,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&rU(e,p)&&u.push({...vf(e,a).statement(ui,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[Ee.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,Ee.GENPAGE_RUNTIME_TYPES_END,p].join(`
-`),diagnostics:u}}Ee.compileGenPage=sU});var gu=y(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.appApi=ei.deleteAppResolvingOnce=ei.unpublishedAppModulesQuery=void 0;var _w=Pt(),lU=wf(),uU=Zp(),Aw=Nr(),cU=pu(),ve=be(),fe=ae(),gf=lt(),dU=Ol(),Ae=te(),pU=(0,fe.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),pf="appmoduleid,name,uniquename,description,aiappdescription";function Tw(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,fe.odataQuery)([["$select",e],["$filter",t],["$top",r]])}ei.unpublishedAppModulesQuery=Tw;function ff(e,t){return Tw(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function hu(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,fe.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function Oa(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function fU(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function vf(e,t){if(typeof e!="string")return!1;try{return(0,fe.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ds(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function mU(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function Pw(e,t){var r,n;let i=u=>{throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let a=`/sitemaps${(0,fe.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,fe.odataLiteral)(t)}'`],["$top",1]])}`,o;try{o=await e.get(a)}catch(u){return i(`failed (${u.message})`)}if(o.status<200||o.status>=300)return i(`returned HTTP ${o.status}`);let s=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function hU(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,fe.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let a=t(await e.get(r(`${n} and ismanaged eq false`)));if(a)return{id:a,managed:!1};let o=t(await e.get(r(n)));return o?{id:o,managed:!0}:void 0}function yf(e){return e instanceof Error?e.message:String(e)}async function gU(e,t){var r,n,i;try{let a=`/roles${(0,fe.odataQuery)([["$select","roleid"],["$filter","name eq 'System Administrator'"],["$top",1]])}`,s=(i=(n=(r=(0,ve.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.roleid;if(!s)return"App roles: no 'System Administrator' role was found in this environment, so the app was created with NO security role associated \u2014 it will not be visible or playable until a role is granted access to it.";let l=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,ve.ensureSuccess)(await e.post(l,{"@odata.id":e.apiUrl(`/roles(${s})`)}),e.apiUrl(l)),null}catch(a){return`App roles: could not associate the 'System Administrator' role with the app (${yf(a)}); it will not be visible or playable until a role is granted access to it.`}}async function vU(e,t){let r=[];async function n(s,l,u){try{return(await(0,_w.collectPages)(e,s,`app assets (${u} for '${t}')`)).map(d=>String(d[l])).filter(d=>d&&d!=="undefined")}catch(c){return r.push(`App components: could not enumerate ${u} for table '${t}' (${yf(c)}); they were NOT added to the app.`),[]}}let[i,a,o]=await Promise.all([n(`/systemforms${(0,fe.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,fe.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"),n(`/savedqueries${(0,fe.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,fe.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),n(`/savedqueryvisualizations${(0,fe.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,fe.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:i,views:a,charts:o,warnings:r}}var Ew=new WeakMap;async function yU(e,t){let r=Ew.get(e);r||(r=new Map,Ew.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await bU(e,t);return i&&r.set(t,i),i}async function Cw(e,t,r){let n=new Array(e.length),i=0;async function a(){for(let o=i;o<e.length;o=i)i=o+1,n[o]=await r(e[o])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),n}async function bU(e,t){let r=`/EntityDefinitions(LogicalName='${(0,fe.odataPathLiteral)(t)}')${(0,fe.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function Sw(e,t){let r=[],n=ds(t.entities),i=4,a=await Cw(n,i,f=>yU(e,f)),o=n.filter((f,m)=>!a[m]);if(o.length>0)throw new Ae.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${o.map(f=>`'${f}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let s=a.filter(f=>!!f);for(let f of s)r.push({"@odata.id":`${f.entitySetName}(${f.metadataId})`});for(let f of ds(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});for(let f of ds(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:f});for(let f of ds(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:f});for(let f of ds(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:f});let l=new Set(t.components.forms),u=new Set(t.components.views),c=new Set(t.components.charts),d=await Cw(n,i,f=>vU(e,f)),p=d.flatMap(f=>f.warnings);for(let f of d){for(let m of f.forms)l.has(m)||(l.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:m}));for(let m of f.views)u.has(m)||(u.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:m}));for(let m of f.charts)c.has(m)||(c.add(m),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:m}))}return{components:r,tables:s,warnings:p}}async function Nw(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ve.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function wU(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,fe.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function Dw(e,t,r){var n;if(r.length===0)return;let i=wU(t),a=await e.get(i);if(a.status<200||a.status>=300)throw new Ae.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the unpublished-aware read returned HTTP ${a.status}. Re-push to retry.`);let o=Oa(a),s=o?.appmoduleidunique;if(typeof s!="string"||!s)throw new Ae.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the app did not return an 'appmoduleidunique' to file components under. Re-push to retry.`);let l=`/appmodulecomponents${(0,fe.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,fe.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new Ae.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${u.status}. Re-push to retry.`);let c=(n=u.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(c))throw new Ae.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let d=new Set(c.map(f=>f.objectid).filter(f=>typeof f=="string").map(f=>f.toLowerCase())),p=r.filter(f=>!d.has(f.metadataId.toLowerCase()));if(p.length>0)throw new Ae.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${p.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${p.map(f=>`'${f.logicalName}' (expected objectid ${f.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function AU(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`;try{let a=await EU(e,r.sitemapId,r.sitemapNameUnique);if(a==="absent"){r.serverRefusedSitemap&&(0,ve.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(a==="foreign"){r.serverRefusedSitemap&&(0,ve.ensureSuccess)(await e.delete(n),e.apiUrl(n));return}if(e.supportsAtomicBatch){if(!r.sitemapWriteToken)return;await Ow(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])}}catch{}}async function EU(e,t,r){var n,i,a;let o=hu(t,"sitemapid,sitemapnameunique"),s=await e.get(o);if(s.status<200||s.status>=300)throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((a=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&a!==void 0?a:"")===r?"ours":"foreign"}async function Rw(e,t){var r;let n=(0,fe.normalizeGuid)(t,"id"),i=h=>{throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${h} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)},a=`/appmodules(${n})${pU}`,o;try{o=await e.get(a)}catch(h){return i(`reading the app failed (${h.message}).`)}if(o.status<200||o.status>=300)return i(o.status===404?"reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap.":`reading the app returned HTTP ${o.status}.`);let s=(r=o.body)===null||r===void 0?void 0:r.uniquename;if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let l=await Pw(e,s);if(!l)return{uniquename:s,appEtag:(0,ve.readEtag)(o)};let u=(0,fe.normalizeGuid)(l,"sitemapId"),c=await bf(e,u),d=hu(u,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(d)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${u}' returned HTTP ${p.status}.`);let f=Oa(p);if(!f)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(f.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!vf(f.sitemapid,u))return i(`sitemap '${u}' was read back as a row carrying sitemapid '${String(f.sitemapid)}'.`);let m=f.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,ve.readEtag)(o),sitemapEtag:c}}async function CU(e,t,r){let n=(0,fe.normalizeGuid)(t,"id"),i=await Rw(e,n);await r?.(i.sitemapXml),await xw(e,n,i)}ei.deleteAppResolvingOnce=CU;async function Ow(e,t){let r=`batch_${(0,gf.newId)()}`,n=`changeset_${(0,gf.newId)()}`,i=t.map((d,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(d.path)} HTTP/1.1`,...d.etag?[`If-Match: ${d.etag}`]:[],""].join(`\r
-`)),a=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r
-`),o=await e.postBatch(a,r),s=e.apiUrl("/$batch");(0,ve.ensureSuccess)(o,s);let l=`app '${t[0].path}'`;if(typeof o.body!="string"||o.body.length===0)throw new Ae.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let u=(0,dU.parseChangeSetStatuses)(o.body,i.map((d,p)=>String(p+1)));if(u===void 0)throw new Ae.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);let c=u.find(d=>d<200||d>=300);if(c!==void 0)throw new Ae.ConnectionError(s,c,`atomic delete of ${l} was rolled back: the change set reported HTTP ${c}`);if(u.length!==i.length)throw new Ae.ConnectionError(s,o.status,`atomic delete of ${l} cannot be confirmed: the $batch response reported ${u.length} operation result(s), expected exactly ${i.length}`)}async function bf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ve.readEtag)(r)}catch{return null}}async function mf(e,t,r,n){if(!n)return null;let i=await bf(e,t);if(!i)return null;try{let a=await e.get(hu(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(a.status<200||a.status>=300)return null;let o=Oa(a);return!o||!vf(o.sitemapid,t)||o.sitemapnameunique!==n||o.sitemapxml!==r.sitemapxml||o.sitemapname!==r.sitemapname?null:i}catch{return null}}function SU(e){return e>=400&&e<500&&e!==408&&e!==429}function hf(e,t,r){if(!e)throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function xw(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await NU(e,n,hf(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new Ae.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await Ow(e,[{path:n,etag:hf(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:hf(r.sitemapEtag,t,"sitemap")}])}async function NU(e,t,r){(0,ve.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function Iw(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,lU.collectGenPageIds)(t))]}catch(i){throw new Ae.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${yf(i)}).`)}if(r.length===0)return;let n=await(0,uU.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Ae.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function DU(e){var t,r;if(e.status!==400)return!1;let n=e.body;return String((r=(t=n?.error)===null||t===void 0?void 0:t.message)!==null&&r!==void 0?r:"").includes("retrieval of version numbers failed")}ei.appApi={async get(e,t){var r;let n=(0,fe.normalizeGuid)(t,"id"),i=ff(pf,n),a=(0,ve.ensureSuccess)(await e.get(i),e.apiUrl(i)),o=(r=Oa(a))!==null&&r!==void 0?r:{};if(!o.appmoduleid)throw new Ae.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let s=await Pw(e,o.uniquename),l=s?(0,fe.normalizeGuid)(s,"sitemapId"):void 0,u=null;if(l){u=await bf(e,l);let d=hu(l,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),p=(0,ve.ensureSuccess)(await e.get(d),e.apiUrl(d)),f=Oa(p),m=h=>{throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': its sitemap '${l}' was located by unique name, but ${h}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!f)return m("the by-id read returned no row");if(f.sitemapnameunique!==o.uniquename)throw new Ae.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${l}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${String(o.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!vf(f.sitemapid,l))return m(`the by-id read returned a row carrying sitemapid '${String(f.sitemapid)}'`);if(typeof f.sitemapxml!="string")return m("the by-id read returned no sitemapxml");o.$sitemap=f}let c=fU(o);return{raw:o,etag:u,...o.appmoduleid?{siblingEtags:{[(0,fe.normalizeGuid)(o.appmoduleid,"appmoduleid")]:c}}:{}}},async list(e,t){let r=ff(pf);return(await(0,_w.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var a,o;return{type:"app",id:(a=i.appmoduleid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",isDirty:!1}})},async create(e,t,r){let n=t;await Iw(e,n.sitemapxml);let i=n.iconWebResourceId?void 0:await hU(e),a=n.iconWebResourceId||i?.id;if(!a)throw new Ae.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let o=null;i?.managed&&(o=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${i.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let s=n.appModuleUniqueName||mU(n.appModuleId),l={name:n.appModuleName,uniquename:s,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(l.description=n.appModuleDescription),n.appModuleAiDescription&&(l.aiappdescription=n.appModuleAiDescription),a&&(l.webresourceid=a);let u="/appmodules",c=(0,ve.ensureSuccess)(await(0,ve.resendDeadlockVictim)(()=>e.post(u,(0,ve.withClientMintedId)(l,"appmoduleid",r))),e.apiUrl(u)),d=(0,ve.resolveCreatedId)(c,"appmoduleid","app module",r),p=null,f=null,m=[];o&&m.push(o);let h={kind:"notRequested"},v=n.sitemapId?(0,fe.normalizeGuid)(n.sitemapId,"sitemapId"):(0,gf.newId)(),b=!1,E={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let N="/sitemaps",R=(0,ve.echoWrite)("sitemapid"),O=await e.post(`${N}${R.query}`,{sitemapid:v,sitemapnameunique:s,...E},R.options);b=SU(O.status);let F=(0,ve.ensureSuccess)(O,e.apiUrl(N));f=(0,ve.readEtag)(F),p=f??await mf(e,v,E,s);let k=await Sw(e,n);m.push(...k.warnings);let P=k.components;P.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:v}),await Nw(e,d,P),await Dw(e,d,k.tables);let V=await gU(e,d);V&&m.push(V),n.appSettings&&Object.keys(n.appSettings).length>0&&m.push(...await(0,cU.applyAppSettings)(e,d,n.appSettings)),n.published!==!1&&(await(0,Aw.publishAppModule)(e,d),h={kind:"submitted"})}catch(N){throw await AU(e,d,{sitemapId:v,sitemapNameUnique:s,serverRefusedSitemap:b,sitemapWriteToken:f}),N}let C=null;if(h.kind==="submitted")try{let N=await e.get(`/appmodules(${d})?$select=appmoduleid`);N.status>=200&&N.status<300&&(C=(0,ve.readEtag)(N))}catch{}return{id:d,etag:p,serverIdentity:{sitemapId:v},siblingEtags:{[d]:C},publish:h,...m.length>0?{warnings:m}:{}}},async update(e,t,r,n,i,a){var o,s,l,u,c,d,p,f,m;let h=r,v=(0,fe.normalizeGuid)(t,"id");if(await Iw(e,h.sitemapxml),!h.sitemapId)throw new Ae.ValidationError("app",v,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${v}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${v}'), clear the local copy with deleteArtifact('app', '${v}'), then author the app again and push.`}]);let b=(0,fe.normalizeGuid)(h.sitemapId,"sitemapId");if(!n)throw new Ae.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${v}': no concurrency token is held for its sitemap row, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the app and re-apply the change.`);let E=await Sw(e,h),C=`/appmodules(${v})`,N=(o=a?.[v])!==null&&o!==void 0?o:null,R=!0,O=!1,F;try{let xe=ff(pf,v),$n=await e.get(xe);if($n.status>=200&&$n.status<300){let nr=(s=Oa($n))!==null&&s!==void 0?s:{};O=!0,F=typeof nr.uniquename=="string"&&nr.uniquename?nr.uniquename:void 0,R=String((l=nr.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=nr.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((p=nr.aiappdescription)!==null&&p!==void 0?p:"")!==String(h.appModuleAiDescription)}}catch{}let k=N;if(R){let xe=O?N:null,$n=xe?(0,ve.echoWrite)("appmoduleid",{"If-Match":xe}):{query:"",options:void 0},nr=await e.patch(`${C}${$n.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},$n.options);if(DU(nr))throw new Ae.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${v}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,ve.ensureSuccess)(nr,e.apiUrl(C)),k=(0,ve.readEtag)(nr)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},V=F||h.appModuleUniqueName||void 0,q=(0,ve.echoWrite)("sitemapid",{"If-Match":n}),ze=`/sitemaps(${b})`,Tt;try{Tt=(0,ve.ensureSuccess)(await e.patch(`${ze}${q.query}`,{...P},q.options),e.apiUrl(ze))}catch(xe){throw(0,Ae.withPartialTokens)(xe,{siblingEtags:{[v]:k}})}let Be=[...E.warnings];try{await Nw(e,v,E.components),await Dw(e,v,E.tables)}catch(xe){Be.push(`App '${v}': one or more components were not pinned (${xe.message}). Navigation may reference content not included in the app; re-push to retry.`)}let Qe={kind:"notRequested"},Z=k,ye=(f=(0,ve.readEtag)(Tt))!==null&&f!==void 0?f:await mf(e,b,P,V);if(h.published===!0){try{await(0,Aw.publishAppModule)(e,v),Qe={kind:"submitted"}}catch(xe){Qe={kind:"failed",error:xe},Be.push(`App '${v}': saved, but publishing failed (${xe.message}). The app remains unpublished; re-push to retry.`)}if(Qe.kind==="submitted"){Z=null;try{let xe=await e.get(`/appmodules(${v})?$select=appmoduleid`);xe.status>=200&&xe.status<300&&(Z=(0,ve.readEtag)(xe)),ye=(m=await mf(e,b,P,V))!==null&&m!==void 0?m:ye}catch{}}}return{id:v,etag:ye,siblingEtags:{[v]:Z},publish:Qe,...Be.length>0?{warnings:Be}:{}}},async delete(e,t){let r=(0,fe.normalizeGuid)(t,"id");await xw(e,r,await Rw(e,r))}}});var wf=y(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.deleteAppCascade=xa.collectGenPageIds=void 0;var IU=gu(),_U=te(),Af=ae(),TU=Jl();function Fw(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new TU.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new _U.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let a=[],o=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&a.push((0,Af.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&o(c)}};return o(i),a}xa.collectGenPageIds=Fw;async function PU(e,t,r){let n=(0,Af.normalizeGuid)(t,"appModuleId");(0,Af.normalizeGuid)(r,"appModuleIdUnique");let i=[],a=[],o=[];await(0,IU.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&o.push(...Fw(l))}),i.push({type:"app",id:n});let s=[...new Set(o)].map(l=>({type:"genPage",id:l}));return{success:a.length===0,deleted:i,failures:a,retained:s}}xa.deleteAppCascade=PU});var Lw={};pn(Lw,{Guid:()=>L});var L,We=T(()=>{"use strict";L=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var M,ht=T(()=>{"use strict";$e();M=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!_.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return _.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var kw={};pn(kw,{ScriptUtilities:()=>_});var _,$e=T(()=>{"use strict";We();ht();_=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return M.IsNullOrEmpty(t.ToString())?!0:L.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:M.IsTrue(n)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let r=new Set;return e.getAllUniqueTagNamesHelper(t,r),r}static getAllUniqueTagNamesHelper(t,r){if(t.nodeType===Node.ELEMENT_NODE&&(r.add(t.tagName),t.hasChildNodes()))for(let n=0;n<t.children.length;n++)this.getAllUniqueTagNamesHelper(t.children.item(n),r)}}});var vu,yu,Fi,bu,Ef,wu,Cf=T(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(vu||(vu={}));yu=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Fi=class extends yu{key;oldValue;newValue;constructor(t,r,n,i){super(vu.FormElementNodeChange,t),this.key=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},bu=class extends yu{property;oldValue;newValue;constructor(t,r,n,i){super(vu.FormElementAttributeChange,t),this.property=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},Ef=class{changeSet;reversedChangeSet;constructor(t){this.changeSet=t,this.changeSet&&(this.reversedChangeSet=this.changeSet.slice().reverse())}length(){return this.changeSet?this.changeSet.length:0}apply(){this.changeSet&&this.changeSet.length>0&&this.changeSet.forEach(t=>{t.apply()})}revert(){this.reversedChangeSet&&this.reversedChangeSet.length>0&&this.reversedChangeSet.forEach(t=>{t.revert()})}},wu=class{isTracking;_trackedChanges;_trackedChangeSets;constructor(t=!1){this.isTracking=t,this._trackedChanges=[],this._trackedChangeSets=[]}addChange(t){this.isTracking&&this._trackedChanges.push(t)}collectChanges(){let t=new Ef(this._trackedChanges.slice());return this._trackedChanges=[],t}pushChangeSet(t){this._trackedChangeSets.push(t)}popChangeSet(){if(this._trackedChangeSets?.length>0)return this._trackedChangeSets.pop()}getChangeSets(){return this._trackedChangeSets}}});var Mw={};pn(Mw,{ChartGridMode:()=>ur,ColumnLayoutWidths:()=>LU,ComponentCategory:()=>Eu,ComponentType:()=>Sf,ControlLayoutTypes:()=>Rf,DisplayConditionsInfo:()=>xU,ElementNames:()=>w,ElementProperties:()=>g,ElementType:()=>Df,EntityAttributeProperty:()=>If,EventType:()=>ps,FormActivationState:()=>Pf,FormCanvasServiceScope:()=>HU,FormDesignerSideBarTab:()=>Nf,FormPresentation:()=>_f,FormState:()=>Au,FormType:()=>je,HeaderDensityType:()=>ti,LookUpTable:()=>Qr,MORE_TAB_PREFIX:()=>MU,NavBarChildElementType:()=>Tf,PREVIEW_ID_HEADER_FLYOUT:()=>qU,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>GU,PREVIEW_ID_NAVIGATION_AREA:()=>UU,PREVIEW_ID_QUICKCREATE_ROOT:()=>WU,PREVIEW_ID_TAB:()=>zU,PREVIEW_ID_TAB_LIST:()=>VU,PREVIEW_ID_TAB_PANEL:()=>$U,PropertyModelKeys:()=>Ff,PropertyModelSectionKeys:()=>kU,RELATED_TAB_ID:()=>Lf,RELATED_TAB_PREFIX:()=>BU,SectionDefaultProperties:()=>FU,SectionLayoutTypes:()=>Te,TabContentType:()=>Of,TabDefaultProperties:()=>ri,TabLayoutTypes:()=>_e,TelemetryPropertyNames:()=>jU,UnboundControlPropertyKeys:()=>xf,compositeAddressFields:()=>OU,compositeFieldNames:()=>Qt,compositeFields:()=>RU});var je,Sf,Nf,w,g,Df,Qt,RU,OU,If,Qr,Au,ti,_f,xU,Tf,Pf,_e,FU,ri,Te,Rf,Of,LU,xf,Ff,kU,ps,ur,Lf,MU,BU,UU,$U,qU,VU,GU,zU,WU,jU,Eu,HU,ee=T(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(je||(je={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Sf||(Sf={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Nf||(Nf={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(w||(w={}));g={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(Df||(Df={}));Qt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},RU=[Qt.fullname,Qt.yomifullname,Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto],OU=[Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(If||(If={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Qr||(Qr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Au||(Au={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ti||(ti={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(_f||(_f={}));xU={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Tf||(Tf={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(Pf||(Pf={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(_e||(_e={}));FU={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},ri={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(Te||(Te={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(Rf||(Rf={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Of||(Of={}));LU={ONE_COLUMN:"100",TWO_COLUMN:"50",THREE_COLUMN:"33.33",FOUR_COLUMN:"25"};(function(e){e.minValue="MinValue",e.maxValue="MaxValue",e.precision="Precision",e.maxLength="MaxLength",e.entityLogicalName="EntityLogicalName",e.defaultViewId="DefaultViewId",e.optionSetDefaultValue="DefaultValue",e.optionSetId="OptionSetId"})(xf||(xf={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(Ff||(Ff={}));kU={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(ps||(ps={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(ur||(ur={}));Lf="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",MU="more_tab_",BU="related_tab_",UU="preview_id_navigation_area",$U="tab-section",qU="headerFieldsFlyout",VU="tablist",GU="header_overflowButton",zU="tab",WU="quickCreateRoot",jU={defaultVisibility:"Default visibility"};(function(e){e.input="input",e.layout="layout",e.grid="grid",e.relatedData="relatedData",e.display="display",e.powerbi="powerbi",e.artificialIntelligence="artificialIntelligence",e.media="media",e.collaboration="collaboration",e.more="more",e.test="test",e.popular="popular"})(Eu||(Eu={}));HU="CellCanvasServiceScope"});var Bw={};pn(Bw,{Attribute:()=>Cu,FormElementNode:()=>H});var Cu,H,tt=T(()=>{"use strict";$e();ht();Cf();ee();We();Cu=class{key;value;constructor(t,r){this.key=t,this.value=r}},H=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${L.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(w.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Cu(t,r))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let r=this.properties.findIndex(n=>n.key===t);r>-1&&this.properties.splice(r,1)})}trackPropertyCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.properties.slice();t(),r.addChange(new Fi(this,"properties",n,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.childrenNodes.slice();t(),r.addChange(new Fi(this,"childrenNodes",n,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.parentNode;if(t(),n===this.parentNode)return;r.addChange(new Fi(this,"parentNode",n,this.parentNode))}else t()}trackAttributeValueChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=t.value;if(i===r)return;t.value=r,n.addChange(new bu(this,t,i,r))}else t.value=r}trackObjectPropertyChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=this[t];if(i===r)return;this[t]=r,n.addChange(new Fi(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){_.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(_.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:M.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=_.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),a=null;i.length===0?(a=new e(t,this),this.addChild(a)):a=i[0],a.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case w.formCell:let t=this.getAncestor(w.formSection);return t||(t=this.getAncestor(w.formHeader),t)||(t=this.getAncestor(w.formFooter),t)?t:null;case w.formSection:return this.getAncestor(w.formTab);case w.formTab:return this.getAncestor(w.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(w.form);return t?t.changeTracker():null}}});var Uw={};pn(Uw,{ControlClassId:()=>I,ControlNamePrefixes:()=>Su,getControlDisplayNames:()=>KU});function KU(e){return{[I.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[I.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[I.ACIControl]:e("controls.controlNames.aci"),[I.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[I.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[I.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[I.ArticleContentControl]:e("controls.controlNames.articleContent"),[I.BooleanControl]:e("controls.controlNames.twoOption"),[I.ButtonControl]:e("controls.controlNames.button"),[I.CheckboxControl]:e("controls.controlNames.checkbox"),[I.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[I.ConnectionControl]:e("controls.controlNames.connection"),[I.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[I.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[I.DashboardControl]:e("controls.controlNames.dashboard"),[I.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[I.EditFilterControl]:e("controls.controlNames.editFilter"),[I.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[I.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[I.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[I.KBViewerControl]:e("controls.controlNames.kbViewer"),[I.LabelControl]:e("controls.controlNames.label"),[I.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[I.MapLinkControl]:e("controls.controlNames.mapLink"),[I.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[I.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[I.PowerBIControl]:e("controls.controlNames.powerBI"),[I.ProcessControl]:e("controls.controlNames.process"),[I.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[I.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[I.ReportControl]:e("controls.controlNames.report"),[I.StreamsControl]:e("controls.controlNames.streams"),[I.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[I.CurrencyControl]:e("controls.controlNames.currency"),[I.DateTimeControl]:e("controls.controlNames.dateAndTime"),[I.DecimalControl]:e("controls.controlNames.decimal"),[I.DurationControl]:e("controls.controlNames.duration"),[I.EmailAddressControl]:e("controls.controlNames.email"),[I.FileControl]:e("controls.controlNames.file"),[I.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[I.IframeControl]:e("controls.controlNames.iframe"),[I.ImageControl]:e("controls.controlNames.image"),[I.LookupControl]:e("controls.controlNames.lookup"),[I.MapsControl]:e("controls.controlNames.maps"),[I.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[I.ChoiceControl]:e("controls.controlNames.choice"),[I.QuickViewControl]:e("controls.controlNames.quickView"),[I.QuickFormControl]:e("controls.controlNames.quickForm"),[I.CustomControl]:e("controls.controlNames.customControl"),[I.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[I.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[I.SubgridControl]:e("controls.controlNames.subgrid"),[I.TextAreaControl]:e("controls.controlNames.textArea"),[I.TextboxControl]:e("controls.controlNames.textBox"),[I.TickerControl]:e("controls.controlNames.ticker"),[I.UrlControl]:e("controls.controlNames.url"),[I.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[I.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[I.IntegerControl]:e("controls.controlNames.integer"),[I.TimerControl]:e("controls.controlNames.timer"),[I.TimelineControl]:e("controls.controlNames.timeline"),[I.EmailBodyControl]:e("controls.controlNames.emailBody"),[I.PartyListControl]:e("controls.controlNames.partyList"),[I.TimezoneControl]:e("controls.controlNames.timezone"),[I.LanguageControl]:e("controls.controlNames.language"),[I.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[I.ChoicesControl]:e("controls.controlNames.choices"),[I.RegardingControl]:e("controls.controlNames.regarding"),[I.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[I.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[I.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[I.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[I.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[I.KBEditorControl]:e("controls.controlNames.KBEditor"),[I.LinkControl]:e("controls.controlNames.link")}}var I,Su,Li=T(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(I||(I={}));Su={[I.WebResourceHTMLControl]:"WebResource",[I.WebResourceImageControl]:"WebResource",[I.IframeControl]:"IFRAME",[I.SearchWidgetControl]:"Search widget",[I.SubgridControl]:"Subgrid",[I.TimelineControl]:"Timeline",[I.QuickViewControl]:"QuickviewControl"}});var ki=y((bQ,qw)=>{var fs=new Proxy(function(){return fs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:fs},apply:function(){return fs},construct:function(){return{}}}),$w=function(){return fs};Object.setPrototypeOf($w,fs);qw.exports=$w});var Et,Cn,Vw,Gw,Fa=T(()=>{"use strict";Et="cds-designer-models",Cn="FormCustomControl",Vw="FormCell",Gw="Form"});var La,Ct,ms=T(()=>{"use strict";La=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,r){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(r),!0)}upsert(t,r){this.update(t,r)||this.add(t,r)}sortedUpsert(t,r){if(!this.update(t,r)){let n=0;for(;n<this.keys.length&&this.keys[n]<t;)n++;this.keys.splice(n,0,t),this.values.splice(n,0,r)}}clear(){this.keys=[],this.values=[]}containsKey(t){return this.keys.indexOf(t)!==-1}containsValue(t){return this.values.indexOf(t)!==-1}count(){return this.keys.length}getValue(t){let r=this.keys.indexOf(t);return r!==-1?this.values[r]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let r=this.keys.indexOf(t);return r!==-1?(this.keys.splice(r,1),this.values.splice(r,1),!0):!1}update(t,r){let n=this.keys.indexOf(t);return n!==-1?(this.values[n]=r,!0):!1}},Ct=class{data={};add(t,r){return this.containsKey(t)?!1:(this.data[t]=r,!0)}upsert(t,r){this.data[t]=r}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let r in this.data)if(this.data[r]===t)return!0;return!1}count(){return Object.keys(this.data).length}getValue(t){return this.containsKey(t)?this.data[t]:!1}getKeys(){return Object.keys(this.data)}getValues(){let t=[];for(let r in this.data)t.push(this.data[r]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,r){return this.containsKey(t)?(this.data[t]=r,!0):!1}getInternalObject(){return this.data}}});var Mi,kf=T(()=>{"use strict";ms();ee();Mi=class e{static lockedFieldCount=new Ct;static dependencyFieldCount=new Ct;static getNecessaryLookUpTable(t){switch(t){case Qr.DependencyFieldTable:return e.dependencyFieldCount;case Qr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Qr.DependencyFieldTable:e.dependencyFieldCount=new Ct;case Qr.LockedFieldTable:e.lockedFieldCount=new Ct}}}});var Nu,zw=T(()=>{"use strict";We();$e();ee();tt();Nu=class extends H{constructor(t){super(w.controlDescription,t)}get forControl(){let t=this.getProperty(g.ForControl);return _.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set forControl(t){this.setProperty(g.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(w.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!_.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!_.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)_.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});var jw,Hw,St,x,Ww,ni,Bi,ka,Mf,Bf,Ma=T(()=>{"use strict";jw={Name:"Name",Value:"Value",Type:"Type",TypeGroup:"TypeGroup",Usage:"Usage",Static:"Static",Primary:"Primary",Columns:"Columns",EnableViewPicker:"EnableViewPicker",EntityName:"EntityName",FilteredViewIds:"FilteredViewIds",ReferencingName:"ReferencingName",RelationshipName:"RelationshipName",RelationshipType:"RelationshipType",TargetEntityType:"TargetEntityType",ViewId:"ViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DefaultViewId:"DefaultViewId",BindAttribute:"BindAttribute",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",QuickForms:"QuickForms",EntityNameKey:"EntityNameKey",CardFormType:"Form.Card",CardFormId:"CardFormId",Hidden:"Hidden",Required:"Required",DefaultValue:"DefaultValue"},Hw={GroupDefinition:"GroupDefinition"},St={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(x||(x={}));(function(e){e.BooleanType="CC_FlipLabel_Name",e.DateTimeType="CC_TextBox_Name",e.DecimalType="CC_TextBox_Name",e.DoubleType="CC_TextBox_Name",e.IntegerType="CC_TextBox_Name",e.LookupType="CC_TextBox_Name",e.MemoType="CC_TextArea_Name",e.MoneyType="CC_TextBox_Name",e.OptionSetType="CC_OptionSet_Name",e.StringType="CC_TextBox_Name",e.GridType="CC_ReadOnlyGrid_Name",e.UnboundCustomControlType="CC_UnboundCustomControl_Name"})(Ww||(Ww={}));(function(e){e.ArcKnobControl="MscrmControls.Knob.ArcKnobControl",e.CardFeedNameControl="MscrmControls.CardFeedContainer.CardFeedContainer",e.CheckboxControl="MscrmControls.FieldControls.CheckboxControl",e.DateTimeControl="MscrmControls.FieldControls.DateTimeControl",e.DurationControl="MscrmControls.FieldControls.DurationControl",e.EditableGridControl="MscrmControls.Grid.GridControl",e.EmailEngagementActionsControl="MscrmControls.EmailEngagement.EmailEngagementActionsControl",e.FormComponent="MscrmControls.ModelForm.ModelFormControl",e.LanguageCodeControl="MscrmControls.FieldControls.LanguagePickerControl",e.LinearSliderControl="MscrmControls.Slider.LinearSliderControl",e.MultiSelectOptionSetControl="MscrmControls.MultiSelectPicklist.UpdMSPicklistControl",e.OptionSetControl="MscrmControls.OptionSet.OptionSetControl",e.PowerBIPCFControl="MscrmControls.PowerBIPCFControl",e.PredictiveScoringWidget="MscrmControls.Sales.PredictiveScoringWidget.PredictiveScoringWidget",e.ReadonlyGrid="MscrmControls.Grid.ReadOnlyGrid",e.SimilarCasesGrid="MscrmControls.Containers.SimilarCasesGridControl",e.StarRatingControl="MscrmControls.Rating.StarRatingControl",e.TimeZoneControl="MscrmControls.FieldControls.TimeZonePickListControl",e.ModelFormControl="MscrmControls.ModelForm.ModelFormControl",e.AutoCompleteControl="MscrmControls.AutoComplete.AutoCompleteControl",e.CanvasAppControl="MscrmControls.Canvas.CanvasControl",e.PowerAppsOneGrid="Microsoft.PowerApps.PowerAppsOneGrid"})(ni||(ni={}));(function(e){e[e.Read=0]="Read",e[e.Edit=1]="Edit",e[e.Both=2]="Both",e[e.Container=3]="Container",e[e.Unknown=4]="Unknown"})(Bi||(Bi={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ka||(ka={}));Mf=[x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.LookupSimple],Bf=[x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.FP,x.Decimal]});function Sn(){return Xr||(Xr=window._makerConfig,Xr&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Xr={...Xr,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Xr?.region==="prod"&&(Xr={endpoints:{eu:{ch:{graphql:"https://graph-make.ch-cm001.gateway.prod.cm.powerapps.com/"},de:{graphql:"https://graph-make.de-cm001.gateway.prod.cm.powerapps.com/"},fr:{graphql:"https://graph-make.fr-cm001.gateway.prod.cm.powerapps.com/"},no:{graphql:"https://graph-make.no-cm001.gateway.prod.cm.powerapps.com/"},default:{graphql:"https://graph-make.eu-cm001.gateway.prod.cm.powerapps.com/"}}},...Xr}),Xr||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Xr,Du=T(()=>{"use strict";});function Kw(e,t,r){if(!e)return Iu.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Iu.add("")),!1;if(e){if(e=e.toLowerCase(),Iu.has(e))return!1;if(!(e in t))return window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoNonExistent",eventInfo:{missinggeo:e,parent:r}}),Iu.add(e),!1}return!0}function JU(e){return Kw(e,Uf,"Location dictionary")?Uf[e.toLowerCase()]:"us"}function QU(){let e=Sn().location.toLowerCase();return Kw(e,Uf,"Current location dictionary")?e:"us"}var Iu,Uf,FQ,Jw=T(()=>{"use strict";Du();Iu=new Set,Uf={cae:"ae",nae:"ae",eas:"as",seas:"as",eau:"au",seau:"au",sbr:"br",cca:"ca",eca:"ca",nch:"ch",wch:"ch",nde:"de",wcde:"de",neu:"eu",weu:"eu",cfr:"fr",sfr:"fr",cin:"in",sin:"in",ejp:"jp",wjp:"jp",suk:"uk",wuk:"uk",eus:"us",wus:"us",cus:"us",ude:"us",udc:"us",ugtx:"us",ugva:"us",eus2:"us",wus2:"us",nza:"za",wza:"za",cne2:"cn",cnn2:"cn",skr:"kr",ckr:"kr",eno:"no",wno:"no",wrx:"us",erx:"us",wex:"us",eex:"us",unitedstates:"us",europe:"eu",asia:"as",australia:"au",japan:"jp",canada:"ca",india:"in",italy:"it",unitedstatesfirstrelease:"us",unitedkingdom:"uk",southamerica:"br",france:"fr",unitedarabemirates:"ae",germany:"de",sweden:"se",switzerland:"ch",korea:"kr",norway:"no",usgov:"us",usgovhigh:"us",usdod:"us",china:"cn",usnat:"us",ussec:"us",southafrica:"za",singapore:"sg",newzealand:"nz",poland:"pl",qatar:"qa",as:"as",au:"au",ca:"ca",in:"in",jp:"jp",kr:"kr",nz:"nz",ae:"ae",qa:"qa",us:"us",uk:"uk",eu:"eu",de:"de",ch:"ch",no:"no",fr:"fr",se:"se",it:"it",pl:"pl",be:"eu",bel:"eu",gr:"eu",grc:"eu",lt:"eu",ltu:"eu",pt:"eu",prt:"eu",bg:"eu",bgr:"eu",es:"eu",esp:"eu",lu:"eu",lux:"eu",ro:"eu",rou:"eu",cz:"eu",cze:"eu",hu:"eu",hun:"eu",si:"eu",svn:"eu",dk:"eu",dnk:"eu",hr:"eu",hrv:"eu",mt:"eu",mlt:"eu",sk:"eu",svk:"eu",nit:"it",nl:"eu",nld:"eu",fi:"eu",fin:"eu",ee:"eu",est:"eu",cy:"eu",cyp:"eu",at:"eu",aut:"eu",swe:"se",cse:"se",ie:"eu",irl:"eu",lv:"eu",lva:"eu",cpl:"pl",nnz:"nz",cqa:"qa",sg:"sg",br:"br",za:"za",sa:"za"};FQ=JU(QU())});var G,kQ,Qw=T(()=>{"use strict";G={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},kQ={[G.USWest]:{geoName:"us",regionShortName:"wus"},[G.USCentral]:{geoName:"us",regionShortName:"cus"},[G.USEast]:{geoName:"us",regionShortName:"eus"},[G.USEast2]:{geoName:"us",regionShortName:"eus2"},[G.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[G.USWest2]:{geoName:"us",regionShortName:"wus2"},[G.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[G.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[G.UKSouth]:{geoName:"uk",regionShortName:"suk"},[G.UKWest]:{geoName:"uk",regionShortName:"wuk"},[G.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[G.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[G.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[G.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[G.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[G.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[G.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[G.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[G.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[G.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[G.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[G.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[G.AsiaEast]:{geoName:"as",regionShortName:"eas"},[G.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[G.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[G.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[G.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[G.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[G.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[G.UAENorth]:{geoName:"ae",regionShortName:"nae"},[G.UAECentral]:{geoName:"ae",regionShortName:"cae"},[G.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[G.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[G.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[G.NorwayEast]:{geoName:"no",regionShortName:"eno"},[G.NorwayWest]:{geoName:"no",regionShortName:"wno"},[G.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[G.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[G.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[G.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[G.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[G.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[G.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[G.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[G.GovernmentUSDodCentral]:{regionShortName:"udc"},[G.GovernmentUSDodEast]:{regionShortName:"ude"},[G.ChinaEast]:{regionShortName:"cne"},[G.ChinaEast2]:{regionShortName:"cne2"},[G.ChinaEast3]:{regionShortName:"cne3"},[G.ChinaNorth]:{regionShortName:"cnn"},[G.ChinaNorth2]:{regionShortName:"cnn2"},[G.ChinaNorth3]:{regionShortName:"cnn3"},[G.UssecEast]:{geoName:"us",regionShortName:"erx"},[G.UssecWest]:{geoName:"us",regionShortName:"wrx"},[G.UsnatEast]:{geoName:"us",regionShortName:"eex"},[G.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var Xw=T(()=>{"use strict";Du();});var hs=T(()=>{"use strict";Du();Jw();Qw();Xw();});function gs(e,t){return Yw?Yw.isOverridden(e,t):{overridden:!1}}var Yw,vs=T(()=>{"use strict";});var $f=T(()=>{"use strict";hs();vs();});function XU(e,t){let{region:r}=Sn();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=gs(e.packageName,t);if(s.overridden)return typeof s.value=="string"?YU(s.value):s.value}let a=n.values,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return a[r]!==void 0?a[r]:o&&a[o]!==void 0?a[o]:a.default}}function YU(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function ZU(e){let t=e.packageName;if(_u.has(t)){let r=`settings has already been created for this package ${t}`;throw console.error(r),new Error(r)}if(Object.keys(e.settings).some(r=>Vf(t,r))){let r=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.settings).forEach(r=>{if(Object.keys(e.settings[r].values).filter(i=>i!=="default").some(i=>!Pu(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function ys(e){ZU(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:XU(e,r)}}),_u.set(e.packageName,e),Object.defineProperties({},t)}function qf(e,t){return _u.has(e)?!!_u.get(e).settings[t]:!1}var _u,Tu=T(()=>{"use strict";hs();vs();Gf();bs();_u=new Map});function Zw(e,t){let{region:r}=Sn();return()=>{let n=gs(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:a&&i[a]!==void 0?!!i[a]:!1}}function e$(e){let t=e.packageName;if(Ru.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>qf(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!Pu(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function zf(e){e$(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:Zw(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,a)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:a})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(a=>{i[a.toString()]={enumerable:!0,configurable:!0,get:Zw(e,a.toString())}}),Object.defineProperties(r,i),n.clear()}},Ru.set(e.packageName,e),Object.defineProperties(r,t)}function Vf(e,t){return Ru.has(e)?!!Ru.get(e).features[t]:!1}var Ru,Gf=T(()=>{"use strict";hs();bs();vs();Tu();Ru=new Map});var tA=y((sX,eA)=>{"use strict";eA.exports=function(t,r){if(r=r.split(":")[0],t=+t,!t)return!1;switch(r){case"http":case"ws":return t!==80;case"https":case"wss":return t!==443;case"ftp":return t!==21;case"gopher":return t!==70;case"file":return!1}return t!==0}});var iA=y(Wf=>{"use strict";var t$=Object.prototype.hasOwnProperty,r$;function rA(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function nA(e){try{return encodeURIComponent(e)}catch{return null}}function n$(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=rA(n[1]),a=rA(n[2]);i===null||a===null||i in r||(r[i]=a)}return r}function i$(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(t$.call(e,i)){if(n=e[i],!n&&(n===null||n===r$||isNaN(n))&&(n=""),i=nA(i),n=nA(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Wf.stringify=i$;Wf.parse=n$});var Kf=y((uX,cA)=>{"use strict";var oA=tA(),Ou=iA(),sA=/[\n\r\t]/g,a$=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o$=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,s$=/^[a-zA-Z]:/,l$=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Hf(e){return(e||"").toString().replace(l$,"")}var jf=[["#","hash"],["?","query"],function(t,r){return Yr(r.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],aA={hash:1,query:1};function lA(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,a;if(e.protocol==="blob:")n=new Zr(unescape(e.pathname),{});else if(i==="string"){n=new Zr(e,{});for(a in aA)delete n[a]}else if(i==="object"){for(a in e)a in aA||(n[a]=e[a]);n.slashes===void 0&&(n.slashes=a$.test(e.href))}return n}function Yr(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function uA(e,t){e=Hf(e),e=e.replace(sA,""),t=t||{};var r=o$.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],a=!!r[3],o=0,s;return i?a?(s=r[2]+r[3]+r[4],o=r[2].length+r[3].length):(s=r[2]+r[4],o=r[2].length):a?(s=r[3]+r[4],o=r[3].length):s=r[4],n==="file:"?o>=2&&(s=s.slice(2)):Yr(n)?s=r[4]:n?i&&(s=s.slice(2)):o>=2&&Yr(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Yr(n),slashesCount:o,rest:s}}function u$(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],a=!1,o=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),o++):o&&(n===0&&(a=!0),r.splice(n,1),o--);return a&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function Zr(e,t,r){if(e=Hf(e),e=e.replace(sA,""),!(this instanceof Zr))return new Zr(e,t,r);var n,i,a,o,s,l,u=jf.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Ou.parse),t=lA(t),i=uA(e||"",t),n=!i.protocol&&!i.slashes,d.slashes=i.slashes||n&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||s$.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Yr(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);p<u.length;p++){if(o=u[p],typeof o=="function"){e=o(e,d);continue}a=o[0],l=o[1],a!==a?d[l]=e:typeof a=="string"?(s=a==="@"?e.lastIndexOf(a):e.indexOf(a),~s&&(typeof o[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+o[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=a.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&o[3]&&t[l]||"",o[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=u$(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Yr(d.protocol)&&(d.pathname="/"+d.pathname),oA(d.port,d.protocol)||(d.host=d.hostname,d.port=""),d.username=d.password="",d.auth&&(s=d.auth.indexOf(":"),~s?(d.username=d.auth.slice(0,s),d.username=encodeURIComponent(decodeURIComponent(d.username)),d.password=d.auth.slice(s+1),d.password=encodeURIComponent(decodeURIComponent(d.password))):d.username=encodeURIComponent(decodeURIComponent(d.auth)),d.auth=d.password?d.username+":"+d.password:d.username),d.origin=d.protocol!=="file:"&&Yr(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function c$(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Ou.parse)(t)),n[e]=t;break;case"port":n[e]=t,oA(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var a=t.indexOf(":");~a?(n.username=t.slice(0,a),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(a+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var o=0;o<jf.length;o++){var s=jf[o];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&Yr(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function d$(e){(!e||typeof e!="function")&&(e=Ou.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var a=i+(r.protocol&&r.slashes||Yr(r.protocol)?"//":"");return r.username?(a+=r.username,r.password&&(a+=":"+r.password),a+="@"):r.password?(a+=":"+r.password,a+="@"):r.protocol!=="file:"&&Yr(r.protocol)&&!n&&r.pathname!=="/"&&(a+="@"),n[n.length-1]===":"&&(n+=":"),a+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(a+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(a+=r.hash),a}Zr.prototype={set:c$,toString:d$};Zr.extractProtocol=uA;Zr.location=lA;Zr.trimLeft=Hf;Zr.qs=Ou;cA.exports=Zr});var p$,dA=T(()=>{"use strict";p$=ce(Kf());});function Jf(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var xu=T(()=>{"use strict";});var Qf,Xf,Yf=T(()=>{"use strict";xu();Qf=class{features=new Map;register(t,r){let n=Jf(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},Xf=new Qf});var Zf=T(()=>{"use strict";});function Pu(e){return f$.has(e)}var f$,bs=T(()=>{"use strict";$f();Gf();Tu();vs();$f();dA();Yf();xu();Zf();f$=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var m$,pA=T(()=>{"use strict";bs();m$=ys({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var Fu,U,z,Ui,Ba,Lu,fA,mA,em,ws=T(()=>{"use strict";ms();Fu=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return em.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})(U||(U={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(z||(z={}));Ui=class extends Fu{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ba=class e extends Fu{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?Lu.Persistent:parseInt(Lu[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(Lu||(Lu={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(fA||(fA={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(mA||(mA={}));em=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new La;return t.add(U.TwoOptions,"SystemCustomization.type.bit.label"),t.add(U.Customer,"SystemCustomization.type.customer.label"),t.add(U.CustomerType,"SystemCustomization.type.customer.label"),t.add(U.DateTime,"SystemCustomization.type.datetime.label"),t.add(U.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(U.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(U.WholeNumber,"SystemCustomization.type.int.label"),t.add(U.LookupType,"SystemCustomization.type.lookup.label"),t.add(U.Lookup,"SystemCustomization.type.lookup.label"),t.add(U.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(U.Currency,"SystemCustomization.type.money.label"),t.add(U.Owner,"SystemCustomization.type.owner.label"),t.add(U.OwnerType,"SystemCustomization.type.owner.label"),t.add(U.PartyList,"SystemCustomization.type.partylist.label"),t.add(U.PartyListType,"SystemCustomization.type.partylist.label"),t.add(U.OptionSet,"SystemCustomization.type.picklist.label"),t.add(U.State,"SystemCustomization.type.state.label"),t.add(U.Status,"SystemCustomization.type.status.label"),t.add(U.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(U.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(U.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(U.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(U.VirtualType,"SystemCustomization.type.virtual.label"),t.add(U.BigInt,"SystemCustomization.type.bigint.label"),t.add(U.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(U.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(U.Image,"SystemCustomization.type.image.label"),t.add(U.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(U.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(U.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(U.Subject,"SystemCustomization.type.subject.label"),t.add(z.Email,"SystemCustomization.String.Format.email"),t.add(z.Text,"SystemCustomization.String.Format.text"),t.add(z.TextArea,"SystemCustomization.String.Format.textarea"),t.add(z.Url,"SystemCustomization.String.Format.url"),t.add(z.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(z.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(z.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(z.Phone,"SystemCustomization.String.Format.phone"),t.add(z.None,"SystemCustomization.Integer.Format."),t.add(z.Duration,"SystemCustomization.Integer.Format.duration"),t.add(z.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(z.Language,"SystemCustomization.Integer.Format.language"),t.add(z.Locale,"SystemCustomization.Integer.Format.language"),t.add(z.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(z.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(z.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ba.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ba.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ba.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ba.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var yA,rm,Ua,$i,tm,ku,$a,Nn,De,hA,gA,vA,Ir=T(()=>{"use strict";yA={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},rm={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(Ua||(Ua={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})($i||($i={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(tm||(tm={}));ku=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})($a||($a={}));Nn=class{static StartTag="<"},De={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:$i.Left,labelPosition:$a.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(hA||(hA={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(gA||(gA={}));(function(e){e.IsHeader="IsHeader",e.IsFooter="IsFooter",e.ContainedInHeader="ContainedInHeader",e.ContainedInFooter="ContainedInFooter",e.NoElementFound="NoElementFound",e.NoTarget="NoTarget",e.CannotAddControlToHeader="CannotAddControlToHeader",e.CannotAddControlToFooter="CannotAddControlToFooter"})(vA||(vA={}))});var nm,bA=T(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(nm||(nm={}))});var EA,h$,wA,sY,lY,As,AA,uY,cY,CA=T(()=>{"use strict";EA=ce(ki());$e();Fa();pA();ws();Ir();Ma();ee();h$=ce(Ai());bA();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(wA||(wA={}));sY={Read:Bi.Read,Edit:Bi.Edit,Both:Bi.Both,Container:Bi.Container},lY={input:ka.Input,bound:ka.Bound,output:ka.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(As||(As={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(AA||(AA={}));uY=new Set([x.Currency,x.Decimal,x.FP,x.Multiple,x.SingleLineEmail,x.SingleLinePhone,x.SingleLineText,x.SingleLineTextArea,x.SingleLineURL,x.SingleLineTickerSymbol,x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.Enum,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.TwoOptions,x.Boolean,x.PowerBIReport,x.DateAndTimeDateAndTime,x.DateAndTimeDateOnly,x.OptionSet,x.MultiSelectOptionSet,x.CardForm]),cY={numbers:[x.WholeNone,x.FP,x.Decimal,x.Currency],text:[x.SingleLineText,x.SingleLineTextArea,x.Multiple],lookup:[x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding],dates:[x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime],allFields:[x.TwoOptions,x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime,x.FP,x.Decimal,x.WholeNone,x.WholeDuration,x.WholeTimeZone,x.WholeLanguage,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.Multiple,x.OptionSet,x.SingleLineText,x.SingleLineTextArea,x.SingleLineEmail,x.SingleLineURL,x.SingleLineTickerSymbol,x.SingleLinePhone]}});var _r,Mu,SA=T(()=>{"use strict";_r=ce(ki());We();$e();ht();Fa();Ma();CA();ws();ee();tt();Ir();Mu=class extends H{constructor(t){super(w.customControl,t)}customControlId;get id(){let t=this.getProperty(g.id);return _.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let a=i.getNodeName();t.get(a)?t.get(a).push(i):t.set(a,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(St.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(o=>o.getNodeName()===t):null,a=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(a)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===St.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===St.name)?.value,a={Name:i,Type:x.Grid,Columns:[]},l=this.getParameters().get(St.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());a[c]=d}}return a}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let a of i)if(a.key===g.static&&a.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(g.Name)}get formFactor(){return this.getProperty(g.formFactor)}set formFactor(t){this.setProperty(g.formFactor,t)}async toJSON(t){if(this.id)return null;let r=await this.parametersToJSON(t),n=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(n)?-1:n,Name:this.name,Version:null,Parameters:r,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(Nn.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,a=this.getParameters();for(let[o,s]of a)if(this.isDataSet(o))for(let l of a.get(o)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),p=await this.parameterJSON(o,u,d,t);r.push({Name:c,Value:p})}else if(this.isGroups(s))r.push({Name:o,Value:{Type:Hw.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(o).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===As.dataset?a.get(St.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:x.Grid}}):c.propertyType===As.property&&(a.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(o),c=await this.parameterJSON(o,l,u,t);if(c)r.push({Name:o,Value:c});else{(0,_r.trackInfoTrace)(Et,{eventName:`${Cn}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${o} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let a=n,o=r.find(s=>s.key===St.name)?.value;if(a)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${o}`);(0,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let a=n,o=r&&r.find(l=>l.key===g.Type),s=a&&!a.ofTypeGroup.every(l=>!Mf.includes(l));if(this.isLookupType(o?.value)||this.isLookupType(a?.ofType)||s)if(a){let l=a.usage,u=this.getParameterIsStatic(t),c=a.isPrimary;if(this.name===ni.FormComponent){let d=this.getFormComponentValueByParameterName(g.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(jw.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(g.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(g.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(g.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(g.DependentAttributeType),AllowFilterOff:M.IsStrictTrue(this.getFormComponentValueByParameterName(g.AllowFilterOff)),DisableQuickFind:M.IsStrictTrue(this.getFormComponentValueByParameterName(g.DisableQuickFind)),EnableViewPicker:!M.IsStrictTrue(this.getFormComponentValueByParameterName(g.DisableViewPicker))}}return{Name:t,Usage:l,Static:u,Primary:c,Value:this.getParameterValue(t)}}else{let l=new Error(`No lookup manifest info for ${t}`);(0,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(a){let l=a.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=a.isPrimary;if(o){let f=o.value;return{Type:f,Static:u,Usage:l,Value:this.isNumberTypeProperty(a,f)&&Number(c)?Number(c):c,Primary:d}}if(a.ofType)return{Type:a.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(a.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let p=new Error(`No property type info for ${t}`);(0,_r.trackErrorTrace)(Et,{eventName:`${Cn}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,_r.trackWarningTrace)(Et,{eventName:`${Cn}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case U.Customer:return x.LookupCustomer;case U.Owner:return x.LookupOwner;case U.PartyList:return x.LookupPartyList;default:return n===z.Regarding?x.LookupRegarding:x.LookupSimple}}isLookupType(t){return Mf.includes(t)}isNumberTypeProperty(t,r){return Bf.includes(r)||t.ofTypeGroup.some(n=>Bf.includes(n))}isDataSet(t){return St.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var j,im=T(()=>{"use strict";j=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var $,qa,He,Bu=T(()=>{"use strict";We();ms();$e();ht();ws();Li();im();Ir();$=class{static get TextBoxControl(){return"4273EDBD-AC1D-40d3-9FB2-095C621B552D"}static get TickerControl(){return"1E1FC551-F7A8-43af-AC34-A8DC35C7B6D4"}static get UrlControl(){return"71716B6C-711E-476c-8AB8-5D11542BFB47"}static get PhoneNumberControl(){return"8C10015A-B339-4982-9474-A95FE05631A5"}static get EmailAddressControl(){return"ADA2203E-B4CD-49be-9DDF-234642B43B52"}static get RadioControl(){return"67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"}static get LookupControl(){return"270BD3DB-D9AF-4782-9025-509E298DEC0A"}static get DateTimeControl(){return"5B773807-9FB2-42db-97C3-7A91EFF8ADFF"}static get IntegerControl(){return"C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F"}static get MoneyControl(){return"533B9E00-756B-4312-95A0-DC888637AC78"}static get FloatControl(){return"0D2C745A-E5A8-4c8f-BA63-C6D3BB604660"}static get DecimalControl(){return"C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E"}static get TextAreaControl(){return"E0DECE4B-6FC8-4a8f-A065-082708572369"}static get PicklistControl(){return"3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"}static get HiddenInputControl(){return"5546E6CD-394C-4BEE-94A8-4425E17EF6C6"}static get GridControl(){return"E7A81278-8635-4D9E-8D4D-59480B391C5B"}static get CheckBoxControl(){return"B0C6723A-8503-4fd7-BB28-C8A06AC933C2"}static get IframeControl(){return"FD2A7985-3187-444e-908D-6624B21F69C0"}static get SocialInsightControl(){return"86B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get OrgInsightsControl(){return"76B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get DurationControl(){return"AA987274-CE4E-4271-A803-66164311A958"}static get RegardingControl(){return"F3015350-44A2-4aa0-97B5-00166532B5E9"}static get PartyListControl(){return"CBFB742C-14E7-4a17-96BB-1A13F7F64AA2"}static get TimeLineControl(){return"06375649-c143-495e-a496-c962e5b4488e"}static get TimeLineControlUC(){return"06375649-C143-495E-A496-C962E5B4488E"}static get TimeZonePicklistControl(){return"7C624A0B-F59E-493d-9583-638D34759266"}static get LanguagePickerControl(){return"671A9387-CA5A-4d1e-8AB7-06E39DDCF6B5"}static get AccessTeamTablePickerControl(){return"3F4E2A56-F102-4B4D-AB9C-F1574CA5BFDA"}static get KBViewerControl(){return"A62B6FA9-169E-406C-B1AA-EAB828CB6026"}static get PicklistStatusControl(){return"5D68B988-0661-4db2-BC3E-17598AD3BE6C"}static get EmailBodyControl(){return"6F3FB987-393B-4d2d-859F-9D0F0349B6AD"}static get PicklistLookupControl(){return"2305E33A-BAD3-4022-9E15-1856CF218333"}static get RelationshipRolePicklistControl(){return"5F986642-5961-4D9F-AB5E-643D71E231E9"}static get RelatedInformationControl(){return"163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8"}static get CoverPagePicklistControl(){return"4168A05C-D857-46AF-8457-5BB47EB04EA1"}static get MailMergeLanguagePickerControl(){return"B634828E-C390-444A-AFE6-E07315D9D970"}static get ConnectionControl(){return"3246F906-1F71-45F7-B11F-D7BE0F9D04C9"}static get ConnectionRoleObjectTypeListControl(){return"821ACF1A-7E46-4A0C-965D-FE14A57D78C7"}static get MapsControl(){return"62B0DF79-0464-470F-8AF7-4483CFEA0C7D"}static get MapLinkControl(){return"91DC0675-C8B9-4421-B1E0-261CEBF02BAC"}static get WebResourceHtmlControl(){return"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"}static get WebResourceImageControl(){return"587CDF98-C1D5-4BDE-8473-14A0BC7644A7"}static get WebResourceSilverlightControl(){return"080677DB-86EC-4544-AC42-F927E74B491F"}static get ReportControl(){return"A28F441B-916C-4865-87FD-0C5D53BD59C9"}static get ArticleContentControl(){return"F02EF977-2564-4B9A-B2F0-DF083D8A019B"}static get ProcessControl(){return"06E9F7AF-1F54-4681-8EEC-1E21A1CEB465"}static get ActivitiesWallControl(){return"6636847D-B74D-4994-B55A-A6FAF97ECEA2"}static get QuickFormControl(){return"69AF7DCA-2E3B-4EE7-9201-0DA731DD2413"}static get QuickFormCollectionControl(){return"5C5600E0-1D6E-4205-A272-BE80DA87FD42"}static get LinkControl(){return"DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"}static get CompositionLinkControl(){return"DB1284EF-9FFC-4E99-B382-0CC082FE2364"}static get ErrorStatusControl(){return"F4C16ECA-CA81-4E39-9448-834B8378721E"}static get ActivitiesContainerControl(){return"C72511AB-84E5-4FB7-A543-25B4FC01E83E"}static get AccessPrivilegeControl(){return"F93A31B2-99AC-4084-8EC2-D4027C31369A"}static get TimerControl(){return"9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E"}static get DynamicPropertyListControl(){return"6896F004-B17A-4202-861E-8B7EA2080E0B"}static get ButtonControl(){return"00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20"}static get SearchWidgetControl(){return"E616A57F-20E0-4534-8662-A101B5DDF4E0"}static get EmailRecipientActivityControl(){return"26E9760F-7454-40DE-BB07-F6DCCCB82040"}static get LabelControl(){return"39354E4A-5015-4D74-8031-EA9EB73A1322"}static get CustomControl(){return"F9A8A302-114E-466A-B582-6771B2AE0D92"}static get EditFilterControl(){return"1479835F-F852-4679-B864-C6892A2844C9"}static get RichEditorControl(){return"F94DB24F-263D-44A7-B38E-A35E9854812B"}static get PowerBIControl(){return"8C54228C-1B25-4909-A12A-F2B968BB0D62"}static get EmailEngagementActionsControl(){return"F454228D-1D25-4319-E12F-D27968BC0234"}static get ACIControl(){return"C8BFBBEF-6851-4401-A0CC-7450062FE085"}static get ChoicesControl(){return"4AA28AB7-9C13-4F57-A73D-AD894D048B5F"}static get ReferencePanelSubgridControl(){return"02D4264B-47E2-4B4C-AA95-F439F3F4D458"}static get ReferencePanelSearchWidget(){return"7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F"}static get ReferencePanelQuickFormCollectionControl(){return"B68B05F0-A46D-43F8-843B-917920AF806A"}static get SpacerControl(){return"E4BAB03A-A9A5-4C23-CC3B-54AA680150E2"}},qa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},He=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new Ct;static initializeFieldControls(){let t=new Ct,r=e.getControlName(U.SingleLineofText,z.Phone);t.add(r,new L($.PhoneNumberControl));let n=e.getControlName(U.SingleLineofText,z.TextArea);t.add(n,new L($.TextAreaControl));let i=e.getControlName(U.SingleLineofText,z.Text);t.add(i,new L($.TextBoxControl));let a=e.getControlName(U.SingleLineofText,z.Email);t.add(a,new L($.EmailAddressControl));let o=e.getControlName(U.SingleLineofText,z.Url);t.add(o,new L($.UrlControl));let s=e.getControlName(U.SingleLineofText,z.TickerSymbol);t.add(s,new L($.TickerControl));let l=e.getControlName(U.SingleLineofText,z.PhoneticGuide);t.add(l,new L($.TextBoxControl));let u=e.getControlName(U.WholeNumber,z.Duration);t.add(u,new L($.DurationControl));let c=e.getControlName(U.WholeNumber,z.Language);t.add(c,new L($.LanguagePickerControl));let d=e.getControlName(U.WholeNumber,z.TimeZone);t.add(d,new L($.TimeZonePicklistControl));let p=e.getControlName(U.WholeNumber,z.None);t.add(p,new L($.IntegerControl));let f=e.getControlName(U.DateTime,z.DateOnly);t.add(f,new L($.DateTimeControl));let m=e.getControlName(U.DateTime,z.DateAndTime);t.add(m,new L($.DateTimeControl));let h=e.getControlName(U.LookupType,z.None);t.add(h,new L($.LookupControl));let v=e.getControlName(U.CustomerType,z.None);t.add(v,new L($.LookupControl));let b=e.getControlName(U.FloatingPointNumber,z.None);t.add(b,new L($.FloatControl));let E=e.getControlName(U.DecimalNumber,z.None);t.add(E,new L($.DecimalControl));let C=e.getControlName(U.Currency,z.None);t.add(C,new L($.MoneyControl));let N=e.getControlName(U.MultipleLineofText,z.None);t.add(N,new L($.TextAreaControl));let R=e.getControlName(U.MultipleLineofText,z.Text);t.add(R,new L($.TextAreaControl));let O=e.getControlName(U.MultipleLineofText,z.TextArea);t.add(O,new L($.TextAreaControl));let F=e.getControlName(U.MultipleLineofText,z.Email);t.add(F,new L($.EmailBodyControl));let k=e.getControlName(U.OptionSet,z.None);t.add(k,new L($.PicklistControl));let P=e.getControlName(U.TwoOptions,z.None);t.add(P,new L($.RadioControl));let V=e.getControlName(U.Image,z.None);t.add(V,new L($.WebResourceImageControl));let q=e.getControlName(U.Image,z.None);t.add(q,new L($.WebResourceHtmlControl));let ze=e.getControlName(U.TwoOptions,"Radio");t.add(ze,new L($.RadioControl));let Tt=e.getControlName(U.TwoOptions,"CheckBox");t.add(Tt,new L($.CheckBoxControl));let Be=e.getControlName(U.TwoOptions,"List");t.add(Be,new L($.PicklistControl));let Qe=e.getControlName(U.State,z.None);t.add(Qe,new L($.PicklistControl));let Z=e.getControlName(U.Status,z.None);t.add(Z,new L($.PicklistStatusControl));let ye=e.getControlName(U.OwnerType,z.None);t.add(ye,new L($.LookupControl));let xe=e.getControlName(U.PartyListType,z.None);t.add(xe,new L($.PartyListControl));let $n=e.getControlName(U.LookupType,z.Regarding);t.add($n,new L($.RegardingControl));let nr=e.getControlName(U.MultiSelectOptionSet,z.None);return t.add(nr,new L($.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!_.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=_.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return _.IsNullOrUndefined(t.control)||_.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===$.CustomControl}static initializeUnboundControls(){let t=new Ct;return t.add($.ACIControl,j.ACIControl),t.add($.IframeControl,j.IframeControl),t.add($.SearchWidgetControl,j.SearchWidgetControl),t.add($.MapsControl,j.MapsControl),t.add($.QuickFormCollectionControl,j.QuickFormCollectionControl),t.add($.GridControl,j.SubGridControl),t.add($.WebResourceImageControl,j.WebResourceImageControl),t.add($.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add($.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add($.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add($.ReferencePanelSubgridControl,j.SubGridControl),t.add($.TimerControl,j.TimerControl),t.add($.TimeLineControl,j.NotesControl),t.add($.TimeLineControlUC,j.NotesControl),t.add($.SocialInsightControl,j.SocialInsightControl),t.add(qa.RelationshipAssistant,j.CustomControl),t}static initializeReferencePanelControls(){let t=new Ct;return t.add($.IframeControl,j.IframeControl),t.add($.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add($.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add($.ReferencePanelSubgridControl,j.SubGridControl),t.add($.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add($.WebResourceImageControl,j.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new La;return t.add(Ua.IFRAME,!0),t.add(Ua.SPACER,!0),t.add(Ua.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(_.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.control)||_.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!_.IsNullOrUndefined(t)&&!_.IsNullOrUndefined(t.Name)&&t.Name.indexOf(De.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return _.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=M.EmptyString;if(_.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.control)||_.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return _.IsNullOrUndefined(t)||_.IsNullOrUndefined(t.guidString)?M.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===$.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===$.CustomControl&&!_.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case j.IframeControl:case j.ACIControl:case j.SocialInsightControl:return 6;case j.SubGridControl:case j.CustomControl:return 4;case j.WebResourceImageControl:return 15;case j.WebResourceHtmlControl:return 15;case j.MapsControl:return 8;case j.SearchWidgetControl:return 10;case j.NotesControl:case j.TimeLineControl:return 15;case j.TimerControl:return 2;default:}}static isLookUpControl(t){return!_.IsNullOrUndefined(t)&&t.ClassId.guidString===$.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!_.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!_.IsNullOrUndefined(t)&&(t.guidString===qa.RelationshipAssistant||t.guidString===qa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!_.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!_.IsNullOrUndefined(t)&&t.guidString===qa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(_.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===$.CustomControl&&!_.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Uu,NA=T(()=>{"use strict";Uu=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let r=this.listeners.indexOf(t);r>-1&&this.listeners.splice(r,1)}emit(t){this.listeners.forEach(r=>r(t)),this.listenersOncer.forEach(r=>r(t)),this.listenersOncer=[]}pipe(t){return this.on(r=>t.emit(r))}}});var qi,Va,DA,IA,ii,_A,TA,am=T(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(qi||(qi={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Va||(Va={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(DA||(DA={}));(function(e){e[e.None=0]="None",e[e.Create=1]="Create",e[e.Existing=2]="Existing",e[e.ReadOnly=3]="ReadOnly",e[e.Disabled=4]="Disabled",e[e.BulkEdit=6]="BulkEdit",e[e.Merge=7]="Merge",e[e.Print=8]="Print",e[e.FollowUp=9]="FollowUp"})(IA||(IA={}));(function(e){e[e.None=-1]="None",e[e.AppointmentBook=0]="AppointmentBook",e[e.Hardcoded=1]="Hardcoded",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.Dashboard=5]="Dashboard",e[e.Quick=6]="Quick",e[e.Mobile=7]="Mobile",e[e.Read=8]="Read",e[e.QuickCreate=9]="QuickCreate",e[e.Dialog=10]="Dialog",e[e.Card=11]="Card",e[e.TaskBasedForm=12]="TaskBasedForm",e[e.InteractionCentricDashboard=13]="InteractionCentricDashboard"})(ii||(ii={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(_A||(_A={}));(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(TA||(TA={}))});var Ga,PA=T(()=>{"use strict";bs();Ga=zf({packageName:"cds-designer-models",features:{showAllPCFControls:{owner:"anchoudh",description:"Do not only show the controls that exist on the whitelist",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},showTestControls:{owner:"lucorre",description:"Show advanced custom controls for testing (designated in Authoring Manifest with isTestOnly=true)",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},enablePrefetchGetMoreComponentsLocalization:{owner:"vajagarl",description:"Enables prefetching the localization files for controls displayed in custom control picker",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0}},showMapControl:{owner:"vayilavarapu",createdDate:"07/19/2022",description:"Show map control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableFallbackFormTemplate:{owner:"vajagarl",createdDate:"01/03/2023",description:"Enable default form template as fallback if unable to retrieve a form template from Dataverse",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableAutoInsertionOfCellInRow:{owner:"debeshd",createdDate:"09/01/2023",description:"Enable the auto insertion of cell in a row when a section is initialized",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableOneGridEvents:{owner:"aansu",createdDate:"08/21/2024",description:"Enable OneGrid events in form designer",enabledFor:{test:!0,preprod:!0,prod:!0,preview:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},disablePBIComponents:{owner:"adekulkarni",createdDate:"02/13/2025",description:"Disables PBI components and cleans them up from the form",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableAgentResponse:{owner:"jennietu",createdDate:"04/24/2025",description:"Enables agent response in form designer",enabledFor:{test:!0,preprod:!0,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableDelayedLocalizationForCustomControls:{owner:"aansu",createdDate:"06/08/2025",description:"Enables delayed localization of custom control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}}}})});function RA(e){return{...e,extractConfig:t=>g$(t,Object.keys(e.fallback))}}function g$(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var om=T(()=>{"use strict";});var sm=y((BY,xA)=>{var Es=new Proxy(function(){return Es},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Es},apply:function(){return Es},construct:function(){return{}}}),OA=function(){return Es};Object.setPrototypeOf(OA,Es);xA.exports=OA});var kA=y((UY,LA)=>{var Cs=new Proxy(function(){return Cs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Cs},apply:function(){return Cs},construct:function(){return{}}}),FA=function(){return Cs};Object.setPrototypeOf(FA,Cs);LA.exports=FA});var lm=y(($Y,BA)=>{var Ss=new Proxy(function(){return Ss},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ss},apply:function(){return Ss},construct:function(){return{}}}),MA=function(){return Ss};Object.setPrototypeOf(MA,Ss);BA.exports=MA});var $A=y((qY,UA)=>{function v$(){this.__data__=[],this.size=0}UA.exports=v$});var za=y((VY,qA)=>{function y$(e,t){return e===t||e!==e&&t!==t}qA.exports=y$});var Ns=y((GY,VA)=>{var b$=za();function w$(e,t){for(var r=e.length;r--;)if(b$(e[r][0],t))return r;return-1}VA.exports=w$});var zA=y((zY,GA)=>{var A$=Ns(),E$=Array.prototype,C$=E$.splice;function S$(e){var t=this.__data__,r=A$(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():C$.call(t,r,1),--this.size,!0}GA.exports=S$});var jA=y((WY,WA)=>{var N$=Ns();function D$(e){var t=this.__data__,r=N$(t,e);return r<0?void 0:t[r][1]}WA.exports=D$});var KA=y((jY,HA)=>{var I$=Ns();function _$(e){return I$(this.__data__,e)>-1}HA.exports=_$});var QA=y((HY,JA)=>{var T$=Ns();function P$(e,t){var r=this.__data__,n=T$(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}JA.exports=P$});var Ds=y((KY,XA)=>{var R$=$A(),O$=zA(),x$=jA(),F$=KA(),L$=QA();function Wa(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Wa.prototype.clear=R$;Wa.prototype.delete=O$;Wa.prototype.get=x$;Wa.prototype.has=F$;Wa.prototype.set=L$;XA.exports=Wa});var ZA=y((JY,YA)=>{var k$=Ds();function M$(){this.__data__=new k$,this.size=0}YA.exports=M$});var tE=y((QY,eE)=>{function B$(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}eE.exports=B$});var nE=y((XY,rE)=>{function U$(e){return this.__data__.get(e)}rE.exports=U$});var aE=y((YY,iE)=>{function $$(e){return this.__data__.has(e)}iE.exports=$$});var um=y((ZY,oE)=>{var q$=typeof global=="object"&&global&&global.Object===Object&&global;oE.exports=q$});var Tr=y((eZ,sE)=>{var V$=um(),G$=typeof self=="object"&&self&&self.Object===Object&&self,z$=V$||G$||Function("return this")();sE.exports=z$});var Is=y((tZ,lE)=>{var W$=Tr(),j$=W$.Symbol;lE.exports=j$});var pE=y((rZ,dE)=>{var uE=Is(),cE=Object.prototype,H$=cE.hasOwnProperty,K$=cE.toString,_s=uE?uE.toStringTag:void 0;function J$(e){var t=H$.call(e,_s),r=e[_s];try{e[_s]=void 0;var n=!0}catch{}var i=K$.call(e);return n&&(t?e[_s]=r:delete e[_s]),i}dE.exports=J$});var mE=y((nZ,fE)=>{var Q$=Object.prototype,X$=Q$.toString;function Y$(e){return X$.call(e)}fE.exports=Y$});var Vi=y((iZ,vE)=>{var hE=Is(),Z$=pE(),eq=mE(),tq="[object Null]",rq="[object Undefined]",gE=hE?hE.toStringTag:void 0;function nq(e){return e==null?e===void 0?rq:tq:gE&&gE in Object(e)?Z$(e):eq(e)}vE.exports=nq});var Dn=y((aZ,yE)=>{function iq(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}yE.exports=iq});var $u=y((oZ,bE)=>{var aq=Vi(),oq=Dn(),sq="[object AsyncFunction]",lq="[object Function]",uq="[object GeneratorFunction]",cq="[object Proxy]";function dq(e){if(!oq(e))return!1;var t=aq(e);return t==lq||t==uq||t==sq||t==cq}bE.exports=dq});var AE=y((sZ,wE)=>{var pq=Tr(),fq=pq["__core-js_shared__"];wE.exports=fq});var SE=y((lZ,CE)=>{var cm=AE(),EE=(function(){var e=/[^.]+$/.exec(cm&&cm.keys&&cm.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function mq(e){return!!EE&&EE in e}CE.exports=mq});var dm=y((uZ,NE)=>{var hq=Function.prototype,gq=hq.toString;function vq(e){if(e!=null){try{return gq.call(e)}catch{}try{return e+""}catch{}}return""}NE.exports=vq});var IE=y((cZ,DE)=>{var yq=$u(),bq=SE(),wq=Dn(),Aq=dm(),Eq=/[\\^$.*+?()[\]{}|]/g,Cq=/^\[object .+?Constructor\]$/,Sq=Function.prototype,Nq=Object.prototype,Dq=Sq.toString,Iq=Nq.hasOwnProperty,_q=RegExp("^"+Dq.call(Iq).replace(Eq,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Tq(e){if(!wq(e)||bq(e))return!1;var t=yq(e)?_q:Cq;return t.test(Aq(e))}DE.exports=Tq});var TE=y((dZ,_E)=>{function Pq(e,t){return e?.[t]}_E.exports=Pq});var ai=y((pZ,PE)=>{var Rq=IE(),Oq=TE();function xq(e,t){var r=Oq(e,t);return Rq(r)?r:void 0}PE.exports=xq});var qu=y((fZ,RE)=>{var Fq=ai(),Lq=Tr(),kq=Fq(Lq,"Map");RE.exports=kq});var Ts=y((mZ,OE)=>{var Mq=ai(),Bq=Mq(Object,"create");OE.exports=Bq});var LE=y((hZ,FE)=>{var xE=Ts();function Uq(){this.__data__=xE?xE(null):{},this.size=0}FE.exports=Uq});var ME=y((gZ,kE)=>{function $q(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}kE.exports=$q});var UE=y((vZ,BE)=>{var qq=Ts(),Vq="__lodash_hash_undefined__",Gq=Object.prototype,zq=Gq.hasOwnProperty;function Wq(e){var t=this.__data__;if(qq){var r=t[e];return r===Vq?void 0:r}return zq.call(t,e)?t[e]:void 0}BE.exports=Wq});var qE=y((yZ,$E)=>{var jq=Ts(),Hq=Object.prototype,Kq=Hq.hasOwnProperty;function Jq(e){var t=this.__data__;return jq?t[e]!==void 0:Kq.call(t,e)}$E.exports=Jq});var GE=y((bZ,VE)=>{var Qq=Ts(),Xq="__lodash_hash_undefined__";function Yq(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Qq&&t===void 0?Xq:t,this}VE.exports=Yq});var WE=y((wZ,zE)=>{var Zq=LE(),e3=ME(),t3=UE(),r3=qE(),n3=GE();function ja(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}ja.prototype.clear=Zq;ja.prototype.delete=e3;ja.prototype.get=t3;ja.prototype.has=r3;ja.prototype.set=n3;zE.exports=ja});var KE=y((AZ,HE)=>{var jE=WE(),i3=Ds(),a3=qu();function o3(){this.size=0,this.__data__={hash:new jE,map:new(a3||i3),string:new jE}}HE.exports=o3});var QE=y((EZ,JE)=>{function s3(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}JE.exports=s3});var Ps=y((CZ,XE)=>{var l3=QE();function u3(e,t){var r=e.__data__;return l3(t)?r[typeof t=="string"?"string":"hash"]:r.map}XE.exports=u3});var ZE=y((SZ,YE)=>{var c3=Ps();function d3(e){var t=c3(this,e).delete(e);return this.size-=t?1:0,t}YE.exports=d3});var tC=y((NZ,eC)=>{var p3=Ps();function f3(e){return p3(this,e).get(e)}eC.exports=f3});var nC=y((DZ,rC)=>{var m3=Ps();function h3(e){return m3(this,e).has(e)}rC.exports=h3});var aC=y((IZ,iC)=>{var g3=Ps();function v3(e,t){var r=g3(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}iC.exports=v3});var Vu=y((_Z,oC)=>{var y3=KE(),b3=ZE(),w3=tC(),A3=nC(),E3=aC();function Ha(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Ha.prototype.clear=y3;Ha.prototype.delete=b3;Ha.prototype.get=w3;Ha.prototype.has=A3;Ha.prototype.set=E3;oC.exports=Ha});var lC=y((TZ,sC)=>{var C3=Ds(),S3=qu(),N3=Vu(),D3=200;function I3(e,t){var r=this.__data__;if(r instanceof C3){var n=r.__data__;if(!S3||n.length<D3-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new N3(n)}return r.set(e,t),this.size=r.size,this}sC.exports=I3});var pm=y((PZ,uC)=>{var _3=Ds(),T3=ZA(),P3=tE(),R3=nE(),O3=aE(),x3=lC();function Ka(e){var t=this.__data__=new _3(e);this.size=t.size}Ka.prototype.clear=T3;Ka.prototype.delete=P3;Ka.prototype.get=R3;Ka.prototype.has=O3;Ka.prototype.set=x3;uC.exports=Ka});var dC=y((RZ,cC)=>{var F3="__lodash_hash_undefined__";function L3(e){return this.__data__.set(e,F3),this}cC.exports=L3});var fC=y((OZ,pC)=>{function k3(e){return this.__data__.has(e)}pC.exports=k3});var hC=y((xZ,mC)=>{var M3=Vu(),B3=dC(),U3=fC();function Gu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new M3;++t<r;)this.add(e[t])}Gu.prototype.add=Gu.prototype.push=B3;Gu.prototype.has=U3;mC.exports=Gu});var vC=y((FZ,gC)=>{function $3(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}gC.exports=$3});var bC=y((LZ,yC)=>{function q3(e,t){return e.has(t)}yC.exports=q3});var fm=y((kZ,wC)=>{var V3=hC(),G3=vC(),z3=bC(),W3=1,j3=2;function H3(e,t,r,n,i,a){var o=r&W3,s=e.length,l=t.length;if(s!=l&&!(o&&l>s))return!1;var u=a.get(e),c=a.get(t);if(u&&c)return u==t&&c==e;var d=-1,p=!0,f=r&j3?new V3:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var v=o?n(h,m,d,t,e,a):n(m,h,d,e,t,a);if(v!==void 0){if(v)continue;p=!1;break}if(f){if(!G3(t,function(b,E){if(!z3(f,E)&&(m===b||i(m,b,r,n,a)))return f.push(E)})){p=!1;break}}else if(!(m===h||i(m,h,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}wC.exports=H3});var mm=y((MZ,AC)=>{var K3=Tr(),J3=K3.Uint8Array;AC.exports=J3});var CC=y((BZ,EC)=>{function Q3(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}EC.exports=Q3});var NC=y((UZ,SC)=>{function X3(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}SC.exports=X3});var PC=y(($Z,TC)=>{var DC=Is(),IC=mm(),Y3=za(),Z3=fm(),e4=CC(),t4=NC(),r4=1,n4=2,i4="[object Boolean]",a4="[object Date]",o4="[object Error]",s4="[object Map]",l4="[object Number]",u4="[object RegExp]",c4="[object Set]",d4="[object String]",p4="[object Symbol]",f4="[object ArrayBuffer]",m4="[object DataView]",_C=DC?DC.prototype:void 0,hm=_C?_C.valueOf:void 0;function h4(e,t,r,n,i,a,o){switch(r){case m4:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case f4:return!(e.byteLength!=t.byteLength||!a(new IC(e),new IC(t)));case i4:case a4:case l4:return Y3(+e,+t);case o4:return e.name==t.name&&e.message==t.message;case u4:case d4:return e==t+"";case s4:var s=e4;case c4:var l=n&r4;if(s||(s=t4),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=n4,o.set(e,t);var c=Z3(s(e),s(t),n,i,a,o);return o.delete(e),c;case p4:if(hm)return hm.call(e)==hm.call(t)}return!1}TC.exports=h4});var OC=y((qZ,RC)=>{function g4(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}RC.exports=g4});var oi=y((VZ,xC)=>{var v4=Array.isArray;xC.exports=v4});var LC=y((GZ,FC)=>{var y4=OC(),b4=oi();function w4(e,t,r){var n=t(e);return b4(e)?n:y4(n,r(e))}FC.exports=w4});var MC=y((zZ,kC)=>{function A4(e,t){for(var r=-1,n=e==null?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a}kC.exports=A4});var UC=y((WZ,BC)=>{function E4(){return[]}BC.exports=E4});var VC=y((jZ,qC)=>{var C4=MC(),S4=UC(),N4=Object.prototype,D4=N4.propertyIsEnumerable,$C=Object.getOwnPropertySymbols,I4=$C?function(e){return e==null?[]:(e=Object(e),C4($C(e),function(t){return D4.call(e,t)}))}:S4;qC.exports=I4});var zC=y((HZ,GC)=>{function _4(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}GC.exports=_4});var si=y((KZ,WC)=>{function T4(e){return e!=null&&typeof e=="object"}WC.exports=T4});var HC=y((JZ,jC)=>{var P4=Vi(),R4=si(),O4="[object Arguments]";function x4(e){return R4(e)&&P4(e)==O4}jC.exports=x4});var gm=y((QZ,QC)=>{var KC=HC(),F4=si(),JC=Object.prototype,L4=JC.hasOwnProperty,k4=JC.propertyIsEnumerable,M4=KC((function(){return arguments})())?KC:function(e){return F4(e)&&L4.call(e,"callee")&&!k4.call(e,"callee")};QC.exports=M4});var YC=y((XZ,XC)=>{function B4(){return!1}XC.exports=B4});var zu=y((Rs,Ja)=>{var U4=Tr(),$4=YC(),tS=typeof Rs=="object"&&Rs&&!Rs.nodeType&&Rs,ZC=tS&&typeof Ja=="object"&&Ja&&!Ja.nodeType&&Ja,q4=ZC&&ZC.exports===tS,eS=q4?U4.Buffer:void 0,V4=eS?eS.isBuffer:void 0,G4=V4||$4;Ja.exports=G4});var Wu=y((YZ,rS)=>{var z4=9007199254740991,W4=/^(?:0|[1-9]\d*)$/;function j4(e,t){var r=typeof e;return t=t??z4,!!t&&(r=="number"||r!="symbol"&&W4.test(e))&&e>-1&&e%1==0&&e<t}rS.exports=j4});var vm=y((ZZ,nS)=>{var H4=9007199254740991;function K4(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=H4}nS.exports=K4});var aS=y((eee,iS)=>{var J4=Vi(),Q4=vm(),X4=si(),Y4="[object Arguments]",Z4="[object Array]",eV="[object Boolean]",tV="[object Date]",rV="[object Error]",nV="[object Function]",iV="[object Map]",aV="[object Number]",oV="[object Object]",sV="[object RegExp]",lV="[object Set]",uV="[object String]",cV="[object WeakMap]",dV="[object ArrayBuffer]",pV="[object DataView]",fV="[object Float32Array]",mV="[object Float64Array]",hV="[object Int8Array]",gV="[object Int16Array]",vV="[object Int32Array]",yV="[object Uint8Array]",bV="[object Uint8ClampedArray]",wV="[object Uint16Array]",AV="[object Uint32Array]",Ce={};Ce[fV]=Ce[mV]=Ce[hV]=Ce[gV]=Ce[vV]=Ce[yV]=Ce[bV]=Ce[wV]=Ce[AV]=!0;Ce[Y4]=Ce[Z4]=Ce[dV]=Ce[eV]=Ce[pV]=Ce[tV]=Ce[rV]=Ce[nV]=Ce[iV]=Ce[aV]=Ce[oV]=Ce[sV]=Ce[lV]=Ce[uV]=Ce[cV]=!1;function EV(e){return X4(e)&&Q4(e.length)&&!!Ce[J4(e)]}iS.exports=EV});var sS=y((tee,oS)=>{function CV(e){return function(t){return e(t)}}oS.exports=CV});var uS=y((Os,Qa)=>{var SV=um(),lS=typeof Os=="object"&&Os&&!Os.nodeType&&Os,xs=lS&&typeof Qa=="object"&&Qa&&!Qa.nodeType&&Qa,NV=xs&&xs.exports===lS,ym=NV&&SV.process,DV=(function(){try{var e=xs&&xs.require&&xs.require("util").types;return e||ym&&ym.binding&&ym.binding("util")}catch{}})();Qa.exports=DV});var ju=y((ree,pS)=>{var IV=aS(),_V=sS(),cS=uS(),dS=cS&&cS.isTypedArray,TV=dS?_V(dS):IV;pS.exports=TV});var bm=y((nee,fS)=>{var PV=zC(),RV=gm(),OV=oi(),xV=zu(),FV=Wu(),LV=ju(),kV=Object.prototype,MV=kV.hasOwnProperty;function BV(e,t){var r=OV(e),n=!r&&RV(e),i=!r&&!n&&xV(e),a=!r&&!n&&!i&&LV(e),o=r||n||i||a,s=o?PV(e.length,String):[],l=s.length;for(var u in e)(t||MV.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||FV(u,l)))&&s.push(u);return s}fS.exports=BV});var Hu=y((iee,mS)=>{var UV=Object.prototype;function $V(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||UV;return e===r}mS.exports=$V});var wm=y((aee,hS)=>{function qV(e,t){return function(r){return e(t(r))}}hS.exports=qV});var vS=y((oee,gS)=>{var VV=wm(),GV=VV(Object.keys,Object);gS.exports=GV});var bS=y((see,yS)=>{var zV=Hu(),WV=vS(),jV=Object.prototype,HV=jV.hasOwnProperty;function KV(e){if(!zV(e))return WV(e);var t=[];for(var r in Object(e))HV.call(e,r)&&r!="constructor"&&t.push(r);return t}yS.exports=KV});var Fs=y((lee,wS)=>{var JV=$u(),QV=vm();function XV(e){return e!=null&&QV(e.length)&&!JV(e)}wS.exports=XV});var ES=y((uee,AS)=>{var YV=bm(),ZV=bS(),eG=Fs();function tG(e){return eG(e)?YV(e):ZV(e)}AS.exports=tG});var SS=y((cee,CS)=>{var rG=LC(),nG=VC(),iG=ES();function aG(e){return rG(e,iG,nG)}CS.exports=aG});var IS=y((dee,DS)=>{var NS=SS(),oG=1,sG=Object.prototype,lG=sG.hasOwnProperty;function uG(e,t,r,n,i,a){var o=r&oG,s=NS(e),l=s.length,u=NS(t),c=u.length;if(l!=c&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:lG.call(t,p)))return!1}var f=a.get(e),m=a.get(t);if(f&&m)return f==t&&m==e;var h=!0;a.set(e,t),a.set(t,e);for(var v=o;++d<l;){p=s[d];var b=e[p],E=t[p];if(n)var C=o?n(E,b,p,t,e,a):n(b,E,p,e,t,a);if(!(C===void 0?b===E||i(b,E,r,n,a):C)){h=!1;break}v||(v=p=="constructor")}if(h&&!v){var N=e.constructor,R=t.constructor;N!=R&&"constructor"in e&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof R=="function"&&R instanceof R)&&(h=!1)}return a.delete(e),a.delete(t),h}DS.exports=uG});var TS=y((pee,_S)=>{var cG=ai(),dG=Tr(),pG=cG(dG,"DataView");_S.exports=pG});var RS=y((fee,PS)=>{var fG=ai(),mG=Tr(),hG=fG(mG,"Promise");PS.exports=hG});var xS=y((mee,OS)=>{var gG=ai(),vG=Tr(),yG=gG(vG,"Set");OS.exports=yG});var LS=y((hee,FS)=>{var bG=ai(),wG=Tr(),AG=bG(wG,"WeakMap");FS.exports=AG});var GS=y((gee,VS)=>{var Am=TS(),Em=qu(),Cm=RS(),Sm=xS(),Nm=LS(),qS=Vi(),Xa=dm(),kS="[object Map]",EG="[object Object]",MS="[object Promise]",BS="[object Set]",US="[object WeakMap]",$S="[object DataView]",CG=Xa(Am),SG=Xa(Em),NG=Xa(Cm),DG=Xa(Sm),IG=Xa(Nm),Gi=qS;(Am&&Gi(new Am(new ArrayBuffer(1)))!=$S||Em&&Gi(new Em)!=kS||Cm&&Gi(Cm.resolve())!=MS||Sm&&Gi(new Sm)!=BS||Nm&&Gi(new Nm)!=US)&&(Gi=function(e){var t=qS(e),r=t==EG?e.constructor:void 0,n=r?Xa(r):"";if(n)switch(n){case CG:return $S;case SG:return kS;case NG:return MS;case DG:return BS;case IG:return US}return t});VS.exports=Gi});var XS=y((vee,QS)=>{var Dm=pm(),_G=fm(),TG=PC(),PG=IS(),zS=GS(),WS=oi(),jS=zu(),RG=ju(),OG=1,HS="[object Arguments]",KS="[object Array]",Ku="[object Object]",xG=Object.prototype,JS=xG.hasOwnProperty;function FG(e,t,r,n,i,a){var o=WS(e),s=WS(t),l=o?KS:zS(e),u=s?KS:zS(t);l=l==HS?Ku:l,u=u==HS?Ku:u;var c=l==Ku,d=u==Ku,p=l==u;if(p&&jS(e)){if(!jS(t))return!1;o=!0,c=!1}if(p&&!c)return a||(a=new Dm),o||RG(e)?_G(e,t,r,n,i,a):TG(e,t,l,r,n,i,a);if(!(r&OG)){var f=c&&JS.call(e,"__wrapped__"),m=d&&JS.call(t,"__wrapped__");if(f||m){var h=f?e.value():e,v=m?t.value():t;return a||(a=new Dm),i(h,v,r,n,a)}}return p?(a||(a=new Dm),PG(e,t,r,n,i,a)):!1}QS.exports=FG});var tN=y((yee,eN)=>{var LG=XS(),YS=si();function ZS(e,t,r,n,i){return e===t?!0:e==null||t==null||!YS(e)&&!YS(t)?e!==e&&t!==t:LG(e,t,r,n,ZS,i)}eN.exports=ZS});var nN=y((bee,rN)=>{var kG=tN();function MG(e,t){return kG(e,t)}rN.exports=MG});var Im=y((wee,iN)=>{var BG=ai(),UG=(function(){try{var e=BG(Object,"defineProperty");return e({},"",{}),e}catch{}})();iN.exports=UG});var Ju=y((Aee,oN)=>{var aN=Im();function $G(e,t,r){t=="__proto__"&&aN?aN(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}oN.exports=$G});var _m=y((Eee,sN)=>{var qG=Ju(),VG=za();function GG(e,t,r){(r!==void 0&&!VG(e[t],r)||r===void 0&&!(t in e))&&qG(e,t,r)}sN.exports=GG});var uN=y((Cee,lN)=>{function zG(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),s=o.length;s--;){var l=o[e?s:++i];if(r(a[l],l,a)===!1)break}return t}}lN.exports=zG});var dN=y((See,cN)=>{var WG=uN(),jG=WG();cN.exports=jG});var gN=y((Ls,Ya)=>{var HG=Tr(),hN=typeof Ls=="object"&&Ls&&!Ls.nodeType&&Ls,pN=hN&&typeof Ya=="object"&&Ya&&!Ya.nodeType&&Ya,KG=pN&&pN.exports===hN,fN=KG?HG.Buffer:void 0,mN=fN?fN.allocUnsafe:void 0;function JG(e,t){if(t)return e.slice();var r=e.length,n=mN?mN(r):new e.constructor(r);return e.copy(n),n}Ya.exports=JG});var bN=y((Nee,yN)=>{var vN=mm();function QG(e){var t=new e.constructor(e.byteLength);return new vN(t).set(new vN(e)),t}yN.exports=QG});var AN=y((Dee,wN)=>{var XG=bN();function YG(e,t){var r=t?XG(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}wN.exports=YG});var CN=y((Iee,EN)=>{function ZG(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}EN.exports=ZG});var DN=y((_ee,NN)=>{var e9=Dn(),SN=Object.create,t9=(function(){function e(){}return function(t){if(!e9(t))return{};if(SN)return SN(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();NN.exports=t9});var Tm=y((Tee,IN)=>{var r9=wm(),n9=r9(Object.getPrototypeOf,Object);IN.exports=n9});var TN=y((Pee,_N)=>{var i9=DN(),a9=Tm(),o9=Hu();function s9(e){return typeof e.constructor=="function"&&!o9(e)?i9(a9(e)):{}}_N.exports=s9});var RN=y((Ree,PN)=>{var l9=Fs(),u9=si();function c9(e){return u9(e)&&l9(e)}PN.exports=c9});var FN=y((Oee,xN)=>{var d9=Vi(),p9=Tm(),f9=si(),m9="[object Object]",h9=Function.prototype,g9=Object.prototype,ON=h9.toString,v9=g9.hasOwnProperty,y9=ON.call(Object);function b9(e){if(!f9(e)||d9(e)!=m9)return!1;var t=p9(e);if(t===null)return!0;var r=v9.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&ON.call(r)==y9}xN.exports=b9});var Pm=y((xee,LN)=>{function w9(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}LN.exports=w9});var Rm=y((Fee,kN)=>{var A9=Ju(),E9=za(),C9=Object.prototype,S9=C9.hasOwnProperty;function N9(e,t,r){var n=e[t];(!(S9.call(e,t)&&E9(n,r))||r===void 0&&!(t in e))&&A9(e,t,r)}kN.exports=N9});var BN=y((Lee,MN)=>{var D9=Rm(),I9=Ju();function _9(e,t,r,n){var i=!r;r||(r={});for(var a=-1,o=t.length;++a<o;){var s=t[a],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?I9(r,s,l):D9(r,s,l)}return r}MN.exports=_9});var $N=y((kee,UN)=>{function T9(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}UN.exports=T9});var VN=y((Mee,qN)=>{var P9=Dn(),R9=Hu(),O9=$N(),x9=Object.prototype,F9=x9.hasOwnProperty;function L9(e){if(!P9(e))return O9(e);var t=R9(e),r=[];for(var n in e)n=="constructor"&&(t||!F9.call(e,n))||r.push(n);return r}qN.exports=L9});var Om=y((Bee,GN)=>{var k9=bm(),M9=VN(),B9=Fs();function U9(e){return B9(e)?k9(e,!0):M9(e)}GN.exports=U9});var WN=y((Uee,zN)=>{var $9=BN(),q9=Om();function V9(e){return $9(e,q9(e))}zN.exports=V9});var XN=y(($ee,QN)=>{var jN=_m(),G9=gN(),z9=AN(),W9=CN(),j9=TN(),HN=gm(),KN=oi(),H9=RN(),K9=zu(),J9=$u(),Q9=Dn(),X9=FN(),Y9=ju(),JN=Pm(),Z9=WN();function e5(e,t,r,n,i,a,o){var s=JN(e,r),l=JN(t,r),u=o.get(l);if(u){jN(e,r,u);return}var c=a?a(s,l,r+"",e,t,o):void 0,d=c===void 0;if(d){var p=KN(l),f=!p&&K9(l),m=!p&&!f&&Y9(l);c=l,p||f||m?KN(s)?c=s:H9(s)?c=W9(s):f?(d=!1,c=G9(l,!0)):m?(d=!1,c=z9(l,!0)):c=[]:X9(l)||HN(l)?(c=s,HN(s)?c=Z9(s):(!Q9(s)||J9(s))&&(c=j9(l))):d=!1}d&&(o.set(l,c),i(c,l,n,a,o),o.delete(l)),jN(e,r,c)}QN.exports=e5});var xm=y((qee,ZN)=>{var t5=pm(),r5=_m(),n5=dN(),i5=XN(),a5=Dn(),o5=Om(),s5=Pm();function YN(e,t,r,n,i){e!==t&&n5(t,function(a,o){if(i||(i=new t5),a5(a))i5(e,t,o,r,YN,n,i);else{var s=n?n(s5(e,o),a,o+"",e,t,i):void 0;s===void 0&&(s=a),r5(e,o,s)}},o5)}ZN.exports=YN});var Fm=y((Vee,eD)=>{function l5(e){return e}eD.exports=l5});var rD=y((Gee,tD)=>{function u5(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}tD.exports=u5});var aD=y((zee,iD)=>{var c5=rD(),nD=Math.max;function d5(e,t,r){return t=nD(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=nD(n.length-t,0),o=Array(a);++i<a;)o[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(o),c5(e,this,s)}}iD.exports=d5});var sD=y((Wee,oD)=>{function p5(e){return function(){return e}}oD.exports=p5});var cD=y((jee,uD)=>{var f5=sD(),lD=Im(),m5=Fm(),h5=lD?function(e,t){return lD(e,"toString",{configurable:!0,enumerable:!1,value:f5(t),writable:!0})}:m5;uD.exports=h5});var pD=y((Hee,dD)=>{var g5=800,v5=16,y5=Date.now;function b5(e){var t=0,r=0;return function(){var n=y5(),i=v5-(n-r);if(r=n,i>0){if(++t>=g5)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}dD.exports=b5});var mD=y((Kee,fD)=>{var w5=cD(),A5=pD(),E5=A5(w5);fD.exports=E5});var gD=y((Jee,hD)=>{var C5=Fm(),S5=aD(),N5=mD();function D5(e,t){return N5(S5(e,t,C5),e+"")}hD.exports=D5});var yD=y((Qee,vD)=>{var I5=za(),_5=Fs(),T5=Wu(),P5=Dn();function R5(e,t,r){if(!P5(r))return!1;var n=typeof t;return(n=="number"?_5(r)&&T5(t,r.length):n=="string"&&t in r)?I5(r[t],e):!1}vD.exports=R5});var Lm=y((Xee,bD)=>{var O5=gD(),x5=yD();function F5(e){return O5(function(t,r){var n=-1,i=r.length,a=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(a=e.length>3&&typeof a=="function"?(i--,a):void 0,o&&x5(r[0],r[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,a)}return t})}bD.exports=F5});var AD=y((Yee,wD)=>{var L5=xm(),k5=Lm(),M5=k5(function(e,t,r,n){L5(e,t,r,n)});wD.exports=M5});var cr,ks=T(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(cr||(cr={}))});function CD(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${ED.EcsConfigType[i]}_${r}`;return{getData:i=>{let a=t.getItem(n(i));return Promise.resolve(a?JSON.parse(a):void 0)},putData:(i,a)=>(t.setItem(n(i),JSON.stringify(a)),Promise.resolve())}}var ED,B5,SD=T(()=>{"use strict";ED=ce(lm()),B5=ce(sm());});var km,ND=T(()=>{"use strict";Tu();km=ys({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var ID,_D,TD,PD,Mm,U5,Qu,DD,Bm=T(()=>{"use strict";ID=ce(sm()),_D=ce(kA()),TD=ce(lm()),PD=ce(nN()),Mm=ce(AD());ks();SD();ND();U5=60*1e3,Qu=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=cr.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,r,n="PROD"){this.clientName=t,this.logger=r,this.endpointType=n,this.ecsEndpoint=n==="PROD"?km.prodEcsEndpoint:km.integrationEcsEndpoint}client=new _D.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=ID.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:a})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let o=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[TD.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:o,databaseInterface:CD(this.clientName,n,this.endpointType),...a}),this.client.requestUpdate(),this._status===cr.NotLoaded&&(this._status=cr.Initialized)}catch(s){this._status=cr.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*U5)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Mm.default)({},t.fallback,n,t.override,DD)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let a=this.getConfig(t);(0,PD.default)(a,n)||(n={...a},r(a))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,a)=>{r=window.setTimeout(()=>{a(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,Mm.default)({},this.client.getConfig()?.config,this.clientConfigOverride,DD);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=cr.ConfigsLoaded;let{ConfigIDs:r,Headers:n}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:r,ETag:n?.ETag})};logEvent=(t,r)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...r})}},DD=(e,t)=>{if(Array.isArray(t))return t}});var OD=y((ste,RD)=>{"use strict";var $5=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};RD.exports=$5});var Um=y((lte,FD)=>{var Ms=new Proxy(function(){return Ms},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ms},apply:function(){return Ms},construct:function(){return{}}}),xD=function(){return Ms};Object.setPrototypeOf(xD,Ms);FD.exports=xD});var MD=y((ute,kD)=>{var Bs=new Proxy(function(){return Bs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Bs},apply:function(){return Bs},construct:function(){return{}}}),LD=function(){return Bs};Object.setPrototypeOf(LD,Bs);kD.exports=LD});var zD=y((cte,GD)=>{"use strict";var $m=MD(),q5={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},V5={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},G5={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},qD={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},qm={};qm[$m.ForwardRef]=G5;qm[$m.Memo]=qD;function BD(e){return $m.isMemo(e)?qD:qm[e.$$typeof]||q5}var z5=Object.defineProperty,W5=Object.getOwnPropertyNames,UD=Object.getOwnPropertySymbols,j5=Object.getOwnPropertyDescriptor,H5=Object.getPrototypeOf,$D=Object.prototype;function VD(e,t,r){if(typeof t!="string"){if($D){var n=H5(t);n&&n!==$D&&VD(e,n,r)}var i=W5(t);UD&&(i=i.concat(UD(t)));for(var a=BD(e),o=BD(t),s=0;s<i.length;++s){var l=i[s];if(!V5[l]&&!(r&&r[l])&&!(o&&o[l])&&!(a&&a[l])){var u=j5(t,l);try{z5(e,l,u)}catch{}}}}return e}GD.exports=VD});function jD(e,t,r){let[n,i]=(0,Za.useState)(e.getConfig(t));return(0,Za.useEffect)(()=>{if(!r?.subscribe&&e.status===cr.ConfigsLoaded)return;let a=e.subscribe(t,o=>{i(o),r?.subscribe||a.unsubscribe()});return a?.unsubscribe},[]),n}function HD(e){return function(t,r){return jD(e,t,r)}}function KD(e,t,r,n){let i=a=>{let o=jD(e,t,n),s={...a,...o};return Za.default.createElement(r,{...s})};return(0,WD.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function JD(e,t,r,n){return t.reduce((i,a)=>KD(e,a,i,n),r)}function QD(e){return function(t,r,n){return KD(e,t,r,n)}}var WD,Za,Vm=T(()=>{"use strict";WD=ce(zD()),Za=ce(Um());ks();});var YD=y((fte,XD)=>{var K5=xm(),J5=Lm(),Q5=J5(function(e,t,r){K5(e,t,r)});XD.exports=Q5});var Xu=y((mte,ZD)=>{var X5=Vi(),Y5=si(),Z5="[object Symbol]";function e8(e){return typeof e=="symbol"||Y5(e)&&X5(e)==Z5}ZD.exports=e8});var tI=y((hte,eI)=>{var t8=oi(),r8=Xu(),n8=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i8=/^\w*$/;function a8(e,t){if(t8(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||r8(e)?!0:i8.test(e)||!n8.test(e)||t!=null&&e in Object(t)}eI.exports=a8});var iI=y((gte,nI)=>{var rI=Vu(),o8="Expected a function";function Gm(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(o8);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(Gm.Cache||rI),r}Gm.Cache=rI;nI.exports=Gm});var oI=y((vte,aI)=>{var s8=iI(),l8=500;function u8(e){var t=s8(e,function(n){return r.size===l8&&r.clear(),n}),r=t.cache;return t}aI.exports=u8});var lI=y((yte,sI)=>{var c8=oI(),d8=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,p8=/\\(\\)?/g,f8=c8(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(d8,function(r,n,i,a){t.push(i?a.replace(p8,"$1"):n||r)}),t});sI.exports=f8});var cI=y((bte,uI)=>{function m8(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}uI.exports=m8});var gI=y((wte,hI)=>{var dI=Is(),h8=cI(),g8=oi(),v8=Xu(),y8=1/0,pI=dI?dI.prototype:void 0,fI=pI?pI.toString:void 0;function mI(e){if(typeof e=="string")return e;if(g8(e))return h8(e,mI)+"";if(v8(e))return fI?fI.call(e):"";var t=e+"";return t=="0"&&1/e==-y8?"-0":t}hI.exports=mI});var yI=y((Ate,vI)=>{var b8=gI();function w8(e){return e==null?"":b8(e)}vI.exports=w8});var wI=y((Ete,bI)=>{var A8=oi(),E8=tI(),C8=lI(),S8=yI();function N8(e,t){return A8(e)?e:E8(e,t)?[e]:C8(S8(e))}bI.exports=N8});var EI=y((Cte,AI)=>{var D8=Xu(),I8=1/0;function _8(e){if(typeof e=="string"||D8(e))return e;var t=e+"";return t=="0"&&1/e==-I8?"-0":t}AI.exports=_8});var NI=y((Ste,SI)=>{var T8=Rm(),P8=wI(),R8=Wu(),CI=Dn(),O8=EI();function x8(e,t,r,n){if(!CI(e))return e;t=P8(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i<a;){var l=O8(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=o){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=CI(c)?c:R8(t[i+1])?[]:{})}T8(s,l,u),s=s[l]}return e}SI.exports=x8});var II=y((Nte,DI)=>{var F8=NI();function L8(e,t,r){return e==null?e:F8(e,t,r)}DI.exports=L8});function RI(e){let{query:t}=(0,PI.default)(window.location.href,!0);return M8(e,t),e}function M8(e,t){let r=k8+e.clientName,n=Object.keys(t).filter(a=>a.startsWith(r));if(!n)return;let i={};n.forEach(a=>{let o=t[a];if(o)try{let s=JSON.parse(o),l=r+OI,u={};if(a===r)u=s;else if(a.startsWith(l)){let c=a.substring(l.length);(0,TI.default)(u,c,s)}(0,_I.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var _I,TI,PI,OI,k8,xI=T(()=>{"use strict";_I=ce(YD()),TI=ce(II()),PI=ce(Kf());OI=".",k8="ecs"+OI});function Zu(e,t,r){let n=RI(new Qu(e,t,r));function i(a){(0,Yu.useEffect)(()=>{n.init(a)},[])}return{featuresClient:n,createFeature:U8(n),useFeaturesClientInitParams:i,withFeatures:(a,o,s)=>JD(n,a,o,s)}}function U8(e){let t=HD(e),r=QD(e);return function(i){let a=RA(i);return a.getConfig=()=>e.getConfig(a),a.isLoaded=()=>e.status===cr.ConfigsLoaded,Xf.register(a,e.clientName),{useFeature:o=>t(a,o),withFeature:(o,s)=>r(a,o,s),feature:a}}}var B8,Yu,zm=T(()=>{"use strict";B8=ce(OD()),Yu=ce(Um());om();Bm();ks();Vm();xI();Yf();});var FI=T(()=>{"use strict";om();Bm();zm();ks();Vm();xu();Zf();});function ec(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,eo.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,eo.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,eo.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var eo,Wm=T(()=>{"use strict";eo=ce(ki());});var Wte,jte,Hte,LI=T(()=>{"use strict";FI();Wm();({featuresClient:Wte,createFeature:jte,useFeaturesClientInitParams:Hte}=Zu("PowerApps-Shell-Test",ec("shell-features")))});var BI=y((Jte,MI)=>{var Us=new Proxy(function(){return Us},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Us},apply:function(){return Us},construct:function(){return{}}}),kI=function(){return Us};Object.setPrototypeOf(kI,Us);MI.exports=kI});var $8,q8,UI=T(()=>{"use strict";hs();$8=ce(BI()),q8=ce(ki());});var $I=T(()=>{"use strict";LI();Wm();UI();});var ire,to,are,qI=T(()=>{"use strict";$I();zm();({featuresClient:ire,createFeature:to,useFeaturesClientInitParams:are}=Zu("PowerApps-MakerPortal",ec("powerapps-features")))});var VI,GI,ure,cre,dre,pre,jm=T(()=>{"use strict";PA();qI();({feature:VI}=to({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:Ga.enableAutoInsertionOfCellInRow}})),{feature:GI}=to({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ga.enableOneGridEvents}}),{feature:ure}=to({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ga.disablePBIComponents}}),{feature:cre}=to({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:Ga.enableAgentResponse}}),{feature:dre,useFeature:pre}=to({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ga.enableDelayedLocalizationForCustomControls}})});var jI=y((mre,WI)=>{var $s=new Proxy(function(){return $s},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$s},apply:function(){return $s},construct:function(){return{}}}),zI=function(){return $s};Object.setPrototypeOf(zI,$s);WI.exports=zI});var gt,li=T(()=>{"use strict";We();$e();ht();Bu();ee();tt();gt=class extends H{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(g.colspan);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){_.IsNullOrUndefined(t)||this.setProperty(g.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(g.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}set id(t){this.setProperty(g.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(g.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(g.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}get Name(){return this.getProperty(g.Name)}set Name(t){this.setProperty(g.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(g.languagecode)===r){i.setProperty(g.description,t);return}let n=new H(w.formLabel,null);n.setProperty(g.description,t),n.setProperty(g.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(g.languagecode)===t)return r.getProperty(g.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(g.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(g.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(g.availableforphone)}set availableforphone(t){_.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(g.availableforphone,String(t))}get visible(){return this.getProcessedValue(g.visible)}set visible(t){_.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(g.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(g.showlabel)}set showlabel(t){_.IsNullOrUndefined(t)||this.setProperty(g.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return _.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(w.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(w.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.DefaultViewId):M.EmptyString}set defaultviewid(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.DependentAttributeName):M.EmptyString}set dependentattributename(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.DependentAttributeType):M.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(w.formControl);if(t)return t.getParam(g.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.FilterRelationshipName):M.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(w.formControl);return t?t.getParam(g.AvailableViewIds):M.EmptyString}set availableviewids(t){let r=this.getFirstChild(w.formControl);r&&!this.IsUnboundControl&&r.setParameter(g.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(w.formControl);if(t&&t.ClassId){let r=He.getUniqueIdentifierForControl(t);return!_.IsNullOrUndefined(r)&&He.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(w.formControl);if(t){let n=He.getUniqueIdentifierForControl(t).guidString,i=n===$.GridControl||n===$.TimeLineControl||n===$.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===w.formSection||this.NodeName===w.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(w.formControl);if(t){let n=He.getUniqueIdentifierForControl(t).guidString,i=n===$.MapsControl||n===$.WebResourceHtmlControl||n===$.WebResourceImageControl||n===$.IframeControl||n===$.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(w.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(w.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var ro,Hm=T(()=>{"use strict";ht();ee();tt();ro=class extends H{constructor(t,r){super(w.dependency,t),M.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(g.id,t)}get id(){return this.getProperty(g.id)}setDefaultProperties(t){this.id=t}}});var HI,no,Km=T(()=>{"use strict";$e();Hm();ee();tt();li();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(HI||(HI={}));no=class extends gt{constructor(t,r){super(w.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(g.Name,t)}get eventName(){return this.getProperty(g.Name)}set application(t){this.setProperty(g.application,t)}get application(){return this.getProperty(g.application)}set attribute(t){this.setProperty(g.EventAttribute,t)}get attribute(){return this.getProperty(g.EventAttribute)}set relationship(t){this.setProperty(g.Relationship,t)}get relationship(){return this.getProperty(g.Relationship)}set control(t){this.setProperty(g.Control,t)}get control(){return this.getProperty(g.Control)}set active(t){this.setProperty(g.EventActive,t)}get active(){return this.getProperty(g.EventActive)}getAllHandlers(){let t=this.getChildren(w.EventHandlers);return t&&t.length?t[0].getChildren(w.handler):[]}getAllDependencies(){let t=this.getChildren(w.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(w.formDependencies);if(_.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new H(w.formDependencies,this)),r=this.getFirstChild(w.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new ro(r,n.toString()))}}}});var Pr,qs=T(()=>{"use strict";We();ms();$e();Li();ee();tt();Ir();Pr=class extends H{previewVersion;constructor(t){super(w.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(g.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t)}set ClassId(t){this.setProperty(g.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(g.datafieldname)}set dataFieldName(t){this.setProperty(g.datafieldname,t)}set id(t){this.setProperty(g.id,t)}get id(){return this.getProperty(g.id)}get UniqueId(){let t=this.getProperty(g.uniqueid);return _.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set UniqueId(t){this.setProperty(g.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(g.isRequired)==="true"}set isRequired(t){_.IsNullOrUndefined(t)||this.setProperty(g.isRequired,String(t))}get disableMru(){return this.getParam(g.DisableMru)==="true"}set disableMru(t){_.IsNullOrUndefined(t)||this.setParameter(g.DisableMru,t)}get useMFDForCreate(){return this.getParam(g.UseMFDForCreate)==="true"}set useMFDForCreate(t){_.IsNullOrUndefined(t)||this.setParameter(g.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(g.UseMFDForEdit)==="true"}set useMFDForEdit(t){_.IsNullOrUndefined(t)||this.setParameter(g.UseMFDForEdit,t)}get disabled(){return this.getProperty(g.disabled)==="true"}set disabled(t){_.IsNullOrUndefined(t)||this.setProperty(g.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(g.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(g.indicationOfSubgrid,String(t))}getAllParameters(){let t=new Ct,r=this.getFirstChild(g.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),a=i&&i.length>0&&i[0];a&&t.add(n.getNodeName(),a.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Nn.StartTag+r).toString(),a=this.parametersNode;if(a){let o=a.findFirst(s=>s&&s.getNodeName()===t);if(o)if(n){this.deleteFirstGrandChildOfName(w.controlParameters,o);return}else{let s=o.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):o.addChild(new H(i,o))}else n||(o=new H(t,a),o.addChild(new H(i,o)),a.addChild(o))}else if(!n){a=new H("parameters",this);let o=new H(t,a);o.addChild(new H(i,o)),a.addChild(o),this.addChild(a)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let a=i.getNodeName();return a.charAt(0)===Nn.StartTag?a.substring(1):a}}}return null}get parametersNode(){let t=this.getChildren(g.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new Ct;switch(this.ClassId.guidString.toUpperCase()){case I.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(o=>{n.add(o,this.getParam(o))}),t&&t.containsKey("DefaultViewId")){let o=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",o)}else{let o=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,o.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(o=>{n.add(o,this.getParam(o))});break}let i=n.getInternalObject(),a=[];for(let o in i)i.hasOwnProperty(o)&&a.push({Name:o,Value:i[o]});return a}getIsUnbound(){return this.getProperty(g.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case I.BooleanControl:case I.CheckboxControl:return 0;case I.DateTimeControl:return 2;case I.DecimalControl:return 3;case I.FloatingNumberControl:return 4;case I.IntegerControl:case I.DurationControl:case I.LanguageControl:case I.TimezoneControl:return 5;case I.LookupControl:return 6;case I.CurrencyControl:return 8;case I.PartyListControl:return 10;case I.ChoiceControl:case I.RelationshipRoleChoiceControl:return 11;case I.ChoiceStatusControl:return 13;case I.TextAreaControl:case I.TextboxControl:case I.LabelControl:case I.EmailAddressControl:case I.UrlControl:case I.TickerControl:case I.ButtonControl:case I.PhoneNumberControl:return 14;case I.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===je.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:n,ControlLayout:0,RequiredLevel:0,Type:this.getAttributeTypeFromClassId(this.ClassId.guidString),IsUnbound:this.getIsUnbound(),IsRequired:this.isRequired,DataFieldName:this.dataFieldName,UniqueId:this.UniqueId&&this.UniqueId.guidString,Id:this.previewVersion?this.id+this.previewVersion:this.id,Label:r.getDisplayName(t.langCode),LabelId:r.labelId&&r.labelId.guidString,Name:null,ShowLabel:r.showlabel,PreviewId:r&&r.id.guidString,Visible:r.visible||t.formModelService.showHiddenElements}}}});var io,Jm=T(()=>{"use strict";ht();Ma();qs();ee();tt();io=class extends Pr{constructor(t){super(t)}get targetEntityType(){return this.getParam(g.targetEntityType)||M.EmptyString}set targetEntityType(t){this.setParameter(g.targetEntityType,t)}get viewId(){return M.StripBraces(this.getParam(g.viewId))||M.EmptyString}set viewId(t){this.setParameter(g.viewId,M.AddBraces(t))}get viewIds(){return this.getParam(g.viewIds)||M.EmptyString}set viewIds(t){this.setParameter(g.viewIds,t)}get relationshipName(){return this.getParam(g.RelationshipName)||M.EmptyString}set relationshipName(t){this.setParameter(g.RelationshipName,t)}get isUserView(){return M.IsStrictTrue(this.getParam(g.isUserView))}set isUserView(t){this.setParameter(g.isUserView,t.toString())}get enableViewPicker(){return M.IsStrictTrue(this.getParam(g.enableViewPicker))}set enableViewPicker(t){this.setParameter(g.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(g.autoExpand)===g.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(g.autoExpand,t?g.Auto:g.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(g.recordsPerPage)?Number(this.getParam(g.recordsPerPage)):Number(g.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(g.recordsPerPage,String(t))}get enableQuickFind(){return M.IsStrictTrue(this.getParam(g.enableQuickFind))}set enableQuickFind(t){this.setParameter(g.enableQuickFind,t)}get teamTemplateId(){return M.StripBraces(this.getParam(g.teamTemplateId))||M.EmptyString}set teamTemplateId(t){this.setParameter(g.teamTemplateId,M.AddBraces(t))}get chartId(){return this.getParam(g.visualizationId)||M.EmptyString}set chartId(t){this.setParameter(g.visualizationId,t)}get enableChartPicker(){return M.IsStrictTrue(this.getParam(g.enableChartPicker))}set enableChartPicker(t){this.setParameter(g.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(g.chartGridMode)){case ur.Chart:return ur.Chart;case ur.Grid:return ur.Grid;default:return ur.All}}set chartGridMode(t){this.setParameter(g.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=ur.Chart:this.chartGridMode=this.enableChartPicker?ur.All:ur.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case g.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case g.viewId:n.getAllChildren()[0].setNodeName("<"+M.AddBraces(r.viewId));break;case g.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case g.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case g.RelationshipName:let i=n.getAllChildren(),a="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(a):n.addChild(new H(a,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let a=n[i].getParameters().get(St.dataset)?n[i].getParameters().get(St.dataset)[0]:null;if(a){let o=a.getAllChildren();this.updateDefaultProperties(o,this)}else{let o=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(o,this)}}}}}});var ao,Qm=T(()=>{"use strict";ht();Ma();qs();ee();ao=class extends Pr{constructor(t){super(t)}get defaultViewId(){return M.StripBraces(this.getParam(g.DefaultViewId))||M.EmptyString}set defaultViewId(t){this.setParameter(g.DefaultViewId,M.AddBraces(t))}get autoResolve(){return M.IsStrictTrue(this.getParam(g.AutoResolve))}set autoResolve(t){this.setParameter(g.AutoResolve,t)}get disableQuickFind(){return M.IsStrictTrue(this.getParam(g.DisableQuickFind))}set disableQuickFind(t){this.setParameter(g.DisableQuickFind,t)}get disableViewPicker(){return M.IsStrictTrue(this.getParam(g.DisableViewPicker))}set disableViewPicker(t){this.setParameter(g.DisableViewPicker,t)}get allowFilterOff(){return M.IsStrictTrue(this.getParam(g.AllowFilterOff))}set allowFilterOff(t){this.setParameter(g.AllowFilterOff,t)}get disableMru(){return M.IsStrictTrue(this.getParam(g.DisableMru))}set disableMru(t){this.setParameter(g.DisableMru,t)}get dependentAttributeName(){return this.getParam(g.DependentAttributeName)||M.EmptyString}set dependentAttributeName(t){this.setParameter(g.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(g.DependentAttributeType)||M.EmptyString}set dependentAttributeType(t){this.setParameter(g.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(g.FilterRelationshipName)||M.EmptyString}set filterRelationshipName(t){this.setParameter(g.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(g.AvailableViewIds)||M.EmptyString}set availableViewIds(t){this.setParameter(g.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case g.datafieldname:case g.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case g.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+M.AddBraces(r.defaultViewId));break;case g.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case g.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case g.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case g.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case g.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case g.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case g.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case g.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case g.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let a=n[i].getParameters().get(St.value)?n[i].getParameters().get(St.value)[0]:null;if(a){let o=a.getAllChildren();this.updateDefaultProperties(o,this)}else{let o=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(o,this)}}}}}});var KI,Xm,qt,Vs=T(()=>{"use strict";KI=ce(jI());li();ee();$e();We();Km();qs();Bu();im();kf();Ir();Li();Fa();Jm();Qm();Ym();ws();Xm="_",qt=class e extends gt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(w.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,_.IsNullOrUndefined(this.getProperty(g.id))&&(this.id=new L(L.NewGuid()))}addControl(t,r,n,i,a,o,s){n instanceof Pr?this.addChild(n):n instanceof L&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,a,o,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!_.IsNullOrUndefined(this.control))return _.IsNullOrUndefined(this.control.dataFieldName)?_.IsNullOrUndefined(this.control.id)?!0:!Mi.dependencyFieldCount.containsKey(this.control.id):!Mi.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new no(this,ps.onLoad))}get dependencies(){let t=this.getChildren(w.formEvents);for(let r of t){let n=r.getChildren(w.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let a;if(i&&Su[i])a=Su[i].replace(/ /g,Xm)+Xm;else{a="Control_";let u=new Error("Control class id does not exist or is undefined");(0,KI.trackErrorTrace)(Et,{eventName:`${Vw}/getNextAvailableControlName`},u)}let o="new_",s=this.getHighestIndexById(t,i)+1,l=`${a}${o}${s}`;for(;n.has(l);)s++,l=`${a}${o}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,g.isUnbound,"true"),e.prototype.setProperty.call(t,g.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,a,o,s){let l;a===dr.Grid?(l=new io(this),l.indicationOfSubgrid=!0):a===dr.Lookup?l=new ao(this):l=new Pr(this);let u=n.guidString,c=o||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,g.id,c),l.ClassId=n,!_.IsNullOrUndefined(s)&&(l.UniqueId=s),!o&&r)this.getUnboundControlProperties(l);else{let d=He.getUniqueIdentifierForControl(l);_.IsNullOrUndefined(d)||(He.getControlDataTypeByControlOrUniqueId(d)===j.QuickFormCollectionControl||!He.isUnboundFormControlByIdentifier(d)?a!==dr.Grid&&o&&u!==I.IframeControl&&u!==I.SubgridControl&&u!==I.ReferencePanelSubgridControl&&(l.dataFieldName=o,e.prototype.setProperty.call(l,g.disabled,"false")):(this.rowspan=He.GetRowSpan(l),(He.getControlDataTypeByControlOrUniqueId(d)===j.NotesControl||He.getControlDataTypeByControlOrUniqueId(d)===j.TimeLineControl)&&(e.prototype.setProperty.call(l,g.disabled,"false"),l.id=j.NotesControl)),(He.getUnboundControlNameFromIdentifier(n)===j.SubGridControl||He.getUnboundControlNameFromIdentifier(n)===j.NotesControl||He.getUnboundControlNameFromIdentifier(n)===j.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(_.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let a=i.getAllChildren();for(let o of a){let s=o.GetPropertyByParameter(g.id);o.getNodeName()===w.dependency&&s?r.push(s):this.buildDependencyList(o,r)}}}get control(){return this.getFirstChild(w.formControl)}set rowspan(t){this.setProperty(g.rowspan,String(t))}get rowspan(){let t=this.getProperty(g.rowspan);return _.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(g.auto,String(t))}get autoexpand(){return this.getProperty(g.auto)==="true"}set colspan(t){let r=Number(rm.ONE_COLUMN),n=Number(rm.FOUR_COLUMN);_.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(g.colspan,String(t))}get colspan(){let t=this.getProperty(g.colspan);return _.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(w.formRow)}getParentSection(){return this.getAncestor(w.formSection)}getParentTab(){return this.getAncestor(w.formTab)}getParentForm(){return this.getAncestor(w.form)}isInHeader(){let t=this.getAncestor(w.formHeader);return!_.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(w.formFooter);return!_.IsNullOrUndefined(t)}isEmpty(){return _.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(w.formHeader):this.isInFooter()?this.getAncestor(w.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(g.userspacer);return _.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(g.userspacer,"true")}ClearUserSpacer(){this.setProperty(g.userspacer,"false")}get columns(){let t=this.getProperty(g.columnName);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!_.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();_.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let a=i.isDuplicateCell(this,n),o=this.getRequiredLevel(t);if((o===Ui.ApplicationRequired||o===Ui.SystemRequired)&&!a||this.isCellLockedByExternal(t)&&!a)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Ui.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Ui.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===w.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(a=>a.getNodeName()===w.formCell&&a.control&&a.control.ClassId.guidString===r),i=0;return n.forEach(a=>{i=Math.max(this.parseControlNameIndex(a.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===Xm&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var oo,Zm=T(()=>{"use strict";ht();ee();tt();oo=class extends H{isInternal;constructor(t,r,n,i){super(w.library,t),this.isInternal=!!i,M.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(g.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(g.libraryUniqueId,t)}get name(){return this.getProperty(g.libraryName)}set name(t){this.setProperty(g.libraryName,t)}get displayName(){return this.getProperty(g.displayName)}set displayName(t){this.setProperty(g.displayName,t)}get description(){return this.getProperty(g.description)}set description(t){this.setProperty(g.description,t)}}});var zi,eh=T(()=>{"use strict";$e();Vs();ee();tt();zi=class extends H{isRowAddedOnDragOver;constructor(t){super(w.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return _.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return _.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(w.formSection)}insertPaddingCellAtIndex(t){let r=new qt(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(w.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function V8(e){switch(e){case $i.Left:return qi.Left;case $i.Right:return qi.Right;case $i.Center:return qi.Center;default:return qi.Left}}function G8(e){switch(e){case $a.Left:return Va.Left;case $a.Top:return Va.Top;default:return Va.Left}}function JI(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var z8,en,Gs=T(()=>{"use strict";am();We();$e();ht();jm();Vs();ee();Ir();li();eh();z8=115,en=class e extends gt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Te.ONE_COLUMN;break;case 11:t=Te.TWO_COLUMN;break;case 111:t=Te.THREE_COLUMN;break;case 1111:t=Te.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=De.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+De.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(g.Name,r)}initializeDefaultProperties(t,r,n){if(n===Te.REFERENCE_PANEL){this.addProperty(g.rowheight,"25");let i=`${De.referencePanelNamePrefix}${L.NewGuid()}${De.namePrefix}`;this.addProperty(g.Name,i)}else this.setUniqueName();if(this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.IsUserDefined,De.IsUserDefined),this.addProperty(g.locklevel,De.LockLevel),this.addProperty(g.showlabel,De.ShowLabel),this.addProperty(g.showbar,De.ShowBar),this.addProperty(g.layout,De.Layout),this.addProperty(g.Fieldlabelalignment,De.labelAlignment),this.addProperty(g.Fieldlabelposition,De.labelPosition),_.IsNullOrUndefined(n))this.addProperty(g.columnName,De.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(g.columnName,i)}this.addProperty(g.LabelWidth,De.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return _.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(M.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new zi(null);if(this.addGrandChild(w.formRows,r),VI.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new qt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Te.REFERENCE_PANEL&&(n=Te.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(w.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(w.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(w.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(w.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(w.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(w.formRows);return t.length===0?[]:t[0].getChildren(w.formRow)}get columns(){let t=this.getProperty(g.columnName),r=_.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return JI(n)}return r}set columns(t){_.IsNullOrUndefined(t)||this.setProperty(g.columnName,String(t))}get rowHeight(){let t=this.getProperty(g.rowheight);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(g.rowheight,String(t))}set autoexpand(t){this.setProperty(g.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(g.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(g.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(g.IsUserDefined,"1"):this.setProperty(g.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(w.formColumn)}getParentTab(){return this.getAncestor(w.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(g.showlabel)==="true"}set showlabel(t){_.IsNullOrUndefined(t)||this.setProperty(g.showlabel,String(t))}get fieldLabelAlignment(){let t=De.labelAlignment,r=this.getProperty(g.Fieldlabelalignment);return _.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){_.IsNullOrUndefined(t)||this.setProperty(g.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(g.Fieldlabelposition);return _.IsNullOrUndefined(t)?De.labelPosition:t}set fieldLabelPosition(t){_.IsNullOrUndefined(t)||this.setProperty(g.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(g.showbar)==="true"}set showbar(t){_.IsNullOrUndefined(t)||this.setProperty(g.showbar,String(t))}get labelwidth(){let t=+this.getProperty(g.LabelWidth);return t===0?z8:t}set labelwidth(t){_.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(g.LabelWidth,t.toString())}async getRowsJSON(t){let r=[],n=[];if(this.rows){for(let i of this.rows)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this.id&&this.id.guidString,Rows:await this.getRowsJSON(t),CellLabel:{Width:this.labelwidth,Alignment:V8(this.fieldLabelAlignment),Position:G8(this.fieldLabelPosition)},Columns:JI(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===w.formSection){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!_.IsNullOrUndefined(this)&&!_.IsNullOrUndefined(this.Name)&&this.Name.indexOf(De.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===w.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===w.formFooter||this.NodeName===w.formHeader}}});var ui,tc=T(()=>{"use strict";ee();tt();Gs();ui=class e extends H{constructor(t){super(w.formColumn,t)}initializeDefaultProperties(t){this.addProperty(g.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(w.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new en(w.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(w.formSections,t,r)}initialize(t,r,n,i=Te.ONE_COLUMN){this.initializeDefaultProperties(t);let a=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(a,this.sections.length),a.setUniqueName()}get parentTab(){return this.getAncestor(w.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(w.formSection)}get width(){return this.getProperty(g.width)}set width(t){this.setProperty(g.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(w.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(g.Name),Id:this.getProperty(g.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(g.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var rc,QI=T(()=>{"use strict";We();ee();Ir();Gs();rc=class extends en{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(g.Name,n),this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.columnName,De.columns),this.setDisplayName(r,t)}}});var nc,XI=T(()=>{"use strict";tc();ee();QI();nc=class extends ui{addAndIntializeNavBarSection(t,r,n,i){let a=new rc(w.formSection,null);return a.initializeNavArea(t,r,i),this.addGrandChildAtIndex(w.formSections,a,n),a}}});var In,ic=T(()=>{"use strict";We();$e();ht();tc();ee();tt();li();In=class extends gt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(w.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(w.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=_e.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=_e.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=_e.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=_e.TWO_COLUMN_WIDER_RIGHT;break}t=_e.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=_e.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=_e.THREE_COLUMN_WIDER_MID;break}t=_e.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(g.Name,ri.namePrefix+t.toString()),this.addProperty(g.id,new L(L.NewGuid()).guidString),this.addProperty(g.IsUserDefined,ri.IsUserDefined),this.addProperty(g.locklevel,ri.LockLevel),this.addProperty(g.showlabel,ri.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=Te.ONE_COLUMN,a=!0,o){let s=this.getChildren(w.formColumns)[0],l=[];switch(t){case _e.ONE_COLUMN:l.push(100);break;case _e.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case _e.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case _e.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case _e.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case _e.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new ui(s);c.initialize(u,r,n,i),this.addGrandChild(w.formColumns,c)}}initialize(t,r,n,i,a,o=Te.ONE_COLUMN,s=!0,l){this.addChild(new H(w.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,a,o,s,l)}get columns(){let t=this.getChildren(w.formColumns);return t.length!==1?[]:t[0].getChildren(w.formColumn)}get expanded(){return this.getProcessedValue(g.expanded)}set expanded(t){_.IsNullOrUndefined(t)||this.setProperty(g.expanded,String(t))}get groupName(){return this.getProperty(g.groupName)}get contentType(){return this.getProperty(g.contentType)}set contentType(t){this.setProperty(g.contentType,t)}insertNewColumnAtIndex(t,r,n,i,a){t.initialize(n,i,a),this.addGrandChildAtIndex(w.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(w.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(w.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===w.formTab){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Wi,th=T(()=>{"use strict";We();ee();tt();Ir();XI();ic();Wi=class extends In{constructor(t,r,n){super(t,_e.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new L(L.NewGuid())}initializeDefaultProps(){this.addChild(new H(w.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(w.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let a of i.cells)if(a.NavId===t)return a;return null}initializeFiveColumns(){for(let t=0;t<ku.FIVE_COLUMN;t++){let r=new nc(this.getChildren(w.formColumns)[0]);r.initializeDefaultProperties(yA.FiveEqColumn),this.addGrandChild(w.formColumns,r)}}}});function j8(e){switch(e){case je.Main:return ii.Main;case je.QuickCreate:return ii.QuickCreate;case je.QuickViewForm:return ii.Quick;case je.Dialog:return ii.Dialog;default:return ii.None}}function H8(e,t){if(t===je.Main){if(e)switch(e.toLowerCase()){case"low":return ti.Low;case"highreadonlyvalues":return ti.HighReadOnlyValues;default:return ti.HighWithControls}return ti.Low}}var oc,W8,ac,YI=T(()=>{"use strict";NA();oc=ce(ki());am();$e();ht();Fa();jm();ee();Ma();Cf();Li();Vs();ee();li();Zm();th();ic();W8="1920";ac=class e extends gt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,a,o,s,l,u){super(w.form,null),this._formUniqueName=a,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=o,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new wu,this._metadataChangeEvent=new Uu}get FormLibraries(){let t=this.getFirstChild(w.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(a=>a instanceof qt).forEach(a=>{let o=a.events;o&&(t=t.concat(o))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof qt){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===w.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let a=i.GetPropertyByParameter(n).replace("$webresource:",""),o=new oo(void 0,void 0,"",!0);return o.name=a,o.displayName=a,o})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(a=>{r.add(a.id)})}catch(i){throw(0,oc.trackErrorTrace)(Gw,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:n.attribute,EventName:n.eventName}}),i}}),r}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return M.IsNullOrEmpty(this.getProperty(g.ShowImage))?!0:this.getProperty(g.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(g.ShowImage,String(t)):this.setProperty(g.ShowImage,"false")}get ShowNavigation(){return M.IsNullOrEmpty(this.getProperty(g.ShowNavigationbar))?!0:this.getProperty(g.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(g.ShowNavigationbar,String(t)):this.setProperty(g.ShowNavigationbar,"false")}get MaxWidth(){return M.IsNullOrEmpty(this.getProperty(g.MaxWidth))?W8:this.getProperty(g.MaxWidth)}set MaxWidth(t){this.setProperty(g.MaxWidth,t)}get headerDensityType(){return this.getProperty(g.HeaderDensityType)}set headerDensityType(t){t&&this.formType===je.Main?this.setProperty(g.HeaderDensityType,t):this.formType!==je.Main&&this.headerDensityType&&this.removeProperty(g.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===je.Main||this.formType===je.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(w.formHeader);return t.length!==1?null:t[0]}set header(t){_.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(w.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(w.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return _.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(w.formFooter);return t.length!==1?null:t[0]}set footer(t){_.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new In(null,t),a=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,a,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(w.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,a){let o=new In(null,_e.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);o.initialize(_e.ONE_COLUMN,s,this.LanguageCode,r,n,a,!1),this.addGrandChildAtIndex(w.formTabs,o,i);let l=o.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===ri.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(w.formTabs);return t.length!==1?[]:t[0].getChildren(w.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Wi)return t}return null}get NavigationNode(){let t=this.getChildren(w.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(w.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(w.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(w.formTabs);if(!_.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(w.formFooter).length>0}get displayCondition(){let t=this.getChildren(w.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(w.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(w.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(w.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);_.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(w.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof qt))return!1;let a=!0;return r==="Tab"?a=i.getParentTab()!==t.getParentTab():r==="Section"?a=i.getParentSection()!==t.getParentSection():a=i!==t,i instanceof qt&&i.control&&t.control&&a&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==I.CustomControl?!1:this.cellHasCustomControlWithName(t,ni.EditableGridControl)||GI.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,ni.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===I.CustomControl&&this.cellHasCustomControlWithName(t,ni.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===w.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let a of r)if(!(a instanceof Wi)){let o=a.toJSON(t);n.push(o)}for(let a of n)i.push(await a)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,oc.getSessionId)(),EntityLogicalName:this._entityName,FormId:this._formId.guidString,TabAttributes:{},Tabs:await this.getTabsJSON(t),HiddenFields:[],Header:this.header&&await this.header.toJSON(t),Footer:this.footer&&await this.footer.toJSON(t),...this.formType===je.Main?{HeaderDensity:H8(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:j8(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:r,BusinessLogic:void 0,FormLibraries:[],Navigation:n,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var sc,rh,ZI=T(()=>{"use strict";We();$e();ee();tt();li();sc=class extends gt{constructor(t){super(w.formDisplayConditions,t)}get Order(){let t=this.getProperty(g.Order);return _.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(g.Order,t.toString())}get FallbackForm(){return this.getProperty(g.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(g.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(w.formEveryOne)&&this.getChildren(w.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new rh(this))}},rh=class extends H{constructor(t){super(w.formEveryOne,t)}}});var lc,e_=T(()=>{"use strict";ee();tt();lc=class extends H{constructor(t,r){super(w.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(g.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(g.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(g.functionName)}set FunctionName(t){this.setProperty(g.functionName,t)}get LibraryName(){return this.getProperty(g.libraryNameEventHandler)}set LibraryName(t){this.setProperty(g.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(g.enabledForField)}set Enabled(t){this.setProperty(g.enabledForField,t)}get PassExecutionContext(){return this.getProperty(g.passExecutionContext)}set PassExecutionContext(t){this.setProperty(g.passExecutionContext,t)}get Parameters(){return this.getProperty(g.parameters)}set Parameters(t){this.setProperty(g.parameters,t)}}});var so,nh=T(()=>{"use strict";ee();Gs();so=class extends en{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(w.formCell);for(let a of i)r.push(a)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var zs,t_=T(()=>{"use strict";ee();nh();zs=class extends so{_customFooter;constructor(t,r){super(w.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var Ws,r_=T(()=>{"use strict";ee();nh();Ws=class extends so{_customHeader;constructor(t,r){super(w.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(g.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(g.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(g.showBody)}set showBody(t){t!=null&&this.setProperty(g.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(g.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(g.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var Vt,ji=T(()=>{"use strict";We();ht();ee();li();Vt=class e extends gt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(g.LCID)===t)return r.getProperty(g.text);return null}getAllTitles(){let t=this.getChildren(w.Titles);return t.length===0?[]:t[0].getChildren(w.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(g.LCID)===r){i.setProperty(g.text,t);return}let n=new e(w.Title,null);n.setProperty(g.text,t),n.setProperty(g.LCID,String(r)),this.addGrandChild(w.Titles,n)}get Sequence(){return+this.getProperty(g.Sequence)}set Sequence(t){this.setProperty(g.Sequence,t.toString())}get Area(){return this.getProperty(g.Area)}set Area(t){this.setProperty(g.Area,t)}set Id(t){this.setProperty(g.Id,t)}get Id(){return this.getProperty(g.Id)}get id(){return new L(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(g.icon)}set Icon(t){t=t||M.EmptyString,this.setProperty(g.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var js,n_=T(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(js||(js={}))});var uc,i_=T(()=>{"use strict";$e();ee();ji();n_();uc=class extends Vt{constructor(t){super(w.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return _.IsNullOrUndefined(r)?js.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):js.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var Se,K8,a_,nae,lo,ih=T(()=>{"use strict";We();ee();ji();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(Se||(Se={}));K8=new Map([[Se.Info,"Info"],[Se.Sales,"Sales"],[Se.Service,"Service"],[Se.Marketing,"Marketing"],[Se.ProcessCenter,"ProcessCenter"]]),a_=new Map([["Info",Se.Info],["Sales",Se.Sales],["Service",Se.Service],["Marketing",Se.Marketing],["ProcessCenter",Se.ProcessCenter]]),nae=new Map([[Se.Info,9e3],[Se.Sales,9200],[Se.Service,9400],[Se.Marketing,9600],[Se.ProcessCenter,9800],[Se.InternetMarketing,1e4],[Se.Async,10200]]),lo=class extends Vt{constructor(t,r){super(w.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=K8.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(w.formNavigation)}get AreaId(){return this.getProperty(g.Id)}set AreaId(t){this.setProperty(g.Id,t)}get id(){return new L(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var uo,ah=T(()=>{"use strict";ee();ji();uo=class extends Vt{constructor(t,r){super(w.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(w.formNavBarArea)}get ParentNavigation(){return this.getAncestor(w.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var cc,o_=T(()=>{"use strict";$e();ee();ji();cc=class extends Vt{RelationshipNameUCIRuntime;constructor(t){super(w.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(g.RelationshipName)}set RelationshipName(t){this.setProperty(g.RelationshipName,t)}set Show(t){this.setProperty(g.Show,String(t))}get Show(){let t=this.getProperty(g.Show);return _.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(g.TitleResourceId)}async toJSON(t){return{Area:this.Area,Show:this.Show||t.formModelService.showHiddenElements,Id:this.Id,Titles:[{Name:t.langCode.toString(),Value:this.getTitle(t.langCode)}],Sequence:this.Sequence.toString(),Privileges:[],TooltipTitles:[],AvailableOffline:!0,PreviewId:this.Id,RelationshipName:this.RelationshipNameUCIRuntime??this.RelationshipName,Icon:null,ViewId:null,Client:null,TitleResourceId:null}}}});var dc,s_=T(()=>{"use strict";ee();ji();dc=class extends Vt{constructor(t){super(w.formNavBarItem,t)}get Url(){return this.getProperty(g.url)}set Url(t){this.setProperty(g.url,t)}}});var pc,l_=T(()=>{"use strict";We();ee();ih();ah();ji();pc=class extends Vt{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(w.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Se.Info,Se.Sales,Se.Service,Se.Marketing,Se.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let a=new Set(i.map(o=>a_.get(o.AreaId)));n=n.filter(o=>!a.has(o))}}else{let i=new uo(w.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let a=new lo(w.formNavBarArea,this.navBarAreas);a.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(a)}),!0):!1}get navBar(){return this.getFirstChild(w.formNavBar)}get id(){return new L(Lf,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(w.formNavBarAreas,r),this.addGrandChildAtIndex(w.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let a of this.navBarAreas.AllNavBarAreaItems)n.push(a.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var u_={};pn(u_,{ControlType:()=>dr,DeserializationService:()=>lh,DeserializationServiceScope:()=>sh,DeserializedFormElementNode:()=>Gt});var oh,Gt,sh,dr,lh,Ym=T(()=>{"use strict";oh=ce(ki());We();$e();ht();Fa();kf();Li();zw();SA();Bu();YI();Vs();tc();qs();Hm();ee();ee();ZI();tt();Ir();Km();e_();t_();Jm();Qm();r_();Zm();eh();Gs();ic();i_();ih();ah();o_();s_();l_();Gt=class extends H{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},sh="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(dr||(dr={}));lh=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,a,o,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let f="";throw d.length===0?f="FormXml has no form node.":f="FormXml has multiple form nodes.",(0,oh.trackErrorTrace)(Et,{eventName:sh,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,a,o,s,l,u,c);return _.IsNullOrUndefined(p.displayCondition)&&s!==je.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Mi.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!_.IsNullOrUndefined(t)){let n=_.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,a,o,s,l,u,c){let d=new ac(r,n,i,a,o,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===je.Main&&(this.insertHeaderFooterElementProperties(w.formHeader,d,d.header),this.insertHeaderFooterElementProperties(w.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(_.IsNullOrUndefined(n)){let i=t===w.formHeader?new Ws(r,!0):new zs(r,!0);Gt.prototype.insertProperty.call(i,g.id,"{"+L.NewGuid()+"}"),Gt.prototype.insertProperty.call(i,g.Fieldlabelposition,"Top"),Gt.prototype.insertProperty.call(i,g.columnName,De.MarginalControlColumns),Gt.prototype.insertProperty.call(i,g.LabelWidth,De.LabelWidth),Gt.prototype.insertProperty.call(i,g.Fieldlabelalignment,"Left");let a=null,o=new zi(a);for(let s=0;s<i.maxColumns;s++){let l=new qt(o);Gt.prototype.insertProperty.call(l,g.id,"{"+L.NewGuid()+"}"),l.setDisplayName(M.EmptyString,this.lcid),Gt.prototype.insertProperty.call(l,g.showlabel,"false"),o.addCell(l)}i.appendRow(o),t===w.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new Gt(`<${t.nodeValue}`,r);if(t.nodeType===Node.COMMENT_NODE)return;let n=this.createModelNode(t,r);return this.populateElementProperties(n,t.attributes),this.populateElementChildren(n,t.childNodes),n}populateElementProperties(t,r){if(!r){let n="attributes is undefined for element: "+t.getNodeName();throw(0,oh.trackErrorTrace)(Et,{eventName:sh,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Gt.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===w.formCell&&i.name===g.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),a=this.deSerializeFormXmlNode(i,t);a&&Gt.prototype.insertChild.call(t,a)}}createModelNode(t,r){switch(t.nodeName){case w.form:throw new Error("Form node shouldn't be created using this method");case w.formTab:return new In(r);case w.formColumn:return new ui(r);case w.formHeader:return new Ws(r,!1);case w.formFooter:return new zs(r,!1);case w.formSection:return new en(w.formSection,r);case w.formRow:return new zi(r);case w.formCell:return new qt(r);case w.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,a;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===g.indicationOfSubgrid&&l.value==="true"||l.name===g.classid&&(l.value?.toLocaleUpperCase()===`{${I.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${I.ReferencePanelSubgridControl}}`))a=dr.Grid;else if(l.name===g.classid&&l.value?.toLocaleUpperCase()===`{${I.LookupControl}}`)a=dr.Lookup;else if(l.name===g.classid&&l.value?.toLocaleUpperCase()===`{${I.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===g.DefaultViewId&&(a=dr.Lookup)}return a===dr.Grid?new io(r):a===dr.Lookup?new ao(r):new Pr(r);case w.formEvent:return new no(r,M.EmptyString);case w.dependency:return this.populateDependencyTable(t),new ro(r,M.EmptyString);case w.Handler:let o=[];return new lc(o,r);case w.formNavigation:return new pc(t.nodeName,r);case w.formNavBarArea:return new lo(t.nodeName,r);case w.formNavBarAreas:return new uo(t.nodeName,r);case w.formNavBar:return new uc(r);case w.formNavBarByRelationshipItem:return new cc(r);case w.formNavBarItem:return new dc(r);case w.formDisplayConditions:return new sc(r);case w.library:return new oo(r,M.EmptyString,M.EmptyString);case w.controlDescription:return new Nu(r);case w.customControl:return this.populateCustomControlConfigurationId(t),new Mu(r);default:return new Gt(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===g.id&&this.upsertFieldCount(i.value,Qr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===g.id){let a=new L(i.value.substr(1,i.value.length-2));for(let o=0;o<t.parentNode.attributes.length;o++){let s=t.parentNode.attributes.item(o);if(s.name===g.ForControl){let l=s.value.substr(1,i.value.length-2);He.CustomControlIdMap.upsert(l,a);break}}break}}}}});var c_={};pn(c_,{SerializationService:()=>uh,SerializationServiceScope:()=>J8,SerializedFormElementNode:()=>co});var J8,co,uh,d_=T(()=>{"use strict";ht();tt();Ir();th();J8="SerializationService",co=class extends H{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},uh=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=co.prototype.fetchNodeName.call(t);if(r.charAt(0)===Nn.StartTag)return M.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return M.EmptyString;let n=co.prototype.enumerateProperties.call(t),i=co.prototype.enumerateChildren.call(t);if(!(t instanceof Wi)){let a=`<${r}`;if(n.length!==0&&(a+=` ${this.getPropertiesString(n)}`),i.length===0)a+=" />";else{let o=M.EmptyString;for(let s of i)o+=this.serializeFormXmlNode(s);a+=`>${o}</${r}>`}return a}return M.EmptyString}getPropertiesString(t){let r=M.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${M.EscapeXml(n.value,!0)}"`}),r}}});var I_=y(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.classIdForAttributeType=Wt.QUICK_VIEW_CLASS_ID=Wt.NOTES_CLASS_ID=Wt.SUBGRID_CLASS_ID=Wt.formRegistration=Wt.FormAdapter=void 0;var _n=(We(),Mr(Lw)),Q8=($e(),Mr(kw)),X8=(tt(),Mr(Bw)),rt=(ee(),Mr(Mw)),qe=(Li(),Mr(Uw)),Y8=(Ym(),Mr(u_)),Z8=(d_(),Mr(c_)),Ke=Kn(),p_=Nr(),zt=Cr(),e6=of(),po=lt(),vt=Xp(),f_=te(),fh=ae(),mh=Qn(),w_=ha(),t6={[rt.FormType.Main]:"Main",[rt.FormType.QuickCreate]:"QuickCreate",[rt.FormType.QuickViewForm]:"QuickView",[rt.FormType.Card]:"Card"},fc={Main:rt.FormType.Main,QuickCreate:rt.FormType.QuickCreate,QuickView:rt.FormType.QuickViewForm,Card:rt.FormType.Card},r6=new Map(Object.entries(qe.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function A_(e){var t;return e&&(t=r6.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Hs(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Hi(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function E_(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function hh(e,t){var r,n;let i=E_(e,"labels");if(!i)return"";let a=i.getAllChildren().filter(s=>s.getNodeName()==="label"),o=(r=a.find(s=>Hi(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return o&&(n=Hi(o).get("description"))!==null&&n!==void 0?n:""}function n6(e){let t=E_(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let a=n.getAllChildren()[0],o=a?a.getNodeName():"";o.charAt(0)==="<"&&(o=o.substring(1)),r[i]=o}return r}function C_(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function ch(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Ks(e){return String(e??"").replace(/[{}]/g,"")}function dh(e){return`{${Ks(e)}}`}function m_(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function hc(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),a=[];if(n.forEach((u,c)=>{c!==i&&a.push({i:c,node:(0,Ke.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Hs(e),c:a}};let o=n[i],s=[],l=[];return o.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,Ke.rawFromNode)(u)})}),{modeled:s,bag:{a:Hs(e),c:a,w:{n:o.getNodeName(),a:Hs(o),c:l}}}}function S_(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((a,o)=>{a.getNodeName()===t&&(!r||n.length===0)?n.push(a):i.push({i:o,node:(0,Ke.rawFromNode)(a)})}),{modeled:n,bag:{a:Hs(e),c:i}}}function h_(e,t){let{modeled:r,bag:n}=hc(e,"tabs","tab");return{tabs:r.map(i=>i6(i,t)),bag:n}}function i6(e,t){var r,n;let i=Hi(e),{modeled:a,bag:o}=hc(e,"columns","column");return{id:(r=i.get("id"))!==null&&r!==void 0?r:"",name:(n=i.get("name"))!==null&&n!==void 0?n:"",label:hh(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:a.map(s=>a6(s,t)),bag:o}}function a6(e,t){let r=Hi(e),{modeled:n,bag:i}=hc(e,"sections","section");return{width:r.get("width"),sections:n.map(a=>o6(a,t)),bag:i}}function o6(e,t){var r,n,i;let a=Hi(e),{modeled:o,bag:s}=hc(e,"rows","row");return{id:(r=a.get("id"))!==null&&r!==void 0?r:"",name:(n=a.get("name"))!==null&&n!==void 0?n:"",label:hh(e,t),visible:a.has("visible")?a.get("visible")==="true":!0,showLabel:a.get("showlabel")==="true",columns:C_((i=a.get("columns"))!==null&&i!==void 0?i:"1"),rows:o.map(l=>s6(l,t)),bag:s}}function s6(e,t){let{modeled:r,bag:n}=S_(e,"cell",!1);return{cells:r.map(i=>l6(i,t)),bag:n}}function l6(e,t){var r;let n=Hi(e),{modeled:i,bag:a}=S_(e,"control",!0),o=hh(e,t),s=n.get("showlabel")==="true",l=i[0]?u6(i[0],o,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:m_(n.get("colspan"),1),rowspan:m_(n.get("rowspan"),1),control:l,bag:a}}function u6(e,t,r){var n,i;let a=Hi(e),o=Ks((n=a.get("classid"))!==null&&n!==void 0?n:""),s=a.get("datafieldname");return{id:(i=a.get("id"))!==null&&i!==void 0?i:"",classId:o,fieldName:s||null,type:A_(o),isRequired:a.get("isrequired")==="true",isReadOnly:a.get("disabled")==="true",label:t,showLabel:r,parameters:n6(e),bag:{a:Hs(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,Ke.rawFromNode)(l)}))}}}function pi(e){return e.a.length===0&&e.c.length===0&&!e.w}function N_(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Ki(e,t){var r;let n=new Set(e.a.map(o=>o[0])),i=pi(e),a=[];for(let o of t)if(n.has(o.key)){let s=(r=N_(e,o.key))!==null&&r!==void 0?r:"";o.matches(s)||a.push([o.key,o.render()])}else i?a.push([o.key,o.render()]):o.matches(o.absentDefault)||a.push([o.key,o.render()]);return(0,Ke.mergeAttrs)(e.a,a)}var ci=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),di=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),g_=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function gc(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function ph(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,fh.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function c6(e,t){var r,n;let i=e.c.find(o=>o.n==="label"&&o.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),a=i??e.c.find(o=>o.n==="label");return(n=(r=a?.a.find(o=>o[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function d6(e,t,r){let n=!1,i=e.c.map(a=>a.n!=="label"||!a.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?a:(n=!0,{...a,a:a.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function gh(e,t,r){let n=e.c.findIndex(a=>a.node.n==="labels");if(n<0){if(!t||pi(e))return e;let o=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:gc(t,r)},...o]}}if(c6(e.c[n].node,r)===t)return e;let i=d6(e.c[n].node,t,r);return{...e,c:e.c.map((a,o)=>o===n?{...a,node:i}:a)}}function p6(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],a=i?i.n:"";a.charAt(0)==="<"&&(a=a.substring(1)),t[n]=a}return t}function f6(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function m6(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function h6(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||pi(e))return e;let i=e.c.reduce((a,o)=>o.i>a?o.i:a,-1);return{...e,c:[...e.c,{i:i+1,node:ph(t)}]}}if(f6(p6(e.c[r].node),t))return e;let n=ph(t);return{...e,c:e.c.map((i,a)=>a===r?{...i,node:n}:i)}}function vc(e,t,r,n){if(e.w){let o={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,Ke.spliceChildren)(e.w.c,r)};return(0,Ke.spliceChildren)(e.c,[o])}let i=n(),a={n:t,a:[],c:r};return e.c.length===0?[...i,a]:(0,Ke.spliceChildren)(e.c,[...i,a])}function g6(e,t){let r=e.tabs.map(n=>v6(n,t));return{n:"form",a:Ki(e.bag,[]),c:e.tabs.length===0&&pi(e.bag)?[]:vc(e.bag,"tabs",r,()=>[])}}function v6(e,t){let r=[ci("id",e.id),ci("name",e.name),di("expanded",e.expanded),di("visible",e.visible,!0)],n=e.columns.map(a=>y6(a,t)),i=gh(e.bag,e.label,t);return{n:"tab",a:Ki(i,r),c:vc(i,"columns",n,()=>e.label?[gc(e.label,t)]:[])}}function y6(e,t){let r=e.width!==void 0?[ci("width",e.width)]:[],n=e.sections.map(i=>b6(i,t));return{n:"column",a:Ki(e.bag,r),c:vc(e.bag,"sections",n,()=>[])}}function b6(e,t){let r=[ci("id",e.id),ci("name",e.name),di("showlabel",e.showLabel),di("visible",e.visible,!0),{key:"columns",matches:a=>C_(a)===e.columns,render:()=>ch(e.columns),absentDefault:ch(1)}],n=e.rows.map(a=>w6(a,t)),i=gh(e.bag,e.label,t);return{n:"section",a:Ki(i,r),c:vc(i,"rows",n,()=>e.label?[gc(e.label,t)]:[])}}function w6(e,t){let r=e.cells.map(n=>A6(n,t));return{n:"row",a:Ki(e.bag,[]),c:pi(e.bag)?r:(0,Ke.assembleChildren)(e.bag,r)}}function A6(e,t){let r=e.control?e.control.showLabel:N_(e.bag,"showlabel")==="true",n=[ci("id",e.id),di("showlabel",r),di("visible",e.visible,!0),g_("colspan",e.colspan),g_("rowspan",e.rowspan)],i=e.control?[E6(e.control)]:[],a;if(pi(e.bag))a=[...e.control&&e.control.label?[gc(e.control.label,t)]:[],...i];else{let o=e.control?gh(e.bag,e.control.label,t):e.bag;a=(0,Ke.assembleChildren)(o,i)}return{n:"cell",a:Ki(e.bag,n),c:a}}function E6(e){let t=[ci("id",e.id),{key:"classid",matches:i=>Ks(i)===e.classId,render:()=>dh(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(ci("datafieldname",e.fieldName)),t.push(di("disabled",e.isReadOnly)),t.push(di("isrequired",e.isRequired));let r=e.fieldName===null?m6(e.bag,"datafieldname"):e.bag,n;return pi(r)?n=Object.keys(e.parameters).length>0?[ph(e.parameters)]:[]:n=(0,Ke.assembleChildren)(h6(r,e.parameters),[]),{n:"control",a:Ki(r,t),c:n}}var C6={make:(e,t)=>new X8.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function v_(e,t,r,n){(0,mh.installDomShim)();let i=N6(e,r);(0,vt.reconcileEmbedDescriptions)(i,n);let a=(0,Ke.rebuildRaw)(g6(i,t),C6,null);return new Z8.SerializationService(t).serializeFormXmlNode(a)}function S6(e){return JSON.parse(JSON.stringify(e))}function N6(e,t){var r;let n=S6(e);n.bag||(n.bag=(0,Ke.emptyBag)()),x6(n.bag),t&&D6(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])I6(i);return n}function D6(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";vh(e,i=>{let a=i.fieldName,o=i;if(!a||o.label!==void 0&&o.classId!==void 0)return;let s=t.resolveField(n,a);s&&(o.label===void 0&&s.displayName&&(o.label=s.displayName),o.classId===void 0&&s.attributeType&&(o.classId=D_(s.attributeType)))})}function y_(e){let t=[];return vh(e,r=>t.push(r)),t}function vh(e,t){var r,n,i,a,o;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(a=u.rows)!==null&&a!==void 0?a:[])for(let d of(o=c.cells)!==null&&o!==void 0?o:[])d.control&&t(d.control)}function I6(e){e.id||(e.id=_n.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.expanded===void 0&&(e.expanded=!0),e.visible===void 0&&(e.visible=!0),e.columns||(e.columns=[]);for(let t of e.columns)_6(t);e.bag||(e.bag=(0,Ke.emptyBag)())}function _6(e){e.sections||(e.sections=[]);for(let t of e.sections)T6(t);e.bag||(e.bag=(0,Ke.emptyBag)()),e.width===void 0&&pi(e.bag)&&(e.width="100%")}function T6(e){e.id||(e.id=_n.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.showLabel===void 0&&(e.showLabel=!1),e.visible===void 0&&(e.visible=!0),e.columns===void 0&&(e.columns=1),e.rows||(e.rows=[]);for(let t of e.rows)P6(t);e.bag||(e.bag=(0,Ke.emptyBag)())}function P6(e){e.cells||(e.cells=[]);for(let t of e.cells)R6(t);e.bag||(e.bag=(0,Ke.emptyBag)())}function R6(e){(0,vt.hasGenPage)(e.control)&&(0,vt.applyEmbedCellDefaults)(e),e.id||(e.id=_n.Guid.NewGuid()),e.visible===void 0&&(e.visible=!0),e.colspan===void 0&&(e.colspan=1),e.rowspan===void 0&&(e.rowspan=1),e.control===void 0&&(e.control=null),e.control&&O6(e.control),e.bag||(e.bag=(0,Ke.emptyBag)())}function O6(e){var t;(0,vt.hasGenPage)(e)&&(0,vt.applyEmbedControlDefaults)(e),e.id||(e.id=_n.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(qe.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":A_(String(e.classId))),e.isRequired===void 0&&(e.isRequired=!1),e.isReadOnly===void 0&&(e.isReadOnly=!1),e.label===void 0&&(e.label=(t=e.fieldName)!==null&&t!==void 0?t:""),e.showLabel===void 0&&(e.showLabel=!0),(e.parameters===void 0||e.parameters===null)&&(e.parameters={});for(let r of Object.keys(e.parameters))(0,fh.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,Ke.emptyBag)())}function x6(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let a of i.c)a.n==="Handler"&&!b_(a,"handlerUniqueId")&&a.a.push(["handlerUniqueId",dh(_n.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!b_(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",dh(_n.Guid.NewGuid())])}}var mc=class{constructor(t=w_.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,a;let{tabs:o,bag:s}=h_(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(a=t6[t.formType])!==null&&a!==void 0?a:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:o,bag:s};return(0,vt.projectGenPageEmbeds)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:v_(t,this.lcid),formid:t.id||(0,po.newId)(),objecttypecode:t.entityLogicalName,type:fc[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:rt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?rt.FormActivationState.Active:rt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,a,o,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d=this.deserialize({formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,po.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(a=u.name)!==null&&a!==void 0?a:"",uniquename:(o=u.uniquename)!==null&&o!==void 0?o:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate});return L6(this.toArtifact(d,(l=u.description)!==null&&l!==void 0?l:void 0),c)}toApiPayload(t,r,n){let i=(0,vt.genPageEmbedIssues)(t);if(i.length>0)throw new f_.ValidationError("form",t.id,i);return{formxml:v_(t,this.lcid,n,r),name:t.name,type:fc[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Set,i=[];return vh(t,a=>{let o=a.fieldName,s=a;!o||s.label!==void 0&&s.classId!==void 0||n.has(o)||(n.add(o),i.push({entityLogicalName:r,fieldName:o}))}),i}createDefault(t){var r,n,i,a,o,s,l,u,c,d,p;let f=(0,vt.genPageEmbedIssues)(t);if(f.length>0)throw new f_.ValidationError("form",t.id||"(new)",f);let m=t.tabs&&t.tabs.length>0?void 0:W6(this.lcid),h=m!==void 0?m:t.tabs.map(E=>k6(E,this.lcid)).join(""),v=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,po.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:fc[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(a=t.name)!==null&&a!==void 0?a:"New Form",description:(o=t.description)!==null&&o!==void 0?o:"",formpresentation:rt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?rt.FormActivationState.Active:rt.FormActivationState.InActive}),b=this.toArtifact(v,t.description);if(t.tabs&&t.tabs.length>0){let E=y_(t);y_(b).forEach((C,N)=>{E[N]&&E[N].label===void 0&&delete C.label,E[N]&&E[N].genPage!==void 0&&(C.genPage=JSON.parse(JSON.stringify(E[N].genPage)))})}return{id:(l=t.id)!==null&&l!==void 0?l:b.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,po.assignMissingIds)(t)}normalize(t){return(0,vt.mintEmbedIdentity)(t)}committed(t,r){var n,i,a,o,s,l;let u=r?.formxml;if(typeof u!="string"||!(0,vt.mayCommitEmbedState)(t))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,po.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:fc[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(a=t.name)!==null&&a!==void 0?a:"",uniquename:(o=t.name)!==null&&o!==void 0?o:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:rt.FormPresentation.AirForm,formactivationstate:rt.FormActivationState.Active}),{bag:d}=h_(c,this.lcid),p=(0,vt.commitEmbedState)(t,(l=(0,vt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node);return{artifact:p,baseline:p}}validate(t){return ez(t)}deserialize(t){(0,mh.installDomShim)();let r=Q8.ScriptUtilities.ParseXml(t.formxml),n=new Y8.DeserializationService(this.lcid).deSerializeFormXml(r,new _n.Guid(t.formid),t.objecttypecode,rt.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!n)throw new Error("FormXml could not be deserialized into a Form model.");return n}readActivationStatus(t){return t.formactivationstate===rt.FormActivationState.InActive?"Inactive":"Active"}};Wt.FormAdapter=mc;function F6(e){var t;(0,mh.installDomShim)();let r=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function L6(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=F6(t),i=["header","footer"].filter(o=>!n.has(o)),a=e.bag.c.filter(o=>{var s;return i.includes((s=o?.node)===null||s===void 0?void 0:s.n)}).map(o=>o.i);return a.length>0&&(e.bag.c=e.bag.c.filter(o=>{var s;return!i.includes((s=o?.node)===null||s===void 0?void 0:s.n)}).map(o=>({...o,i:o.i-a.filter(s=>s<o.i).length}))),e}function Rr(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function yh(e,t){return e?`<labels><label description="${Rr(e)}" languagecode="${t}" /></labels>`:""}function bh(e){return e&&e.length>0?Ks(e):(0,po.newId)()}function k6(e,t){var r,n,i,a;let o=(r=e.columns)!==null&&r!==void 0?r:[],s=(o.length>0?o:[z6()]).map(l=>M6(l,t)).join("");return`<tab id="{${Rr(bh(e.id))}}" name="${Rr((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}">${yh(e.label,t)}<columns>${s}</columns></tab>`}function M6(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(a=>B6(a,t)).join("");return`<column width="${Rr((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function B6(e,t){var r,n,i,a,o;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>U6(l,t)).join("");return`<section id="{${Rr(bh(e.id))}}" name="${Rr((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(a=e.visible)!==null&&a!==void 0?a:!0}" columns="${ch((o=e.columns)!==null&&o!==void 0?o:1)}">${yh(e.label,t)}<rows>${s}</rows></section>`}function U6(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>$6(n,t)).join("")}</row>`}function $6(e,t){var r,n,i,a,o;let s=q6(e),l=s.control,u=l?yh((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?V6(l):"";return`<cell id="{${Rr(bh(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(a=s.colspan)!==null&&a!==void 0?a:1}" rowspan="${(o=s.rowspan)!==null&&o!==void 0?o:1}">${u}${c}</cell>`}function q6(e){if(!(0,vt.hasGenPage)(e.control))return e;let t={...e.control};(0,vt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,vt.applyEmbedCellDefaults)(r),r}function V6(e){var t,r,n;let i=e.fieldName?` datafieldname="${Rr(e.fieldName)}"`:"",a=G6(e.parameters),o=e.classId?Ks(e.classId):String(qe.ControlClassId.TextboxControl);return`<control id="${Rr((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Rr(o)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${a}</control>`}function G6(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,fh.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Rr(e[n])}</${n}>`).join("")}</parameters>`)}function z6(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function W6(e){return`<tab id="{${_n.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${_n.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${e}" /></labels><rows></rows></section></sections></column></columns></tab>`}function j6(e=w_.DEFAULT_LCID){return{adapter:new mc(e),api:e6.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,p_.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,p_.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Wt.formRegistration=j6;var H6=new Set(["id","name","label","expanded","visible","columns","bag"]),K6=new Set(["id","width","sections","bag"]),J6=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),Q6=new Set(["id","cells","bag"]),X6=new Set(["id","visible","colspan","rowspan","control","bag"]),Y6=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","bag"]),Z6={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function ez(e){let t=[];return(0,zt.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let a=`/tabs/${i}`;(0,zt.rejectUnknownKeys)(n,H6,a,"tab",t),(0,zt.childObjects)(n,"columns",a,"column",t).forEach(({node:s,index:l})=>{let u=`${a}/columns/${l}`;(0,zt.rejectUnknownKeys)(s,K6,u,"column",t),(0,zt.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:p})=>{let f=`${u}/sections/${p}`;(0,zt.rejectUnknownKeys)(d,J6,f,"section",t),(0,zt.childObjects)(d,"rows",f,"row",t).forEach(({node:h,index:v})=>{let b=`${f}/rows/${v}`;(0,zt.rejectUnknownKeys)(h,Q6,b,"row",t),(0,zt.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:N})=>{let R=`${b}/cells/${N}`;(0,zt.rejectUnknownKeys)(C,X6,R,"cell",t,Z6);let O=C.control;O!=null&&!(0,zt.isJsonObject)(O)?t.push((0,zt.issue)(`${R}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof O}`)):(0,zt.isJsonObject)(O)&&(0,zt.rejectUnknownKeys)(O,Y6,`${R}/control`,"control",t)})})})})}),t.push(...(0,vt.genPageEmbedIssues)(e)),t}Wt.SUBGRID_CLASS_ID=qe.ControlClassId.SubgridControl;Wt.NOTES_CLASS_ID=qe.ControlClassId.TimelineControl;Wt.QUICK_VIEW_CLASS_ID=qe.ControlClassId.QuickViewControl;var tz={Lookup:String(qe.ControlClassId.LookupControl),Customer:String(qe.ControlClassId.LookupControl),Owner:String(qe.ControlClassId.LookupControl),PartyList:String(qe.ControlClassId.PartyListControl),Boolean:String(qe.ControlClassId.BooleanControl),DateTime:String(qe.ControlClassId.DateTimeControl),Decimal:String(qe.ControlClassId.DecimalControl),Double:String(qe.ControlClassId.FloatingNumberControl),Money:String(qe.ControlClassId.CurrencyControl),Integer:String(qe.ControlClassId.IntegerControl),BigInt:String(qe.ControlClassId.IntegerControl),Memo:String(qe.ControlClassId.TextAreaControl),String:String(qe.ControlClassId.TextboxControl)},rz="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function D_(e){return e==="Picklist"||e==="State"||e==="Status"?rz:e&&tz[e]||String(qe.ControlClassId.TextboxControl)}Wt.classIdForAttributeType=D_;function b_(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var wh=y(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.viewApi=fo.findDefaultViews=void 0;var T_=Pt(),Xt=be(),tn=ae(),nz="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",iz="savedqueryid,name,returnedtypecode,querytype,isdefault";async function az(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),a=`returnedtypecode eq '${(0,tn.odataLiteral)(t)}' and querytype eq 0`,o=`/savedqueries${(0,tn.odataQuery)([["$select","savedqueryid,name,isdefault"],["$filter",a]])}`;return(await(0,T_.collectPages)(e,o,`findDefaultViews('${t}')`)).filter(l=>{var u;return l.savedqueryid&&!i.has(l.savedqueryid)&&(l.isdefault||/^(Active|Inactive)\b/i.test((u=l.name)!==null&&u!==void 0?u:""))}).map(l=>{var u;return{id:String(l.savedqueryid),name:String((u=l.name)!==null&&u!==void 0?u:"")}})}fo.findDefaultViews=az;async function oz(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,tn.odataPathLiteral)(t)}')${(0,tn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let a=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof a=="number"?a:void 0}}async function __(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await oz(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}fo.viewApi={async get(e,t){let r=(0,tn.normalizeGuid)(t,"id"),n=await(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,tn.odataQuery)([["$select",nz]]);return{raw:(0,Xt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",(0,tn.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueries${(0,tn.odataQuery)([["$select",iz],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,tn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,T_.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var a,o;return{type:"view",id:(a=i.savedqueryid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Xt.echoWrite)("savedqueryid"),a=`/savedqueries${i.query}`,o=await __(e,n.layoutxml,n.returnedtypecode),s=(0,Xt.ensureSuccess)(await e.post(a,(0,Xt.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:o,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r),i.options),e.apiUrl(a));return{id:(0,Xt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Xt.readEtag)(s)}},async update(e,t,r,n){let i=r,a=(0,tn.normalizeGuid)(t,"id"),o=(0,Xt.echoWrite)("savedqueryid",{"If-Match":(0,Xt.requireEtag)(n,"view",a)}),s=`/savedqueries(${a})${o.query}`,l=await __(e,i.layoutxml,i.returnedtypecode),u=(0,Xt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},o.options),e.apiUrl(s));return{id:a,etag:(0,Xt.readEtag)(u)}},delete(e,t){return(0,Xt.deleteRecord)(e,"savedqueries",t)}}});var z_=y(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.viewRegistration=mo.ViewAdapter=void 0;var k_=te(),Yt=Cr(),Ah=Kn(),Ji=_i(),P_=Nr(),sz=wh(),Eh=Qn(),lz=lt(),M_=100,bc=class{toArtifact(t){var r,n,i,a,o,s,l,u;(0,Eh.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,Ji.parseXmlRoot)(c,"<fetch/>"),f=(0,Ji.parseXmlRoot)(d,"<grid/>"),m=U_(p);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(a=t.name)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:cz(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:B_(f,p),filters:q_(p),sort:$_(p),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,Ji.projectElementBag)(p):void 0,layoutBag:d?(0,Ji.projectElementBag)(f):void 0}}fromArtifact(t){(0,Eh.installDomShim)();let{fetchxml:r,layoutxml:n}=R_(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,a,o;(0,Eh.installDomShim)();let{fetchxml:s,layoutxml:l}=R_(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(a=t.queryType)!==null&&a!==void 0?a:0,isdefault:(o=t.isDefault)!==null&&o!==void 0?o:!1}}createDefault(t){var r,n,i,a,o,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,lz.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:c,queryType:(o=t.queryType)!==null&&o!==void 0?o:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,Yt.childObjects)(n,"columns","","column",r),(0,Yt.childObjects)(n,"sort","","sort",r),(0,Yt.childObjects)(n,"linkEntities","","linkEntity",r),uz(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Yt.isJsonObject)(i)?Ch(i,"/filters",r):r.push((0,Yt.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};mo.ViewAdapter=bc;function uz(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Yt.isJsonObject)(r))return;for(let a of["name","from","to"]){let o=r[a];(typeof o!="string"||o.trim()==="")&&t.push((0,Yt.issue)(`/linkEntities/${n}/${a}`,"linkentity-needs-keys",`a join needs a non-empty '${a}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(o)}.`))}let i=r.filters;i!=null&&((0,Yt.isJsonObject)(i)?Ch(i,`/linkEntities/${n}/filters`,t):t.push((0,Yt.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Ch(e,t,r){(0,Yt.childObjects)(e,"conditions",t,"condition",r),(0,Yt.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:a})=>Ch(i,`${t}/groups/${a}`,r))}function cz(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function B_(e,t){var r;let n=Sh(t),i=e.getElementsByTagName("cell"),a=[],o=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?M_:c,order:o},p=n.get(u);p&&(d.relatedEntity=p.linkKey,p.attributeName&&p.attributeName!==u&&(d.sourceAttribute=p.attributeName)),o+=1,a.push(d)}return a}function Sh(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],a=i.getAttribute("name");if(!a)continue;let o=i.getElementsByTagName("attribute");for(let s=0;s<o.length;s+=1){let l=o[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||a,linkName:a,attributeName:u,link:i})}}return t}function U_(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of yt(t,"link-entity")){let i=n.getAttribute("name"),a=n.getAttribute("from"),o=n.getAttribute("to");if(!i||!a||!o)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=yt(n,"filter").find(c=>!wc(c));r.push({name:i,from:a,to:o,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Nh(u)}:{}})}return r}function $_(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];if(o.nodeType===1&&o.tagName==="order"){let s=o.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=o.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:o.getAttribute("entityname")||""})}}return n}function q_(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=yt(t,"filter").filter(i=>!wc(i)).map(Nh);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function wc(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(yt(e,"filter").length>0)return!1;let t=yt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||yt(r,"value").length>0||pz(r))}var dz=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function pz(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!dz.has(i))return!0}return!1}function Nh(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],a=[],o=e.childNodes;for(let s=0;s<o.length;s+=1){let l=o[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let p=l.getAttribute("entityname")||"";p&&(c.entityname=p),i.push(c)}else l.tagName==="filter"&&a.push(Nh(l))}return{type:n,conditions:i,groups:a}}function yt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName===t&&r.push(a)}return r}var Dh=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function fz(e,t){let r=Sh(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let a=r.get(i.name);if(a){let o=Dh(i),s=n.get(o);s?s.push(a.link):n.set(o,[a.link])}}return n}function mz(e,t,r,n){if(!n||n.size===0)return;let i=new Set,a=t.getElementsByTagName("link-entity");for(let s=0;s<a.length;s+=1)i.add(a[s]);let o=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Dh(s));return!!l&&l.some(u=>!i.has(u))});if(o.length!==0)throw new k_.ValidationError("view",e.id,o.map(s=>(0,Yt.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function R_(e){let t=hz(e.columns);if(!O_(e.fetchBag)||!O_(e.layoutBag))return{fetchxml:Iz({...e,columns:t}),layoutxml:_z({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=x_(e.fetchBag,"fetch",r),i=x_(e.layoutBag,"grid",r),a=B_(i,n),o=!yc(t,a),s=!yc(e.sort,$_(n)),l=!yc(e.filters,q_(n)),u=e.linkEntities,c=u!==void 0&&!yc(u,U_(n)),d=c?fz(n,a):void 0;return c&&Sz(r,n,u),c&&(Dz(e,n,t,d),mz(e,n,t,d)),o?(F_(r,n,t,a),bz(r,i,t)):c&&F_(r,n,t,a),s&&Ez(r,n,e.sort),l&&Cz(r,n,e.filters),{fetchxml:(0,Ji.serializeNode)(n),layoutxml:(0,Ji.serializeNode)(i)}}function hz(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:M_,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function O_(e){return!!e&&(e.c.length>0||e.a.length>0)}function x_(e,t,r){let n={n:t,a:(0,Ah.mergeAttrs)(e.a,[]),c:(0,Ah.spliceChildren)(e.c,[])};return(0,Ah.rebuildRaw)(n,(0,Ji.domEngine)(r),null)}function F_(e,t,r,n){var i,a;let o=t.getElementsByTagName("entity")[0];if(!o)return;let s=d=>{var p,f;return`${(p=d.relatedEntity)!==null&&p!==void 0?p:""}:${d.name}:${(f=d.sourceAttribute)!==null&&f!==void 0?f:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||gz(o,d);let u=Sh(t),c=new Set(yt(o,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((p,f)=>p.order-f.order))if(d.relatedEntity){let p=u.get(d.name);if(p&&p.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(p.linkKey===d.relatedEntity||p.linkName===d.relatedEntity||!G_(o,d.relatedEntity)))continue;let f=vz(e,o,d.relatedEntity),m=e.createElement("attribute");V_(m,d),f.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:f.getAttribute("name")||d.relatedEntity,attributeName:(a=d.sourceAttribute)!==null&&a!==void 0?a:d.name,link:f})}else{if(c.has(d.name))continue;let p=e.createElement("attribute");p.setAttribute("name",d.name),yz(o,p),c.add(d.name)}}function V_(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function gz(e,t){if(t.relatedEntity){for(let r of yt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of yt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of yt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function G_(e,t,r=!1){let n=a=>a.getAttribute("alias")===t||a.getAttribute("name")===t;for(let a of yt(e,"link-entity"))if(n(a))return a;if(r)return;let i=e.getElementsByTagName("link-entity");for(let a=0;a<i.length;a+=1)if(n(i[a]))return i[a]}function vz(e,t,r){let n=G_(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function yz(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function bz(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),a=wz(n);if(Az(a,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);a[s].getAttribute("width")!==l&&a[s].setAttribute("width",l)}return}let o=new Map;for(let s of a){let l=s.getAttribute("name");l&&o.set(l,s),n.removeChild(s)}for(let s of i){let l=o.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function wz(e){return yt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Az(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].getAttribute("name")!==t[r].name)return!1;return!0}function Ez(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(p,f)=>`${p.toLowerCase()}\0${f.toLowerCase()}`,a=new Map,o=new Map,s=(p,f,m)=>{let h=p.get(f);h?h.push(m):p.set(f,[m])};for(let p of yt(n,"order")){let f=p.getAttribute("attribute")||"";f&&(s(a,i(p.getAttribute("entityname")||"",f),p),s(o,f.toLowerCase(),p)),n.removeChild(p)}let l=new Set,u=(p,f)=>{let m=p.get(f);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=p=>{var f;let m=o.get(p.toLowerCase());if(!m)return;let h=m.filter(b=>!l.has(b)),v=(f=h.find(b=>!b.getAttribute("entityname")))!==null&&f!==void 0?f:h[0];return v&&l.add(v),v},d=r.map(p=>{let f=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:u(a,i(p.entityname,f))}});for(let p of d)p.expression.entityname===void 0&&(p.element=c(String(p.expression.attribute)));for(let{expression:p,element:f}of d){let m=f??e.createElement("order");m.setAttribute("attribute",p.attribute),m.setAttribute("descending",String(p.descending)),p.entityname?m.setAttribute("entityname",p.entityname):p.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function Cz(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of yt(n,"filter"))wc(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Js(e,r))}}function yc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Sz(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let a=yt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),o=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,v)=>{if(s[v])return;let b=a.filter(N=>!l.has(N)&&m(N,h));if(b.length!==1)return;let E=b[0];r.some((N,R)=>R!==v&&!s[R]&&m(E,N))||(s[v]=E,l.add(E))})};u((m,h)=>!!h.alias&&o(m,"name")===h.name&&o(m,"alias")===h.alias),u((m,h)=>o(m,"name")===h.name&&o(m,"from")===h.from&&o(m,"to")===h.to),u((m,h)=>o(m,"name")===h.name&&o(m,"from")===h.from),u((m,h)=>o(m,"name")===h.name&&o(m,"to")===h.to),u((m,h)=>o(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=a.filter(m=>!l.has(m)),p=new Map;for(let m of d){let h=p.get(o(m,"name"));h?h.push(m):p.set(o(m,"name"),[m])}let f=new Map;for(let m of c){let h=f.get(r[m].name);h?h.push(m):f.set(r[m].name,[m])}for(let[m,h]of f){let v=(n=p.get(m))!==null&&n!==void 0?n:[];v.length===h.length&&h.forEach((b,E)=>{s[b]=v[E],l.add(v[E])})}r.forEach((m,h)=>{let v=s[h];if(v){L_(e,v,m);return}let b=e.createElement("link-entity");L_(e,b,m),i.appendChild(b)});for(let m of a)l.has(m)||i.removeChild(m)}var Nz=new Set(["inner","outer"]);function Dz(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let a=new Set,o=t.getElementsByTagName("link-entity");for(let c=0;c<o.length;c+=1){let d=o[c],p=d.getAttribute("name"),f=d.getAttribute("alias");p&&a.add(p),f&&a.add(f)}let s=new Set;for(let c=0;c<o.length;c+=1)s.add(o[c]);let l=c=>{let d=n?.get(Dh(c));return!!d&&d.every(p=>s.has(p))},u=r.filter(c=>c.relatedEntity&&!a.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new k_.ValidationError("view",e.id,u.map(c=>{var d;let p=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(f=>f.name===c.relatedEntity||f.alias===c.relatedEntity);return(0,Yt.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(p?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function L_(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):Nz.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=yt(t,"filter").find(a=>!wc(a)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Js(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function Iz(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let a=new Map;for(let o of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",o.name),s.setAttribute("from",o.from),s.setAttribute("to",o.to),o.alias&&s.setAttribute("alias",o.alias),o.linkType&&s.setAttribute("link-type",o.linkType),o.filters&&(o.filters.conditions.length>0||o.filters.groups.length>0)&&s.appendChild(Js(r,o.filters)),i.appendChild(s);for(let l of[o.alias||o.name,o.name])a.has(l)||a.set(l,s)}for(let o of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(o.relatedEntity){V_(s,o);let l=a.get(o.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",o.relatedEntity),i.appendChild(l),a.set(o.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",o.name),i.appendChild(s)}for(let o of e.sort){let s=r.createElement("order");s.setAttribute("attribute",o.attribute),s.setAttribute("descending",String(o.descending)),o.entityname&&s.setAttribute("entityname",o.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(Js(r,e.filters)),new XMLSerializer().serializeToString(r)}function Js(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(Js(e,n));return r}function _z(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,a=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=a[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let o=n.createElement("row");o.setAttribute("name","result"),o.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(o);for(let s of a){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),o.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Tz(){return{adapter:new bc,api:sz.viewApi,publish:(e,t,r)=>(0,P_.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,P_.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}mo.viewRegistration=Tz});function Ac(e,t){return e==="SetFieldValue"&&t!==void 0&&Pz.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Pz,Ih=T(()=>{"use strict";Pz=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function W_(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function _h(e){return e==="AllForms"||W_(e)?1:2}function Th(e){return W_(e)?e:null}function j_(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:ho.WorkflowCategory.BusinessRule,type:ho.WorkflowTypeCode.Definition,mode:1,scope:ho.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:_h(e.scope),processtriggerformid:Th(e.scope)}}var ho,H_=T(()=>{"use strict";ho=ce(Ai());});function K_(e,t=0){return(ct[e[t+0]]+ct[e[t+1]]+ct[e[t+2]]+ct[e[t+3]]+"-"+ct[e[t+4]]+ct[e[t+5]]+"-"+ct[e[t+6]]+ct[e[t+7]]+"-"+ct[e[t+8]]+ct[e[t+9]]+"-"+ct[e[t+10]]+ct[e[t+11]]+ct[e[t+12]]+ct[e[t+13]]+ct[e[t+14]]+ct[e[t+15]]).toLowerCase()}var ct,J_=T(()=>{ct=[];for(let e=0;e<256;++e)ct.push((e+256).toString(16).slice(1))});function Ph(){return Ec>Cc.length-16&&((0,Q_.randomFillSync)(Cc),Ec=0),Cc.slice(Ec,Ec+=16)}var Q_,Cc,Ec,X_=T(()=>{Q_=require("crypto"),Cc=new Uint8Array(256),Ec=Cc.length});var Y_,Rh,Z_=T(()=>{Y_=require("crypto"),Rh={randomUUID:Y_.randomUUID}});function Rz(e,t,r){if(Rh.randomUUID&&!t&&!e)return Rh.randomUUID();e=e||{};let n=e.random??e.rng?.()??Ph();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return K_(n)}var Nt,eT=T(()=>{Z_();X_();J_();Nt=Rz});var Oh=T(()=>{eT()});var tT=T(()=>{"use strict";});var xh=y(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.WorkflowConditionOperator=pr.WorkflowAttributeType=pr.SystemStep=pr.FieldRequiredLevelTypes=pr.AttributeDateTimeBehavior=void 0;pr.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};pr.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};pr.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};pr.WorkflowAttributeType={Boolean:"0",Customer:"1",DateTime:"2",Decimal:"3",Float:"4",Integer:"5",Lookup:"6",Money:"7",Owner:"8",PartyList:"9",Picklist:"10",Key:"11",State:"12",Status:"13",String:"14",UniqueIdentifier:"15",EntityNameReference:"16",Entity:"17",EntityCollection:"18",BpfProcess:"19",BpfStageCategory:"20",BpfStage:"21",EntityReferenceCollection:"22",MultiSelectPicklist:"23",BigType:"24"};pr.WorkflowConditionOperator={IsNull:"0",NotNull:"1",LogicalAnd:"2",LogicalOr:"3",IN:"4",NotIn:"5",NotInNull:"51",Equal:"6",NotEqual:"7",Contains:"8",DoesNotContain:"9",BeginsWith:"10",DoesNotBeginWith:"11",EndsWith:"12",DoesNotEndWith:"13",GreaterThan:"14",GreaterThanOrEqual:"15",LessThan:"16",LessThanOrEqual:"17",EqualUserId:"18",NotEqualUserId:"19",On:"20",NotOn:"21",OnOrAfter:"22",OnOrBefore:"23",Yesterday:"24",Today:"25",Tomorrow:"26",NextSevenDays:"27",LastSevenDays:"28",NextWeek:"29",LastWeek:"30",ThisWeek:"31",NextMonth:"32",LastMonth:"33",ThisMonth:"34",NextYear:"35",LastYear:"36",ThisYear:"37",Anytime:"38",LastXHours:"39",NextXHours:"40",LastXDays:"41",NextXDays:"42",LastXWeeks:"43",NextXWeeks:"44",LastXMonths:"45",NextXMonths:"46",LastXYears:"47",NextXYears:"48",Under:"49",NotUnder:"50"}});function aT(e){switch(e){case"Boolean":return Ne.WorkflowAttributeType.Boolean;case"Customer":return Ne.WorkflowAttributeType.Customer;case"DateTime":return Ne.WorkflowAttributeType.DateTime;case"Decimal":return Ne.WorkflowAttributeType.Decimal;case"Double":return Ne.WorkflowAttributeType.Float;case"Integer":return Ne.WorkflowAttributeType.Integer;case"Lookup":return Ne.WorkflowAttributeType.Lookup;case"Money":return Ne.WorkflowAttributeType.Money;case"Owner":return Ne.WorkflowAttributeType.Owner;case"Picklist":return Ne.WorkflowAttributeType.Picklist;case"State":return Ne.WorkflowAttributeType.State;case"Status":return Ne.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ne.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ne.WorkflowAttributeType.BigType;default:return Ne.WorkflowAttributeType.String}}function pT(e){return e&&e!==Ne.WorkflowAttributeType.String?e:void 0}function Fz(e){return{__class:dT,parameterName:"primaryEntity",entityName:e}}function rT(e){return{__class:Lh,type:Fh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:oT,parameters:[e]}}function nT(e,t,r=Ne.WorkflowAttributeType.String){return{__class:lT,type:r,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,entity:Fz(t),attributeName:e}}function Lz(e,t=Ne.WorkflowAttributeType.String){return{__class:uT,type:t,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function kz(e){return{__class:cT,type:Fh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function fT(e,t){let r=Oz[e.operator],n=rT(nT(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=kz(e.right.value??"0"):e.right.kind==="field"?i=nT(e.right.field??"",t,e.right.workflowType):i=Lz(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let a=rT(i);return{__class:Lh,type:Fh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:sT,parameters:[r,n,a]}}function mT(e){return typeof e=="object"&&e.__class===Lh}function Mz(e){return typeof e=="object"&&e.__class===cT}function Sc(e){return mT(e)&&e.method===oT&&e.parameters.length>0?Sc(e.parameters[0]):e}function iT(e){if(typeof e!="object"||e.__class!==lT)return null;let t=e.entity;if(t&&t.__class&&t.__class!==dT)return null;let r=e.attributeName;return r?{field:r,workflowType:pT(e.type)}:null}function hT(e){if(!e)return null;let t=Sc(e);if(!mT(t)||t.method!==sT||t.parameters.length!==3)return null;let r=t.parameters[0],n=xz[String(r)];if(!n)return null;let i=iT(Sc(t.parameters[1]));if(!i)return null;let a=Sc(t.parameters[2]);if(Mz(a))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(a.days??"")},dateArithmetic:!0};let o=iT(a);if(o)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:o.field,workflowType:o.workflowType}};if(typeof a=="object"&&a.__class===uT){let s=a.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:pT(a.type)}}}return null}function Mh(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=kh&&r<=go}function Qi(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!Mh(t)?"invalidDayCount":null}function vo(e){return Qi(e)===null}var Ne,oT,sT,Fh,lT,uT,Lh,cT,dT,Oz,xz,kh,go,Qs=T(()=>{"use strict";Ne=ce(xh());oT="0",sT="3",Fh="0",lT="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",uT="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Lh="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",cT="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",dT="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Oz={"+":0,"-":1,"*":2,"/":3},xz={0:"+",1:"-",2:"*",3:"/"};kh=0,go=2147483647});function Uz(e){return e.startsWith("__")&&!Bz.has(e)}function $z(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Uz(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function DT(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ys(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Bh(e){return DT(e)||Ys(e)}function qz(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Xs(){return{list:[]}}function Uh(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Nt(),languageCode:r,description:t}]}}function Vh(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function _c(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entity:Vh(t),attributeName:e}}function bo(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function zz(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?TT:_T:IT}function PT(e){return e.bpfField==="StageCategory"?W.WorkflowAttributeType.BpfStageCategory:W.WorkflowAttributeType.BpfProcess}function Wz(e,t){let r=PT(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${vT}_${gT}`,entityName:gT,relatedAttributeName:vT},attributeName:Gz}:_c(Vz,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,method:Gh,parameters:[zz(e),n]}}function jz(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Gh)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===_T?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===TT?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===IT?{bpfField:"ProcessName"}:null}function Nc(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Gh){let r=(t.parameters??[])[0];if(typeof r=="string"&&Hz.has(r.replace(/^"+|"+$/g,"")))return!0}return Ys(e)?Nc(e.operand):DT(e)?Nc(e.left)||(e.right??[]).some(Nc):!1}function RT(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??W.WorkflowAttributeType.Lookup,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:bo(e.id.replace(/[{}]/g,""),W.WorkflowAttributeType.UniqueIdentifier)}}function yT(e){return e==="ContainsData"||e==="DoesNotContainData"}function bT(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function wT(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??W.WorkflowAttributeType.Lookup:e.valueWorkflowType??W.WorkflowAttributeType.String,n=qh[e.operator]??W.WorkflowConditionOperator.Equal;if(e.source==="BusinessProcess"){let o=Wz(e,t);if(yT(e.operator))return bT(o,n);let s=PT(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:o,right:[bo(e.value??"",s)]}}let i=_c(e.field,t,r);if(yT(e.operator))return bT(i,n);let a;if(e.valueType==="Field"&&e.valueField)a=[_c(e.valueField,t,r)];else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");a=[RT(e.lookupValue)]}else e.valueType==="Clear"?a=[bo(null,r)]:e.valueType==="Expression"?a=[Ic(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:a=[bo(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:i,right:a}}function Kz(e,t,r){if(e.length===0)return null;let n=wT(e[0],r);for(let i=1;i<e.length;i++){let a=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:W.WorkflowAttributeType.Boolean,behavior:W.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:a==="AND"?W.WorkflowConditionOperator.LogicalAnd:W.WorkflowConditionOperator.LogicalOr,left:n,right:[wT(e[i],r)]}}return n}function Dc(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return e.primitiveValue==null?{valueType:"Clear",valueWorkflowType:e.type}:{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):""};if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==W.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=hT(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Jz(e){let t=NT[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Ys(e)?e.operand:e.left,i=Ys(e)?[]:e.right,a=jz(n);if(a){let d=i[0];return{id:Nt(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:a.bpfField,...a.stageType?{stageType:a.stageType}:{},operator:t,valueType:"Value",value:d?.primitiveValue!=null&&!r?String(d.primitiveValue):""}}let o=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=o?n.type:void 0,u=r?{valueType:"Value"}:Dc(i[0]),c=u.valueWorkflowType??l;return{id:Nt(),field:s,fieldDisplayName:s,operator:t,...u,...c?{valueWorkflowType:c}:{}}}function AT(e){if(!e||!Bh(e))return{clauses:[],logic:"AND"};let t=[],r=(a,o)=>{let s=a.conditionOperatoroperator;if(Ys(a)||s!==W.WorkflowConditionOperator.LogicalAnd&&s!==W.WorkflowConditionOperator.LogicalOr){t.push({...Jz(a),...o?{connector:o}:{}});return}let l=s===W.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Bh(a.left)&&r(a.left,o),a.right.filter(Bh).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(a=>a.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function Ic(e,t,r,n,i,a,o,s){if(e==="Field"&&r)return _c(r,n,W.WorkflowAttributeType.String);if(e==="Expression"){if(i)return fT(i,n);if(a!=null)return a}return e==="Lookup"&&o?RT(o):e==="Clear"?bo(null,s??W.WorkflowAttributeType.String):bo(t??"",W.WorkflowAttributeType.String)}function $h(e,t){return{propertyName:e,propertyValueExpr:t}}function yo(e){return`Step_${e.value++}`}function fr(e,t){let r=(t.counts[e]??0)+1,n=`${e}${r}`;for(;t.used.has(n);)r+=1,n=`${e}${r}`;return t.counts[e]=r,t.used.add(n),n}function ET(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):fr(t,r)}function Qz(e){return e===ST.StateCode.Activated?"Active":"Draft"}function Xz(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function OT(e,t=1033){return new wo({languageCode:t}).serialize(e)}function xT(e){return new wo().deserialize(e)}var ST,W,Bz,qh,NT,Gh,IT,_T,TT,Vz,Gz,gT,vT,Hz,zh,wo,Wh=T(()=>{"use strict";Oh();ST=ce(Ai());tT();Qs();W=ce(xh());Bz=new Set(["__class"]);qh={Equals:W.WorkflowConditionOperator.Equal,DoesNotEqual:W.WorkflowConditionOperator.NotEqual,IsGreaterThan:W.WorkflowConditionOperator.GreaterThan,IsLessThan:W.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:W.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:W.WorkflowConditionOperator.LessThanOrEqual,Contains:W.WorkflowConditionOperator.Contains,DoesNotContain:W.WorkflowConditionOperator.DoesNotContain,BeginsWith:W.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:W.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:W.WorkflowConditionOperator.EndsWith,DoesNotEndWith:W.WorkflowConditionOperator.DoesNotEndWith,On:W.WorkflowConditionOperator.On,NotOn:W.WorkflowConditionOperator.NotOn,ContainsData:W.WorkflowConditionOperator.NotNull,DoesNotContainData:W.WorkflowConditionOperator.IsNull},NT={};for(let e of Object.keys(qh))NT[qh[e]]=e;Gh="23",IT="BpfProcess",_T="ActiveStageCategory",TT="SelectedStageCategory",Vz="processid",Gz="stagecategory",gT="processstage",vT="stageid";Hz=new Set(["ActiveStage","SelectedStage","Stage"]);zh={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};wo=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>zh[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],a={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??Nt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Xs(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(a)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:fr("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??yo(this.stepCounter),stepLabels:{list:[]},specification:$h(t.field,Ic(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:Vh(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),a=t??"",o=n?.stepLabels,s=Uh(o,a,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:ET(n?.id,"ActionStep",this.idCounter),name:n?.name??yo(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??Nt(),uniqueName:n?.uniqueName??`id_${Nt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=Vh(this.entityName),n=t.stepName??yo(this.stepCounter),i=t.stepLabels??Xs(),a={name:n,stepLabels:i,description:t.displayName},o=t.type;switch(o){case"SetFieldValue":return{...a,id:fr("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:$h(t.field,Ic(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...a,id:fr("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:$h(t.field,Ic(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...a,id:fr("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...a,id:fr("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?W.FieldRequiredLevelTypes.Required:W.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...a,id:fr("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=Uh(t.stepLabels,s,this.languageCode);return{...a,id:fr("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,name:s,controlId:t.field,entity:r,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,l=Uh(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...a,id:fr("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${o}`)}}serializeConditionNode(t){let r=t.stepName??yo(this.stepCounter),n=fr("ConditionStep",this.idCounter),i=[],a=t,o=!0;for(;a;){let s=a.rawConditionExpression??Kz(a.clauses,a.logic,this.entityName),l=o?a.branchName??yo(this.stepCounter):yo(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:o?ET(a.branchId,"ConditionBranchStep",this.idCounter):fr("ConditionBranchStep",this.idCounter),name:l,description:a.displayName,stepLabels:Xs(),conditionExpression:s??void 0,steps:{list:a.trueBranch.map(p=>this.serializeBranchItem(p))}};i.push(c);let d=a.falseBranch;if(d.length===1&&d[0].kind==="condition"){a=d[0],o=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),a=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Xs(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:fr("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Xs(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let a=JSON.parse(t.wfomJson);i={id:a.id==="WorkflowStep0"||!a.id?t.workflowid??Nt():a.id,name:a.name,description:a.description,nextStepIndex:a.nextStepIndex,category:a.category==="0"||a.category===0?"2":a.category,businessProcessType:a.businessProcessType,mode:a.mode,title:a.title||t.name||"",primaryEntityName:a.primaryEntityName==="1"||!a.primaryEntityName?t.primaryentity??"":a.primaryEntityName,workflowEntityId:a.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!a.workflowEntityId?t.workflowid??"":a.workflowEntityId,formId:a.formId,variables:a.variables,inputs:a.inputs,reservedProperties:$z(a)};let s=(a.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Xz(r,i?.formId),status:Qz(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(qz);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...a]=t,{clauses:o,logic:s}=AT(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(a,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??Nt(),displayName:c,clauses:o,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...Nc(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=AT(n.conditionExpression);return i.length===0?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},a=n.stepLabels?.list,o=a&&a.length>0?a[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||Nt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Dc(u?.propertyValueExpr)}}),meta:i,acceptanceText:o}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Dc(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetFieldValue",displayName:t.description||t.name||this.label("setFieldValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Dc(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==W.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:a,acceptanceText:o}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:o,applyActions:i,recommendationActionStepMeta:a}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var FT=T(()=>{"use strict";});function fi(e){return!Yz.has(e)}function BT(e){return e==="Equals"||e==="DoesNotEqual"}function Tc(e){return kT.has(e)?Zz:i7.has(e)?e7:MT.has(e)?t7:o7.has(e)?n7:r7}function UT(e){return Tc(e)[0]}function $T(e,t){return Tc(t).includes(e)}function LT(e){return kT.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":MT.has(e)?"date":a7.has(e)?"boolean":"other"}function Pc(e,t){let r=LT(e),n=LT(t);return r==="other"||n==="other"?e===t:r===n}var Yz,Zz,e7,t7,r7,n7,kT,i7,MT,a7,o7,jh=T(()=>{"use strict";FT();Yz=new Set(["ContainsData","DoesNotContainData"]);Zz=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],e7=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],t7=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],r7=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],n7=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],kT=new Set(["String","Memo","EntityName"]),i7=new Set(["Integer","BigInt","Money","Decimal","Double"]),MT=new Set(["DateTime"]),a7=new Set(["Boolean"]),o7=new Set(["Lookup","Owner","Customer"])});function Qh(e){return s7.has(e.type)}function Hh(e,t,r,n,i,a,o){let s=i.get(r);!s||!l7.has(s.attributeType)||n!=="Value"||o?.operator&&!BT(o.operator)||a.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:o?.target,itemId:o?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function Kh(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Jh(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${go}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:go}}}function qT(e,t,r,n,i,a,o,s){if(i!=="Clear")return;let l=a.get(n);Ac(r,l)||o.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Oc(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(Qh(t))return!0}else if(Oc(t))return!0;return!1}function Xh(e,t){if(e.id===t)return e;for(let r of[...e.trueBranch,...e.falseBranch]){if(r.id===t)return r;if(r.kind==="condition"){let n=Xh(r,t);if(n)return n}}return null}function Ao(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=Ao(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=Ao(n,t);if(i)return i}}return null}function Yh(e,t){return{...e,trueBranch:VT(e.trueBranch,t),falseBranch:VT(e.falseBranch,t)}}function VT(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Yh(r,t):r)}function mi(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?mi(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?mi(n,t,r):n)}}function Rc(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Rc(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Rc(n,t,r):n)}}function GT(e,t,r,n){return mi(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Zh(e){return e.length===1&&e[0].kind==="condition"}function c7(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Zh(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function d7(e){return!!e&&c7(e)<u7}function p7(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let a=[];if(Zh(n.falseBranch)){let o=r(n.falseBranch[0],i);if(o)return o}else a.push(...n.falseBranch.filter(o=>o.kind==="condition"));a.push(...n.trueBranch.filter(o=>o.kind==="condition"));for(let o of a){let s=r(o,o);if(s)return s}};return r(e,e)}function zT(e,t,r){let n=p7(e,t);return!n||!d7(n)?e:mi(e,t,i=>WT(i,r))}function WT(e,t){if(Zh(e.falseBranch))return{...e,falseBranch:[WT(e.falseBranch[0],t)]};let r=eg(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function jT(e,t){let r=Ao(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return mi(e,r.node.id,a=>({...a,falseBranch:i}))}function HT(e,t,r){let n=Ao(e,t);if(!n)return e;let i=a=>{let o=[...a],s=o[n.index+r];return s?(o[n.index+r]=o[n.index],o[n.index]=s,o):a};return mi(e,n.node.id,a=>({...a,trueBranch:n.branch==="true"?i(a.trueBranch):a.trueBranch,falseBranch:n.branch==="false"?i(a.falseBranch):a.falseBranch}))}function eg(e){return{kind:"condition",id:Nt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function KT(e,t){let r={kind:"action",id:Nt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Nt(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...r,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...r,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...r,type:"SetVisibility",field:"",visible:!0};default:return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function JT(e){if(!e)return[];let t=[];return QT(e,t),[...new Set(t)]}function QT(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?QT(r,t):"field"in r&&r.field&&t.push(r.field)})}function XT(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return YT(e,r,n),Oc(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function YT(e,t,r){let n=!!e.rawConditionExpression;e.clauses.length===0&&!n&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(i=>{if(n)return;if(i.source==="BusinessProcess"){i.bpfField?i.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:i.id,messageKey:"Validation.SelectBusinessProcessField"});return}let a=i.valueType==="Expression"&&!i.rawExpression?Qi(i.expression):null;if(!i.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:i.id});else if(fi(i.operator)&&i.valueType==="Value"&&!i.value)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id});else if(fi(i.operator)&&i.valueType==="Value"&&i.value){let o=r.get(i.field);o?.maxLength&&i.value.length>o.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${o.maxLength} characters.`,target:"clauseValue",itemId:i.id,messageParams:{maxLength:o.maxLength}})}else fi(i.operator)&&i.valueType==="Expression"&&!i.rawExpression&&!vo(i.expression)&&t.push(a==="invalidDayCount"?Jh(e.id,"clauseValue",i.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.CompleteClauseFormula"});fi(i.operator)&&i.valueType==="Lookup"&&(Kh(i.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseLookupValue"})),fi(i.operator)&&Hh(e.id,"Condition",i.field,i.valueType,r,t,{operator:i.operator,target:"clauseValue",itemId:i.id})}),[...e.trueBranch,...e.falseBranch].forEach(i=>{if(i.kind==="condition")YT(i,t,r);else{if(!("field"in i)||!i.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:`${i.type}: a target field is required.`,target:"actionField",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&(i.valueType??"Value")==="Value"&&!i.value?.trim())t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Value"&&i.value){let a=r.get(i.field);a?.maxLength&&i.value.length>a.maxLength&&t.push({nodeId:i.id,kind:"ACTION_VALUE_TOO_LONG",message:`${i.type}: value exceeds the field's maximum length of ${a.maxLength} characters.`,target:"actionValue",messageParams:{actionType:i.type,maxLength:a.maxLength}})}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Field"){if(!i.valueField)t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:i.type}});else if(r.size>0){let a=r.get(i.field),o=r.get(i.valueField);a&&o&&!Pc(a.attributeType,o.attributeType)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:i.type}})}}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Expression"){let a=i.rawExpression?null:Qi(i.expression);!i.rawExpression&&!vo(i.expression)&&t.push(a==="invalidDayCount"?Jh(i.id,"actionValue"):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:i.type}})}else(i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Lookup"&&!Kh(i.lookupValue)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:i.type}});if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.field&&(Hh(i.id,i.type,i.field,i.valueType,r,t,{target:"actionValue"}),qT(i.id,i.type,i.type,i.field,i.valueType,r,t,{target:"actionValue"})),i.type==="ShowErrorMessage"&&!i.errorMessage?.trim()&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),i.type==="Recommendation"){let a=i.applyActions??[];i.recommendationTitle?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),i.messageText?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),a.length===0&&t.push({nodeId:i.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),a.forEach(o=>{if(!o.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:o.id,messageKey:"Validation.RecommendationApplyField"});else if(o.valueType==="Field")o.valueField||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplySourceField"});else if(o.valueType==="Expression"){let s=o.rawExpression?null:Qi(o.expression);!o.rawExpression&&!vo(o.expression)&&t.push(s==="invalidDayCount"?Jh(i.id,"applyActionValue",o.id):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplyFormula"})}else o.valueType==="Lookup"?Kh(o.lookupValue)||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplyLookupValue"}):o.valueType==="Clear"||o.value?.trim()||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:o.id,messageKey:"Validation.RecommendationApplyValue"});o.field&&(Hh(i.id,"Recommendation",o.field,o.valueType,r,t,{target:"applyActionValue",itemId:o.id}),qT(i.id,"Recommendation","SetFieldValue",o.field,o.valueType,r,t,{target:"applyActionValue",itemId:o.id}))})}}})}var s7,l7,u7,tg=T(()=>{"use strict";Oh();Ih();jh();Qs();s7=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);l7=new Set(["Lookup","Customer","Owner"]);u7=10});var ZT={};pn(ZT,{DAY_COUNT_MAX:()=>go,DAY_COUNT_MIN:()=>kh,DEFAULT_DESERIALIZE_LABELS:()=>zh,WorkflowJsonMapper:()=>wo,addElseIfInTree:()=>zT,appendToBranch:()=>GT,areFieldKindsCompatible:()=>Pc,attributeTypeToWorkflowType:()=>aT,buildWorkflowEntity:()=>j_,collectUsedFields:()=>JT,createEmptyAction:()=>KT,createEmptyCondition:()=>eg,deserializeWorkflowJson:()=>xT,findNode:()=>Xh,findParent:()=>Ao,getDefaultOperatorForFieldType:()=>UT,getExpressionModelIssue:()=>Qi,getOperatorsForFieldType:()=>Tc,hasAnyTriggerGeneratingAction:()=>Oc,isDayCountValid:()=>Mh,isExpressionModelComplete:()=>vo,isOperatorCompatible:()=>$T,isTriggerGeneratingAction:()=>Qh,moveBranchItemInTree:()=>HT,operatorNeedsValue:()=>fi,processTriggerFormIdFromScope:()=>Th,processTriggerScopeFromScope:()=>_h,removeElseIfInTree:()=>jT,removeNodeFromTree:()=>Yh,serializeToWorkflowJson:()=>OT,supportsClearForActionType:()=>Ac,updateActionInTree:()=>Rc,updateConditionInTree:()=>mi,validateBusinessRule:()=>XT});var e2=T(()=>{"use strict";Ih();H_();Wh();Wh();tg();tg();jh();Qs();Qs();});var rg=y(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.cloneJson=void 0;function f7(e){return JSON.parse(JSON.stringify(e))}xc.cloneJson=f7});var d2=y(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.BUSINESS_RULE_NULL_GUID=hi.businessRuleRegistration=hi.BusinessRuleAdapter=void 0;var t2=lt(),Zs=(e2(),Mr(ZT)),r2=Nr(),n2=te(),m7=rg(),rn=Cr(),h7=Xd(),g7=lt();function v7(e){return s2((0,m7.cloneJson)(e))}function s2(e){var t,r;let n=i=>(i??[]).map(a=>y7(a)?s2(a):a);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function y7(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function b7(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new n2.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new n2.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var w7="00000000-0000-0000-0000-000000000000";hi.BUSINESS_RULE_NULL_GUID=w7;var A7=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),E7=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],C7=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],S7=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Or(e,t){return e===void 0?t:{...e,...t}}var Xi=["kind","id","type","displayName","field","stepName","stepLabels"],i2=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],N7={Recommendation:[...Xi,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Xi,"lock"],ShowErrorMessage:[...Xi,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Xi,...i2],SetDefaultValue:[...Xi,...i2],SetBusinessRequired:[...Xi,"required"],SetVisibility:[...Xi,"visible"]};function K(e,t){return t===void 0?{}:{[e]:t}}function l2(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function ng(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",l2(e.lookupValue)),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function u2(e,t){let r=new Set(t),n={};for(let[i,a]of Object.entries(e))r.has(i)||a!==void 0&&(n[i]=a);return Object.keys(n).length>0?n:void 0}var D7=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function I7(e){return Or(e.bag,{id:e.id,field:e.field,...ng(e),...K("stepName",e.stepName),...K("displayName",e.displayName)})}function _7(e){let t=u2(e,D7);return{id:e.id,field:e.field,valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression),...K("stepName",e.stepName),...K("displayName",e.displayName),...K("bag",t)}}function a2(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function o2(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var T7=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),P7=new Set,R7="INVALID_CLEAR_FOR_FIELD";function O7(e){let t=n=>{var i;return(0,rn.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,rn.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let a of["clauses","trueBranch","falseBranch"])Array.isArray(i[a])&&(i[a]=i[a].map(r));return i};return r(e)}var Fc=class{toArtifact(t){let r=this.residualBag(t,E7),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Or(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},a=(0,Zs.deserializeWorkflowJson)(i);return this.toArtifact(a)}toApiPayload(t){var r;let n=this.fromArtifact(t);n.wfomRoot&&(n.wfomRoot={...n.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||n.wfomRoot.primaryEntityName});let i=(0,Zs.serializeToWorkflowJson)(n),a=(r=n.ruleId)!==null&&r!==void 0?r:(0,t2.newId)();return{Entity:this.buildWorkflowEntity(n,a),WfomJson:i,status:t.status}}createDefault(t){var r,n,i,a,o,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:"",scope:(o=t.scope)!==null&&o!==void 0?o:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Zs.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(v7(b7(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,t2.newId)()),u}assignMissingIds(t){return(0,g7.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,rn.isJsonObject)(n)?(c2(n,"/rootCondition",r),r):(r.push((0,rn.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(o){return[(0,rn.issue)("/rootCondition","rule-not-representable",o instanceof Error?o.message:String(o))]}let i=n.rootCondition===null?null:O7(n.rootCondition),a;return r.length===0?a=T7:r.some(o=>o.requiredLevel!==void 0)?a=P7:a=new Set([R7]),(0,Zs.validateBusinessRule)(i,r).filter(o=>!a.has(o.kind)).map(o=>(0,rn.issue)(`/rootCondition (${o.nodeId})`,`business-rule-${o.kind}`,o.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}residualBag(t,r){return u2(t,r)}buildWorkflowEntity(t,r){return(0,Zs.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,C7),n={id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseToJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemToJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemToJson(i))};return r&&(n.bag=r),n}clauseToJson(t){let r=this.residualBag(t,S7),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,N7[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels),...K("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(_7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...a2(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...a2(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return o2(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Or(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Or(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...K("value",t.value),...K("valueField",t.valueField),...K("lookupValue",l2(t.lookupValue)),...K("expression",t.expression),...K("rawExpression",t.rawExpression),...K("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!A7.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);F7(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Or(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(I7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Or(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Or(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Or(t.bag,{...r,type:"SetFieldValue",...ng(t)});case"SetDefaultValue":return Or(t.bag,{...r,type:"SetDefaultValue",...ng(t)});case"SetBusinessRequired":return Or(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Or(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return o2(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};hi.BusinessRuleAdapter=Fc;function c2(e,t,r){(0,rn.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,rn.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,rn.childObjects)(e,n,t,"branchItem",r).forEach(({node:a,index:o})=>{"clauses"in a||"trueBranch"in a||"falseBranch"in a?c2(a,`${t}/${n}/${o}`,r):x7(a,`${t}/${n}/${o}`,r)})}function x7(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,rn.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function F7(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function L7(){return{adapter:new Fc,api:h7.businessRuleApi,publish:(e,t,r)=>(0,r2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,r2.boundEntityPublishScope)(t)}}hi.businessRuleRegistration=L7});var I2=y(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.appRegistration=gi.AppAdapter=gi.HEADER_NAV_BOOLEAN_RULE=void 0;var Tn=Cr(),nt=Kn(),tl=_i(),k7=Nr(),M7=gu(),ig=pu(),ag=Qn(),B7=lt(),U7=ae(),A2=ha(),E2=te(),C2=mu();Object.defineProperty(gi,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return C2.HEADER_NAV_BOOLEAN_RULE}});var Bc="7.0.0.0",p2=`<SiteMap IntroducedVersion="${Bc}"></SiteMap>`,f2="/_imgs/imagestrips/transparent_spacer.gif",m2="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",$7=["Entity","Url","DefaultDashboard","Page","GenPageId"],el="sitemapId",h2="sitemapName",q7="sitemapNameUnique",g2="aiDescription",v2="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",V7=new RegExp(`^(?:\\{${v2}\\}|${v2})$`);function y2(e,t){if(!V7.test(e.trim()))throw new E2.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function b2(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new E2.ValidationError("app",t,[S2(e)]);return e}function S2(e){return(0,Tn.issue)("/headerAndNavigationRefresh",C2.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function G7(e){let t=n=>{let i=e[n];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},r=n=>{let i=t(n);if(i!==void 0)try{return(0,U7.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}var Uc=class{constructor(t=A2.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Lc(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,nt.emptyBag)()}}fromArtifact(t){(0,ag.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,nt.rebuildRaw)(i,(0,tl.domEngine)(n),null)}fromApiResponse(t){var r,n,i,a,o,s,l,u,c,d,p;(0,ag.installDomShim)();let f=t??{},m=(r=f.$sitemap)!==null&&r!==void 0?r:f,h=(0,tl.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:p2,p2),v=this.toArtifact(h);return v.id=(i=f.appmoduleid)!==null&&i!==void 0?i:"",v.name=(a=f.name)!==null&&a!==void 0?a:"",v.uniqueName=(o=f.uniquename)!==null&&o!==void 0?o:"",v.description=(s=f.description)!==null&&s!==void 0?s:"",f.aiappdescription&&(v.aiDescription=f.aiappdescription),v.bag={a:[[el,(u=(l=m.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[h2,(c=m.sitemapname)!==null&&c!==void 0?c:""],[q7,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[g2,(p=f.aiappdescription)!==null&&p!==void 0?p:""]],c:[]},v}toApiPayload(t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h,v;(0,ag.installDomShim)();let b=(0,tl.serializeNode)(this.fromArtifact(t)),E=[],C=[];for(let R of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let O of(a=R.groups)!==null&&a!==void 0?a:[])for(let F of(o=O.subAreas)!==null&&o!==void 0?o:[])F.type==="Entity"&&F.entity?E.push(F.entity):F.type==="DashBoard"&&F.dashboardId&&C.push(F.dashboardId);let N=(s=t.bag)!==null&&s!==void 0?s:(0,nt.emptyBag)();return{sitemapId:sg(N,el)||(t.sitemapId?y2(t.sitemapId,t.id):""),sitemapxml:b,sitemapname:sg(N,h2)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:sg(N,g2))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[ig.HEADER_AND_NAVIGATION_REFRESH]:b2(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?ig.APP_SETTING_ON:ig.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(m=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&m!==void 0?m:[],dashboards:[...(v=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&v!==void 0?v:[],...C]}}}createDefault(t){var r,n,i,a,o,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,B7.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(a=t.uniqueName)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:y2(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:b2(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(ug):Array.isArray(r.areas)?r.areas.forEach(ug):Array.isArray(r.groups)?ug(r):Array.isArray(r.subAreas)?D2(r):"type"in r&&$c(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Tn.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,a=t.headerAndNavigationRefresh;if(a!==void 0&&typeof a!="boolean"&&r.push(S2(a)),i==null)return r;if(!(0,Tn.isJsonObject)(i))return r.push((0,Tn.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let o=(0,Tn.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return o.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Tn.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let m=`${c}/groups/${f}`;(0,Tn.childObjects)(p,"subAreas",m,"subArea",r).forEach(({node:v,index:b})=>{let E=`${m}/subAreas/${b}`;(0,Tn.optionalEnum)(v,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],E,"subarea-type-invalid",r);let C=G7(v);if(!C)return;let N=s.get(C);if(N===void 0){s.set(C,E);return}r.push((0,Tn.issue)(E,"subarea-duplicate-target",`the sitemap already navigates to this target at ${N}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}applyServerIdentity(t,r){let n=r[el];if(!n)return;t.bag||(t.bag=(0,nt.emptyBag)());let i=t.bag.a.find(a=>a[0]===el);i?i[1]=n:t.bag.a.push([el,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Lc(t,"Group"),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:og(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},o=t.getAttribute("Icon");o&&(a.icon=o);let s=t.getAttribute("VectorIcon");return s&&(a.vectorIcon=s),a}groupToJson(t){var r;let{bag:n,modeledEls:i}=Lc(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:og(t,this.lcid),subAreas:i.map(a=>this.subAreaToJson(a)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Lc(t,null),i=z7(t),a={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:og(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(a.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(a.dashboardId=l);let u=t.getAttribute("Url");u&&(a.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(a.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(a.genPageId=l)}else{let l=t.getAttribute("Url");l&&(a.url=l)}let o=t.getAttribute("Icon");o&&o!==f2&&(a.icon=o);let s=t.getAttribute("VectorIcon");return s&&(a.vectorIcon=s),a}rootToRaw(t){var r,n,i,a;let o=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,nt.emptyBag)(),l=kc(o)?[["IntroducedVersion",Bc]]:[],u=((a=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&a!==void 0?a:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,nt.mergeAttrs)(o.a,l),c:(0,nt.spliceChildren)(o.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,nt.emptyBag)(),i=kc(n),a=[],o=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Bc]),t.icon!==void 0?a.push(["Icon",t.icon]):Mc(n.a,"Icon")&&o.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Mc(n.a,"VectorIcon")&&o.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=lg((0,nt.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,nt.mergeAttrs)(n.a,a,o),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,nt.emptyBag)(),i=kc(n),a=[];t.id&&a.push(["Id",t.id]),i&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Bc],["IsProfile","false"]);let o=t.subAreas.map(l=>this.subAreaToRaw(l)),s=lg((0,nt.spliceChildren)(n.c,o),t.title,i,this.lcid);return{n:"Group",a:(0,nt.mergeAttrs)(n.a,a),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,nt.emptyBag)(),i=kc(n),a=j7(n.a,t.type),o=[],s=[];t.id&&o.push(["Id",t.id]),K7(o,t),i?(o.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&o.push(["Icon",t.icon])):t.icon!==void 0?o.push(["Icon",t.icon]):Mc(a,"Icon",f2)&&s.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Mc(a,"VectorIcon")?t.type==="GenPage"?o.push(["VectorIcon",m2]):s.push("VectorIcon"):t.type==="GenPage"&&!W7(a,"VectorIcon")&&o.push(["VectorIcon",m2]);let l=lg((0,nt.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,nt.mergeAttrs)(a,o,s),c:l}}};gi.AppAdapter=Uc;function Lc(e,t){let r=(0,tl.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],a=e.childNodes,o=0;for(let s=0;s<a.length;s+=1){let l=a[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:o,node:(0,nt.rawFromNode)((0,tl.nodeLikeFromDom)(l))}),o+=1)}return{bag:{a:r,c:n},modeledEls:i}}function w2(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName===t&&r.push(a)}return r}function og(e,t){var r;let n=w2(e,"Titles")[0];if(!n)return"";let a=w2(n,"Title").find(o=>o.getAttribute("LCID")===String(t));return a&&(r=a.getAttribute("Title"))!==null&&r!==void 0?r:""}function z7(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function kc(e){return e.a.length===0&&e.c.length===0}function W7(e,t){return e.some(([r])=>r===t)}function Mc(e,t,r){let n=e.find(([a])=>a===t),i=n?.[1];return!!i&&i!==r}function sg(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function j7(e,t){let r=H7(t);return e.filter(([n])=>!$7.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function H7(e){switch(e){case"Entity":return new Set(["Entity"]);case"URL":return new Set(["Url"]);case"DashBoard":return new Set(["DefaultDashboard","Url"]);case"CustomPage":return new Set(["Page"]);case"GenPage":return new Set(["GenPageId"]);default:return new Set}}function K7(e,t){var r,n,i,a,o;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(a=t.page)!==null&&a!==void 0?a:""]);break;case"GenPage":e.push(["GenPageId",(o=t.genPageId)!==null&&o!==void 0?o:""]);break;default:break}}function lg(e,t,r,n){if(!t)return e;let i=e.findIndex(a=>a.n==="Titles");if(i>=0){let a=e.slice();return a[i]=J7(e[i],t,n),a}return r?[Q7(t,n),...e]:e}function J7(e,t,r){let n=!1,i=e.c.map(a=>!n&&a.n==="Title"&&X7(a,"LCID")===String(r)?(n=!0,{n:a.n,a:(0,nt.mergeAttrs)(a.a,[["Title",t]]),c:a.c}):a);return n||i.unshift(N2(t,r)),{n:e.n,a:e.a.map(a=>[a[0],a[1]]),c:i}}function Q7(e,t){return{n:"Titles",a:[],c:[N2(e,t)]}}function N2(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function X7(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Y7(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function $c(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Y7(8)}`)}function ug(e){var t;$c(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])D2(r)}function D2(e){var t;$c(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])$c(r,"subarea")}function Z7(e=A2.DEFAULT_LCID){return{adapter:new Uc(e),api:M7.appApi,languageSensitive:!0,publish:(t,r)=>(0,k7.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}gi.appRegistration=Z7});var _2={};pn(_2,{ActionType:()=>dg,AppActionOrigin:()=>bg,AppActionVisibilityType:()=>yg,ButtonType:()=>fg,CannotUpdateAppActionColumns:()=>eW,Context:()=>hg,IconType:()=>pg,Location:()=>mg,OnClickEventType:()=>vg,Scope:()=>gg,VisibilityType:()=>cg});var cg,dg,pg,fg,mg,hg,gg,vg,yg,bg,eW,T2=T(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(cg||(cg={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(dg||(dg={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(pg||(pg={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(fg||(fg={}));(function(e){e[e.Form=0]="Form",e[e.HomePageGrid=1]="HomePageGrid",e[e.SubGridStandard=2]="SubGridStandard",e[e.SubGridAssociated=3]="SubGridAssociated",e[e.QuickForm=4]="QuickForm",e[e.Global=5]="Global",e[e.Dashboard=6]="Dashboard"})(mg||(mg={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(hg||(hg={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(gg||(gg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(vg||(vg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(yg||(yg={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(bg||(bg={}));eW=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var x2=y(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.commandApi=void 0;var P2=Pt(),xr=be(),O2=te(),mr=ae(),tW="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function qc(e,t){let r=`/EntityDefinitions(LogicalName='${(0,mr.odataPathLiteral)(t)}')${(0,mr.odataQuery)([["$select","MetadataId"]])}`,i=(0,xr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,a=i?.MetadataId;return a?(0,mr.normalizeGuid)(a,"entityMetadataId"):""}Vc.commandApi={async get(e,t){let r=t,n=await qc(e,r),i=n?`_contextentity_value eq ${n}`:`contextvalue eq '${(0,mr.odataLiteral)(r)}'`,a=`/appactions${(0,mr.odataQuery)([["$expand",tW],["$filter",i]])}`,o,s=await(0,P2.collectPages)(e,a,"fetchArtifact('command')",c=>{o=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let p=c["@odata.etag"];u[(0,mr.normalizeGuid)(d,"appactionid")]=typeof p=="string"?p:null}}return{raw:l,etag:o?(0,xr.readEtag)(o):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t){let r=t,n=r.entityMetadataId||await qc(e,r.entityLogicalName);return R2(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){let a=r,o=a.entityMetadataId||await qc(e,a.entityLogicalName);return R2(e,{...a,entityMetadataId:o},!0,i)},async delete(e,t){let r=await qc(e,t),n=r?`_contextentity_value eq ${r}`:`contextvalue eq '${(0,mr.odataLiteral)(t)}'`,i=`/appactions${(0,mr.odataQuery)([["$select","appactionid"],["$filter",n]])}`,a=await(0,P2.collectPages)(e,i,"deleteArtifact('command')");for(let o of a)o.appactionid&&await(0,xr.deleteRecord)(e,"appactions",o.appactionid)}};async function R2(e,t,r,n){let i=t.entityMetadataId?(0,mr.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",a=nW(t.rows),o={};try{await rW(e,t,a,i,r,n,o)}catch(s){throw(0,O2.withPartialTokens)(s,{memberEtags:o})}return{id:t.entityLogicalName,etag:null,memberEtags:o}}async function rW(e,t,r,n,i,a,o){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,mr.normalizeGuid)(c.appactionid,"id"),p=(s=a?.[d])!==null&&s!==void 0?s:c.etag,f=(0,xr.echoWrite)("appactionid",p?{"If-Match":p}:void 0),m=`/appactions(${d})${f.query}`,h=(0,xr.ensureSuccess)(await e.patch(m,c.body,f.options),e.apiUrl(m));o[d]=(0,xr.readEtag)(h)}else{let d=(0,xr.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};if(f["[email protected]"]===void 0){if(!n)throw new O2.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${c.appactionid}' for entity '${t.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);f["[email protected]"]=`/entities(${n})`}let m=(0,xr.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),h=(0,xr.readCreatedId)(m,"appactionid");h&&(o[(0,mr.normalizeGuid)(h,"appactionid")]=(0,xr.readEtag)(m))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,mr.normalizeGuid)(c,"id");await(0,xr.deleteRecord)(e,"appactions",d,(u=a?.[d])!==null&&u!==void 0?u:void 0),delete o[d]}}function nW(e){let t=new Map(e.map(a=>[a.appactionid,a])),r=new Set,n=[],i=a=>{if(r.has(a.appactionid))return;let o=a.body["[email protected]"];if(typeof o=="string"){let s=/\(([^)]+)\)/.exec(o),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(a.appactionid),n.push(a)};return e.forEach(i),n}});var j2=y(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.commandRegistration=Eo.CommandAdapter=void 0;var Ve=(T2(),Mr(_2)),F2=Nr(),hr=Cr(),iW=x2(),aW=lt(),Co=ae(),Eg="$ClientSvg:",Cg=".svg",oW=2,sW=1,lW=1,M2="entityMetadataId",uW=new Set(["@odata.etag","IconWebResourceId","OnClickEventJavaScriptWebResourceId","VisibilityFormulaComponentLibraryId","OnClickEventFormulaComponentLibraryId","ContextEntity","_appmoduleid_value","_contextentity_value","_createdby_value","_createdonbehalfby_value","_iconwebresourceid_value","_modifiedby_value","_modifiedonbehalfby_value","_onclickeventformulacomponentlibraryid_value","_onclickeventjavascriptwebresourceid_value","_organizationid_value","_parentappactionid_value","_visibilityformulacomponentlibraryid_value","createdon","modifiedon","overriddencreatedon","overwritetime","componentstate","componentidunique","solutionid","ismanaged","iscustomizable","versionnumber","importsequencenumber","timezoneruleversionnumber","utcconversiontimezonecode","statecode","statuscode","scope"]),Gc=class{toArtifact(t){var r,n,i,a,o,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let f of l){let m=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(f),c.set(m,h)}let d=new Map;for(let f of(a=c.get(""))!==null&&a!==void 0?a:[]){let m=mW(f.location),h=(o=d.get(m))!==null&&o!==void 0?o:[];h.push(f),d.set(m,h)}let p=[];for(let[f,m]of d)p.push({location:f,groups:dW(m,c,V2(f),u)});return{id:u,entityLogicalName:u,commandBars:fW(p),bag:{a:[[M2,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Ng(t),appActions:wg(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?wg(r).map(l=>l.appactionid):[]),i=wg(t,new Set([...n].map(l=>l.toLowerCase()))),a=new Set(i.map(l=>l.appactionid)),o=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?DW(l.row):W2(l.row)}}),s=[...n].filter(l=>!a.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Ng(t),rows:o,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,a;let o=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:o,entityLogicalName:o,commandBars:(a=t.commandBars)!==null&&a!==void 0?a:[]}}assignMissingIds(t){return(0,aW.assignMissingIds)(t)}validate(t){let r=[];return(0,hr.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:a})=>{let o=`/commandBars/${a}`;(0,hr.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],o,"bar-location-invalid",r),(0,hr.childObjects)(i,"groups",o,"group",r).forEach(({node:l,index:u})=>{let c=`${o}/groups/${u}`;B2(l.bag)||((0,hr.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),U2((0,hr.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Eo.CommandAdapter=Gc;function B2(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function U2(e,t,r){e.forEach(({node:n,index:i})=>{let a=`${t}/${i}`;B2(n.bag)||(0,hr.optionalGuidId)(n,"id",a,"control-id-invalid",r),(0,hr.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],a,"control-type-invalid",r);let o=n.location;o!==void 0&&(typeof o!="number"||!Number.isInteger(o)||o<0||o>6)&&r.push((0,hr.issue)(`${a}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(o)}`)),n.action!==void 0&&n.action!==null&&((0,hr.isJsonObject)(n.action)?(0,hr.optionalEnum)(n.action,"type",["javascript"],`${a}/action`,"action-type-invalid",r):r.push((0,hr.issue)(`${a}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,hr.childObjects)(n,"children",a,"control",r);s.length>0&&U2(s,`${a}/children`,r)})}function Sg(e){return{a:Object.entries(e)}}function cW(e){return Object.fromEntries(e.a)}function zc(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Ng(e){let t=zc(e.bag,M2);return typeof t=="string"?t:""}function dW(e,t,r,n){var i,a;let o=[],s=[];for(let l of jc(e))l.type===Ve.ButtonType.Group?o.push({id:q2(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:jc((a=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&a!==void 0?a:[]).map(u=>Wc(u,t,r,n)),bag:Sg(l)}):s.push(Wc(l,t,r,n));return s.length>0&&o.unshift({id:NW(n,r),title:"",controls:s}),o}function Dg(e){let t=e.bag?zc(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function Wc(e,t,r,n){var i,a,o,s,l;let u=q2(e.name,n),c={id:u,type:hW(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Sg(e)},d=$2(e);d&&(c.icon=d);let p=pW(e);p&&(c.action=p),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let f=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(f&&f.length>0){let m=[],h=[];for(let v of jc(f))if(v.type===Ve.ButtonType.Group){let b=(a=v.appactionid)!==null&&a!==void 0?a:"",E=Sg(v);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(o=v.appactionid)!==null&&o!==void 0?o:void 0,c.flyoutGroupBag=E);let C=[];for(let N of jc((l=t.get((s=v.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let R=Wc(N,t,r,n);m.push(R),C.push(Dg(R))}h.push({id:b,bag:E,childIds:C})}else m.push(Wc(v,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function $2(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Eg)?e.fonticon.slice(Eg.length)+Cg:e.fonticon}function pW(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,a={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(a.libraryName=n.name);let o=e.onclickeventjavascriptparameters;return typeof o=="string"&&o&&(a.parameters=o),a}function L2(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function jc(e){return[...e].sort((t,r)=>L2(t)-L2(r))}function fW(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,a;return((i=t[r.location])!==null&&i!==void 0?i:9)-((a=t[n.location])!==null&&a!==void 0?a:9)})}function q2(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let r=e.split("!");return r.length===2?r[1]:e}function mW(e){switch(e){case Ve.Location.Form:case Ve.Location.QuickForm:return"MainTab";case Ve.Location.HomePageGrid:case Ve.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function V2(e){switch(e){case"MainTab":return Ve.Location.Form;case"HomeTab":return Ve.Location.HomePageGrid;default:return Ve.Location.SubGridStandard}}function hW(e){switch(e){case Ve.ButtonType.Dropdown:return"FlyoutAnchor";case Ve.ButtonType.Split:return"SplitButton";default:return"Button"}}function gW(e){switch(e){case"FlyoutAnchor":return Ve.ButtonType.Dropdown;case"SplitButton":return Ve.ButtonType.Split;default:return Ve.ButtonType.Standard}}function vW(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function G2(e,t){var r,n,i;return((n=(r=e.bag)===null||r===void 0?void 0:r.a.length)!==null&&n!==void 0?n:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function wg(e,t=new Set){var r,n,i,a;let o=[],s=Ng(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=V2(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var m;return(m=f.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(f=>!G2(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(vW(f)){let h=bW(f,u,void 0,e,s);o.push(h),m=h.appactionid}for(let h of(a=f.controls)!==null&&a!==void 0?a:[])z2(h,u,m,e,s,o,d?p:void 0,t),p+=1}}return o}function z2(e,t,r,n,i,a,o,s=new Set){var l;let u=yW(e,t,r,n,i,o);a.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!G2(h,s)),p=(h,v,b)=>{z2(h,t,v,n,i,a,d?b:void 0,s)},f=e.flyoutGroups;if(f&&f.length>0){let h=new Map(c.map(N=>[Dg(N),N])),v=new Set,b=0,E;for(let[N,R]of f.entries()){let O=R.id||(N===0?Ag(u.appactionid):_g("flyout-group",`${u.appactionid}#${N}`)),F=k2(O,t,u.appactionid,n,i,R.bag);a.push(F);let k=F.appactionid;E===void 0&&(E=k);for(let P of R.childIds){let V=h.get(P);!V||v.has(P)||(v.add(P),p(V,k,b),b+=1)}}let C=E??Ag(u.appactionid);for(let N of c){let R=Dg(N);v.has(R)||(v.add(R),p(N,C,b),b+=1)}return}let m=e.flyoutGroupId||Ag(u.appactionid);a.push(k2(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,v]of c.entries())p(v,m,h)}function yW(e,t,r,n,i,a){let o=Ig(e,t,r,n,i),s=o.row;a!==void 0&&typeof s.sequence!="number"&&(s.sequence=a);let l=$2(s);return e.location!==void 0&&(s.location=e.location),s.type=gW(e.type),s.buttonlabeltext=e.label,AW(s,e.icon,l),CW(s,e.action),EW(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...o,row:s}}function bW(e,t,r,n,i){let a=Ig(e,t,r,n,i);return a.row.type=Ve.ButtonType.Group,a.row.grouptitle=e.title,a}function k2(e,t,r,n,i,a){let o=Ig({id:e,bag:a},t,r,n,i),s=o.row;return s["[email protected]"]=`/appactions(${(0,Co.normalizeGuid)(r,"Command flyout group id")})`,s.type=Ve.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),o}function Ig(e,t,r,n,i){let a,o,s,l;if(e.bag&&e.bag.a.length>0){a=cW(e.bag),o=!0;let u=zc(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=zc(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,a=wW(l,t,n,i),o=!1,s=null;return r?a["[email protected]"]=`/appactions(${(0,Co.normalizeGuid)(r,"Command parent appaction id")})`:o&&typeof a._parentappactionid_value=="string"&&a._parentappactionid_value&&a.type!==Ve.ButtonType.Group&&(a["[email protected]"]=null),delete a._parentappactionid_value,{appactionid:l,exists:o,etag:s,row:a}}function wW(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Ve.Context.Entity,contextvalue:r.entityLogicalName,scope:Ve.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,Co.normalizeGuid)(n,"Command context entity metadata id")})`),i}function AW(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Co.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Cg)?Eg+t.slice(0,t.length-Cg.length):t,e.IconWebResourceId=null}function EW(e){let t=(n,i)=>{let a=e[n];if(typeof a!="string"||a.length===0||e[`${i}@odata.bind`]!==void 0)return;let o=(0,Co.normalizeGuid)(a,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${o})`};e.onclickeventtype===sW&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===lW)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function CW(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=oW,t.webResourceId){let r=(0,Co.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function SW(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function _g(e,t){let r="";for(let n=0;n<4;n+=1)r+=SW(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Ag(e){return _g("flyout-group",e)}function NW(e,t){return _g("loose-group",`${e}|${t}`)}function W2(e){let t={...e};for(let r of uW)delete t[r];return t}function DW(e){let t=W2(e);for(let r of Ve.CannotUpdateAppActionColumns)delete t[r];return t}function IW(){return{adapter:new Gc,api:iW.commandApi,publish:(e,t,r)=>(0,F2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,F2.boundEntityPublishScope)(t)}}Eo.commandRegistration=IW});var H2=y(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.chartApi=void 0;var _W=Pt(),Zt=be(),So=ae(),TW="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",PW="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";Hc.chartApi={async get(e,t){let r=(0,So.normalizeGuid)(t,"id"),n=await(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,So.odataQuery)([["$select",TW]]);return{raw:(0,Zt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",(0,So.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueryvisualizations${(0,So.odataQuery)([["$select",PW],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,So.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,_W.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var a,o;return{type:"chart",id:(a=i.savedqueryvisualizationid)!==null&&a!==void 0?a:"",name:(o=i.name)!==null&&o!==void 0?o:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Zt.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${i.query}`,o=(0,Zt.ensureSuccess)(await e.post(a,(0,Zt.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(a));return{id:(0,Zt.resolveCreatedId)(o,"savedqueryvisualizationid","chart",r),etag:(0,Zt.readEtag)(o)}},async update(e,t,r,n){let i=r,a=(0,So.normalizeGuid)(t,"id"),o=(0,Zt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Zt.requireEtag)(n,"chart",a)}),s=`/savedqueryvisualizations(${a})${o.query}`,l=(0,Zt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},o.options),e.apiUrl(s));return{id:a,etag:(0,Zt.readEtag)(l)}},delete(e,t){return(0,Zt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var dP=y(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.chartRegistration=Do.ChartAdapter=void 0;var Tg=Kn(),K2=Cr(),nn=_i(),J2=Nr(),RW=H2(),Pg=Qn(),OW=lt(),xW=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],FW=new Map(xW.map(e=>[e.toLowerCase(),e]));function eP(e){var t;return e&&(t=FW.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function LW(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function kW(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,v)=>({alias:`agg_${v}`,series:h})),a=e.categories.map((h,v)=>({alias:`grp_${v}`,category:h})),o=h=>`<attribute alias="${h.alias}" name="${No(h.series.attribute)}" aggregate="${No(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${No(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${No(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,v)=>{if(!h){l.push(v);return}let b=u.get(h);b?b.push(v):u.set(h,[v])};i.forEach(h=>c(h.series.relatedEntity,o(h))),a.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,v])=>`<link-entity name="${No(h)}">${v.join("")}</link-entity>`).join(""),p=l.join("")+d,f=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=a[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${No(n)}">${p}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${f}</category></categorycollection></datadefinition>`}var Kc=class{toArtifact(t){var r,n,i,a,o,s,l;(0,Pg.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,nn.parseXmlRoot)(u,"<datadefinition/>"),p=(0,nn.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(a=t.name)!==null&&a!==void 0?a:"",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:tP(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:iP(d),categories:aP(d),presentation:rP(p),dataBag:u?(0,nn.projectElementBag)(d):void 0,presentationBag:c?(0,nn.projectElementBag)(p):void 0,rowBag:MW(t.charttype,t.type)}}fromArtifact(t){(0,Pg.installDomShim)();let{datadescription:r,presentationdescription:n}=BW(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:Q2(t.rowBag,"charttype"),type:Q2(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,a,o,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(a=u.presentationdescription)!==null&&a!==void 0?a:"",primaryentitytypecode:(o=u.primaryentitytypecode)!==null&&o!==void 0?o:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,a,o,s,l;(0,Pg.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,OW.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:u,chartType:(o=t.chartType)!==null&&o!==void 0?o:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,K2.childObjects)(n,"series","","series",r),(0,K2.childObjects)(n,"categories","","category",r),r}};Do.ChartAdapter=Kc;function MW(e,t){let r=[];return e!==void 0&&r.push(["charttype",String(e)]),t!==void 0&&r.push(["type",String(t)]),r.length>0?{a:r,c:[]}:void 0}function Q2(e,t){if(!e)return;let r=e.a.find(([i])=>i===t);if(!r)return;let n=parseInt(r[1],10);return Number.isNaN(n)?void 0:n}function tP(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return eP(t[r].getAttribute("ChartType"));return"Column"}function rP(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],a=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return a&&(r.title=a),r}function Jc(e){return e.getElementsByTagName("fetch")[0]}function nP(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],a=i.getAttribute("name");if(!a)continue;let o=i.getElementsByTagName("attribute");for(let s=0;s<o.length;s+=1){let l=o[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,a)}}return t}function iP(e){let t=Jc(e);if(!t)return[];let r=nP(t),n=t.getElementsByTagName("attribute"),i=[];for(let a=0;a<n.length;a+=1){let o=n[a],s=o.getAttribute("aggregate");if(!s)continue;let l=o.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=o.getAttribute("charttype");c&&(u.seriesType=eP(c));let d=o.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=r.get(p);f&&(u.relatedEntity=f),i.push(u)}return i}function aP(e){var t;let r=Jc(e);if(!r)return[];let n=nP(r),i=r.getElementsByTagName("attribute"),a=[];for(let o=0;o<i.length;o+=1){let s=i[o];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=n.get(p);f&&(u.relatedEntity=f),a.push(u)}return a}function BW(e){if(!X2(e.dataBag)||!X2(e.presentationBag)){let a=kW(e);return{datadescription:a,presentationdescription:nj(e,a)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=Y2(e.dataBag,"datadefinition",t),n=Y2(e.presentationBag,"Chart",t),i=iP(r);if(!Rg(e.series,i)){let a=Og(r);UW(t,r,e.series);let o=Og(r),s=o.length>0?o:e.series.map(()=>"");oP(t,n,s,a,e.chartType)}return Rg(e.categories,aP(r))||$W(t,r,e.categories),e.chartType!==tP(n)&&uP(n,e.chartType),Rg(e.presentation,rP(n))||cP(n,e.presentation),{datadescription:(0,nn.serializeNode)(r),presentationdescription:(0,nn.serializeNode)(n)}}function X2(e){return!!e&&(e.c.length>0||e.a.length>0)}function oP(e,t,r,n,i){let a,o=t.childNodes;for(let d=0;d<o.length;d+=1)if(o[d].nodeType===1&&o[d].tagName==="Series"){a=o[d];break}a||(a=e.createElement("Series"),t.insertBefore(a,t.firstChild));let s=[],l=a.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,p)=>{let f=s[p];if(!f)return;let m=u.get(d);m?m.push(f):u.set(d,[f])});let c=r.map(d=>{let p=u.get(d),f=p&&p.length>0?p.shift():void 0;if(f)return f;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)a.removeChild(d);for(let d of c)a.appendChild(d)}function Og(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function Y2(e,t,r){let n={n:t,a:(0,Tg.mergeAttrs)(e.a,[]),c:(0,Tg.spliceChildren)(e.c,[])};return(0,Tg.rebuildRaw)(n,(0,nn.domEngine)(r),null)}function UW(e,t,r){let n=Jc(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sP(e,t,i,HW(n),r,JW,{aliasPrefix:"aggregate_column",addRef:GW,removeRef:jW})}function $W(e,t,r){let n=Jc(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sP(e,t,i,KW(n),r,QW,{aliasPrefix:"groupby_column",addRef:zW,removeRef:WW})}function sP(e,t,r,n,i,a,o){let s=new Map;for(let f of n){let m=f.getAttribute("alias");m&&s.set(m,f)}let l=new Set,u=[],c=(f,m)=>{var h;let v=XW(r,f),b=m.relatedEntity;(v??void 0)!==(b??void 0)&&((h=f.parentNode)===null||h===void 0||h.removeChild(f),Z2(e,r,f,b))};for(let f of i){let m=f.alias?s.get(f.alias):void 0;m&&!l.has(m)?(a(m,f),c(m,f),l.add(m)):u.push(f)}let d=n.filter(f=>!l.has(f)),p=0;for(let f of u)if(p<d.length){let m=d[p];a(m,f),c(m,f),l.add(m),p+=1}else{let m=e.createElement("attribute"),h=f.alias||VW(t,o.aliasPrefix);m.setAttribute("alias",h),a(m,f),Z2(e,r,m,f.relatedEntity),o.addRef(e,t,h)}for(let f of n)if(!l.has(f)){let m=f.getAttribute("alias");m&&o.removeRef(t,m),ZW(f)}}function qW(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let a=n[i].getAttribute("alias");a&&t.add(a)}}return t}function VW(e,t){let r=qW(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function lP(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function GW(e,t,r){let n=lP(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let a=e.createElement("measurecollection"),o=e.createElement("measure");o.setAttribute("alias",r),a.appendChild(o),i.appendChild(a)}function zW(e,t,r){let n=lP(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function WW(e,t){let r=e.getElementsByTagName("category");for(let n=0;n<r.length;n+=1)r[n].getAttribute("alias")===t&&r[n].removeAttribute("alias")}function jW(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let a=0;a<n.length;a+=1)n[a].getAttribute("alias")===t&&i.push(n[a]);for(let a of i){let o=a.parentNode;o?.removeChild(a),o&&o.tagName==="measurecollection"&&!tj(o)&&((r=o.parentNode)===null||r===void 0||r.removeChild(o))}}function HW(e){let t=[],r=e.getElementsByTagName("attribute");for(let n=0;n<r.length;n+=1)r[n].getAttribute("aggregate")&&t.push(r[n]);return t}function KW(e){var t;let r=[],n=e.getElementsByTagName("attribute");for(let i=0;i<n.length;i+=1)((t=n[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&r.push(n[i]);return r}function JW(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function QW(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.getAttribute("dategrouping")!==null&&e.removeAttribute("dategrouping")}function XW(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function Z2(e,t,r,n){n?YW(e,t,n).appendChild(r):t.appendChild(r)}function YW(e,t,r){let n=t.getElementsByTagName("link-entity");for(let a=0;a<n.length;a+=1)if(n[a].getAttribute("name")===r)return n[a];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function ZW(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!ej(t))){let r=t.parentNode;r&&r.removeChild(t)}}function ej(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1){let i=n.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function tj(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function uP(e,t){let r=e.getElementsByTagName("Series"),n=!1;for(let i=0;i<r.length;i+=1)r[i].getAttribute("ChartType")&&(r[i].setAttribute("ChartType",t),n=!0);if(!n){for(let i=0;i<r.length;i+=1)if(!rj(r[i])){r[i].setAttribute("ChartType",t);return}}}function rj(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName==="Series")return!0}return!1}function cP(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],a=e.getElementsByTagName("Legends");for(let o=0;o<a.length;o+=1)i.push(a[o]);if(t.showLegend&&i.length===0){let o=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),o.appendChild(s),e.appendChild(o)}else if(!t.showLegend)for(let o of i)(r=o.parentNode)===null||r===void 0||r.removeChild(o)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function nj(e,t){let r=(0,nn.parseXmlRoot)(LW(),"<Chart/>");uP(r,e.chartType),cP(r,e.presentation);let n=Og((0,nn.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&oP(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,nn.serializeNode)(r)}function Rg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function No(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ij(){return{adapter:new Kc,api:RW.chartApi,publish:(e,t,r)=>(0,J2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,J2.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Do.chartRegistration=ij});var hP=y(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.dashboardApi=_o.dashboardEntity=void 0;var aj=Pt(),vi=be(),Io=ae(),pP=tf();function fP(e){return e&&e.toLowerCase()!=="none"?e:void 0}_o.dashboardEntity=fP;var mP="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",oj={select:mP,required:["name","type","objecttypecode","istabletenabled"]},sj="formid,name,type,objecttypecode",lj=0,uj=10;_o.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Io.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Io.odataQuery)([["$select",mP]]),i=(0,vi.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,vi.readEtag)(i)}},async list(e,t){let r=[`(type eq ${lj} or type eq ${uj})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Io.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Io.odataQuery)([["$select",sj],["$filter",r.join(" and ")]])}`;return(await(0,aj.collectPages)(e,n,"listArtifacts('dashboard')")).map(a=>{var o,s;let l=fP(a.objecttypecode);return{type:"dashboard",id:(o=a.formid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,vi.echoWrite)("formid"),a=`/systemforms${i.query}`,o={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(o.objecttypecode=n.objecttypecode);let s=(0,vi.ensureSuccess)(await e.post(a,(0,vi.withClientMintedId)(o,"formid",r),i.options),e.apiUrl(a));return{id:(0,vi.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,vi.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,pP.patchSystemForm)(e,(0,Io.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,oj)},readToken(e,t){return(0,pP.readSystemFormContentEtag)(e,(0,Io.normalizeGuid)(t,"id"))},delete(e,t){return(0,vi.deleteRecord)(e,"systemforms",t)}}});var _P=y(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.dashboardRegistration=an.TILE_CLASS_ID=an.DashboardAdapter=void 0;var nl=Kn(),gr=_i(),xg=Nr(),rl=Cr(),AP=hP(),Fg=Qn(),Yi=lt(),EP=ae(),CP=ha(),gP="0",Lg="10",cj=new Map([["{E7A81278-8635-4D9E-8D4D-59480B391C5B}","chart"],["{FD2A7985-3187-444E-908D-6624B21F69C0}","iframe"],["{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}","webresource"],["{EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8}","stream"],["{06375649-C143-495E-A496-C962E5B4488E}","timeline"],["{8C54228C-1B25-4909-A12A-F2B968BB0D62}","powerbi"],["{F9A8A302-114E-466A-B582-6771B2AE0D92}","assistant"]]),dj="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Xc=class{constructor(t=CP.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,a,o;(0,Fg.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,gr.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(a=t.description)!==null&&a!==void 0?a:"",dashboardType:pj(t.type),entityLogicalName:(o=(0,AP.dashboardEntity)(t.objecttypecode))!==null&&o!==void 0?o:null,enabledForMobile:!!t.istabletenabled,layoutType:fj(l),components:vP(l,this.lcid),bag:(0,gr.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Fg.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Lg:gP,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:yP(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){return{name:t.name,description:t.description,formxml:yP(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Lg:gP,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,a,o,s,l,u;(0,Fg.installDomShim)();let c=(0,gr.parseXmlRoot)(Dj(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Yi.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(a=t.dashboardType)!==null&&a!==void 0?a:"Standard",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:vP(c,this.lcid),bag:(0,gr.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let r=t;(typeof r.id!="string"||r.id.length===0)&&(r.id=(0,Yi.newId)())}return t}validate(t){let r=[],n=(0,rl.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:a,index:o})=>{let s=`/components/${o}`;for(let l of["position","parameters"]){let u=a[l];u!==void 0&&!(0,rl.isJsonObject)(u)&&r.push((0,rl.issue)(`${s}/${l}`,`component-${l}-must-be-object`,`a component ${l} must be a JSON object when present, got ${u===null?"null":typeof u}`))}if((0,rl.isJsonObject)(a.position)){let l=il(a.position);i.has(l)?r.push((0,rl.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};an.DashboardAdapter=Xc;function pj(e){return String(e??"")===Lg?"Interactive":"Standard"}function fj(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function Y(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let a=n[i];a.nodeType===1&&a.tagName.toLowerCase()===t&&r.push(a)}return r}function vP(e,t){let r=[];return Y(e,"tabs").flatMap(i=>Y(i,"tab")).forEach((i,a)=>{Y(i,"columns").flatMap(s=>Y(s,"column")).forEach((s,l)=>{Y(s,"sections").flatMap(c=>Y(c,"section")).forEach((c,d)=>{mj(c,{tabIndex:a,columnIndex:l,sectionIndex:d},r,t)})})}),r}function mj(e,t,r,n){Y(e,"rows").flatMap(a=>Y(a,"row")).forEach((a,o)=>{Y(a,"cell").forEach((s,l)=>{let u=hj(s,{...t,rowIndex:o,cellIndex:l},n);u&&r.push(u)})})}function hj(e,t,r){var n,i;let a=DP((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(a.toLowerCase().startsWith("spacer"))return null;let o=Y(e,"control")[0];if(!o)return null;let s=(i=o.getAttribute("classid"))!==null&&i!==void 0?i:"",l=yj(o),u=bj(s,l,o),c=gj(o);return{id:o.getAttribute("id")||a,type:u,name:NP(e,r),classId:s,position:t,colspan:kg(e,"colspan",1),rowspan:kg(e,"rowspan",1),parameters:l,bag:(0,gr.projectElementBag)(e),...c?{icProperties:c}:{}}}function SP(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName.toLowerCase()==="icproperties")return n}}function gj(e){let t=SP(e);return t?(0,gr.serializeNode)(t):void 0}function vj(e,t,r){let n=SP(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,a=(0,nl.rebuildRaw)((0,nl.rawFromNode)((0,gr.nodeLikeFromDom)(i)),(0,gr.domEngine)(e),null);n&&(0,gr.serializeNode)(n)===(0,gr.serializeNode)(a)||(n?t.replaceChild(a,n):t.appendChild(a))}function NP(e,t){var r,n;let i=Y(e,"labels")[0];if(!i)return"";let a=Y(i,"label"),o=(r=a.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:a[0];return(n=o?.getAttribute("description"))!==null&&n!==void 0?n:""}function yj(e){var t;let r={},n=Y(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let a=0;a<i.length;a+=1){let o=i[a];o.nodeType===1&&(r[o.tagName]=((t=o.textContent)!==null&&t!==void 0?t:"").trim())}return r}function bj(e,t,r){var n;let i=cj.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===dj?"assistant":i:"unknown"}function kg(e,t,r){var n;let i=parseInt((n=e.getAttribute(t))!==null&&n!==void 0?n:"",10);return Number.isNaN(i)?r:i}function DP(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function wj(e,t){let r={n:"form",a:(0,nl.mergeAttrs)(e.bag.a,[]),c:(0,nl.spliceChildren)(e.bag.c,[])};return(0,nl.rebuildRaw)(r,(0,gr.domEngine)(t),null)}function yP(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=wj(e,r);return Cj(r,n,e.components,t),Aj(r,n,e.components,t),(0,gr.serializeNode)(n)}function Aj(e,t,r,n){let i=IP(t);for(let a of r)i.has(il(a.position))||Ej(e,t,a,n)}function Ej(e,t,r,n){var i,a,o,s;let l=(a=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&a!==void 0?a:0,u=Ij(t,e,l);for(let V of Y(u,"row"))Y(V,"cell").some(q=>Y(q,"control").length>0)||u.removeChild(V);let c=r.classId||an.TILE_CLASS_ID[r.type]||an.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&bP(r.bag,"id")?String(bP(r.bag,"id")):Qc((0,Yi.newId)()),f=r.id?Qc(r.id):Qc((0,Yi.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),v=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=Y(u,"row"),E=b[b.length-1],C=E?Y(E,"cell").reduce((V,q)=>V+kg(q,"colspan",1),0):0;(!E||C+v>h)&&(E=e.createElement("row"),u.appendChild(E));let N=e.createElement("cell");N.setAttribute("id",p),N.setAttribute("colspan",String(v)),N.setAttribute("rowspan",String(d)),N.setAttribute("showlabel","true");let R=e.createElement("labels"),O=e.createElement("label");O.setAttribute("description",(o=r.name)!==null&&o!==void 0?o:""),O.setAttribute("languagecode",String(n)),R.appendChild(O),N.appendChild(R);let F=e.createElement("control");F.setAttribute("id",f),F.setAttribute("classid",Qc(c));let k=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let V of Object.keys(P)){let q=(0,EP.createSafeXmlElement)(e,V,"dashboard tile parameter");q.textContent=P[V],k.appendChild(q)}F.appendChild(k),N.appendChild(F),E.appendChild(N)}function bP(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Cj(e,t,r,n){var i;let a=IP(t),o=new Set(r.map(s=>il(s.position)));for(let s of r){let l=a.get(il(s.position));if(!l)continue;let u=Y(l,"control")[0];u&&(Sj(e,l,s.name,n),Nj(e,u,s.parameters),wP(l,"colspan",s.colspan),wP(l,"rowspan",s.rowspan),s.icProperties!==void 0&&vj(e,u,s.icProperties))}for(let[s,l]of a)o.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function IP(e){let t=new Map;return Y(e,"tabs").flatMap(n=>Y(n,"tab")).forEach((n,i)=>{Y(n,"columns").flatMap(o=>Y(o,"column")).forEach((o,s)=>{Y(o,"sections").flatMap(u=>Y(u,"section")).forEach((u,c)=>{Y(u,"rows").flatMap(p=>Y(p,"row")).forEach((p,f)=>{Y(p,"cell").forEach((m,h)=>{var v;DP((v=m.getAttribute("id"))!==null&&v!==void 0?v:"").toLowerCase().startsWith("spacer")||Y(m,"control")[0]&&t.set(il({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:h}),m)})})})})}),t}function il(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Sj(e,t,r,n){if(r===NP(t,n))return;let i=Y(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let a=Y(i,"label").find(o=>o.getAttribute("languagecode")===String(n));a||(a=e.createElement("label"),a.setAttribute("languagecode",String(n)),i.appendChild(a)),a.setAttribute("description",r)}function Nj(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let a=Y(t,"parameters")[0];a||(a=e.createElement("parameters"),t.appendChild(a));let o=new Map,s=a.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&o.set(u.tagName,u)}for(let l of i){let u=r[l],c=o.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,EP.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,a.appendChild(d)}}}function wP(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function Dj(e=2){let t=`{${(0,Yi.newId)()}}`,r=`{${(0,Yi.newId)()}}`,n=`{${(0,Yi.newId)()}}`,i=Math.max(1,Math.floor(e));return`<form><tabs><tab id="${t}" name="General" showlabel="true" expanded="true" verticallayout="true"><columns><column width="100%"><sections><section id="${r}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${n}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}an.TILE_CLASS_ID={chart:"E7A81278-8635-4D9E-8D4D-59480B391C5B",list:"E7A81278-8635-4D9E-8D4D-59480B391C5B",iframe:"FD2A7985-3187-444E-908D-6624B21F69C0",webresource:"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"};function Qc(e){return`{${e.replace(/[{}]/g,"")}}`}function Ij(e,t,r){var n;let i=Y(e,"tabs").flatMap(u=>Y(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let a=Y(i,"columns").flatMap(u=>Y(u,"column"))[0];if(!a)throw new Error("addDashboardTile: dashboard formxml has no <column>");let o=Y(a,"sections").flatMap(u=>Y(u,"section")),s=(n=o[r])!==null&&n!==void 0?n:o[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=Y(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function _j(e=CP.DEFAULT_LCID){return{adapter:new Xc(e),api:AP.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,xg.publishBoundEntity)(t,n):(0,xg.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,xg.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}an.dashboardRegistration=_j});var GP=y(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});ed.genPageApi=void 0;var Zc=Pt(),BP=Ol(),Ie=be(),se=ae(),Fr=cu(),ke=te(),UP=lt();function Tj(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var on="uxagentprojects",ea="uxagentprojectfiles",sl="agentconversationmessages",ll="uxagentprojectid",Dt="uxagentprojectfileid",ta="agentconversationmessageid",al=`${ll},name`,Pj=`${Dt},filename,filetype`,$P=2e8,qP=200000001,ra={"MSCRM.IncludeUnpublished":"true"},Mg={};function Zi(e,t){return{"MSCRM.VersioningChangeset":e,...ra,...t}}async function Ug(e,t,r,n){var i;let a=`/${t}(${r})`+(0,se.odataQuery)([["$select",n]]),o=(0,Ie.ensureSuccess)(await e.get(a,{headers:{...ra}}),e.apiUrl(a));return{row:(i=o.body)!==null&&i!==void 0?i:{},etag:(0,Ie.readEtag)(o)}}async function Yc(e,t,r=ra){let n=`/${ea}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ie.ensureSuccess)(i,e.apiUrl(n));let a=i.body,o=Tj(a);if(o)return{status:"available",data:(0,Fr.bytesToBase64)(o)};if(typeof a=="string")return{status:"available",data:(0,Fr.utf8ToBase64)(a)};throw new ke.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof a}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function VP(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Rj(e,t,r,n,i,a){if(!e.supportsBinaryPatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let o=`/${ea}(${t})/filecontent`,s=(0,Fr.base64ToBytes)(n);(0,se.assertNoControlChars)(r,"generative-page file name"),(0,Ie.ensureSuccess)(await e.patchRaw(o,s,{headers:Zi(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":VP(r),...a?{"If-Match":"*"}:{}})}),e.apiUrl(o))}async function ol(e,t,r=ra){let n=`/${ea}`+(0,se.odataQuery)([["$select",Pj],["$filter",`_${ll}_value eq ${t}`]]);return(await(0,Zc.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(a=>({row:a,etag:typeof a["@odata.etag"]=="string"?a["@odata.etag"]:null}))}async function Bg(e,t){let r=`/${sl}`+(0,se.odataQuery)([["$select",`${ta},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Zc.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...ra}})}async function TP(e,t){var r,n,i;let{row:a,etag:o}=await Ug(e,on,t,al),s=new Map;for(let{row:l,etag:u}of await ol(e,t))s.set((0,se.normalizeGuid)(String((r=l[Dt])!==null&&r!==void 0?r:""),Dt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=a.name)!==null&&i!==void 0?i:""),etag:o,rows:s}}function PP(e,t,r){var n,i,a,o,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,se.normalizeGuid)(c.id,"file id");u.add(d);let p=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new ke.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!p)throw new ke.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}p&&c.unchanged||(p?(p.filename!==c.name||p.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:p!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((o=(a=t.messages)===null||a===void 0?void 0:a.length)!==null&&o!==void 0?o:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function qg(e){let t=(0,Fr.base64ToUtf8)(e);return(0,Fr.utf8ToBase64)(t)===(0,Fr.bytesToBase64)((0,Fr.base64ToBytes)(e))?t:void 0}function Oj(e,t,r,n){var i,a,o,s,l,u,c,d;let p=t.sender==="user"?{changeSet:n,dataSources:(a=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&a!==void 0?a:[],model:(s=(o=r.messageContext)===null||o===void 0?void 0:o.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[ta]:(0,se.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${on}(${e})`,message:t.message,messagecontext:JSON.stringify(p),messagesender:t.sender==="user"?$P:qP}}async function xj(e,t,r){var n,i,a,o;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(p=>p.id).filter(p=>typeof p=="string"&&p!=="").map(p=>(0,se.normalizeGuid)(p,"message id"));if(s.length===0)return r;let l=`/${sl}`+(0,se.odataQuery)([["$select",`${ta},message,messagesender,_regardingobjectid_value`],["$filter",s.map(p=>`${ta} eq ${p}`).join(" or ")]]),u=await(0,Zc.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...ra}});if(u.length===0)return r;let c=new Map(u.map(p=>{var f;return[String((f=p[ta])!==null&&f!==void 0?f:"").toLowerCase(),p]})),d=[];for(let p of(i=r.messages)!==null&&i!==void 0?i:[]){let f=p.id?c.get((0,se.normalizeGuid)(p.id,"message id")):void 0;if(!f){d.push(p);continue}if(!(String((a=f.message)!==null&&a!==void 0?a:"")===p.message&&Number(f.messagesender)===(p.sender==="user"?$P:qP)&&String((o=f._regardingobjectid_value)!==null&&o!==void 0?o:"").toLowerCase()===t))throw new ke.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${p.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function $g(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${on}`,body:(0,Ie.withClientMintedId)({name:t.name},ll,e),headers:Zi(n)};case"createRow":return{method:"POST",path:`/${ea}`,body:(0,Ie.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${ll}@odata.bind`]:`/${on}(${e})`},Dt,(0,se.normalizeGuid)(t.file.id,"file id")),headers:Zi(n)};case"renameRow":return{method:"PATCH",path:`/${ea}(${(0,se.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Zi(n,{"If-Match":"*"})};case"content":{let i=qg(t.data);if(i===void 0)throw new ke.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,se.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${ea}(${(0,se.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Zi(n,{"x-ms-file-name":VP(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${ea}(${t.fileId})`,headers:Zi(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${on}(${e})`,body:{name:t.name},headers:Zi(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${sl}`,body:Oj(e,t.turn,r,n)};default:{let i=t;throw new ke.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function RP(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||qg(r.data)!==void 0)}async function OP(e,t,r,n,i){await(0,BP.postChangeSet)(e,r.map(a=>$g(t,a,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function xP(e,t,r,n,i){var a;let o=[];for(let s of r){if(s.kind==="message"){o.push(s);continue}if(s.kind==="content"){await Rj(e,(0,se.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=$g(t,s,n,i),u={headers:(a=l.headers)!==null&&a!==void 0?a:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Ie.ensureSuccess)(c,e.apiUrl(l.path))}if(o.length===0)return{warnings:[],turnRecorded:!0};try{let s=o.map(l=>$g(t,l,n,i));if(e.supportsAtomicBatch)await(0,BP.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ie.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function FP(e,t,r,n,i,a,o){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...o,u]});try{let u=await TP(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,se.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,N]of c){let R=u.rows.get(C);R&&(R.filename!==N.name||R.filetype!==N.fileType)&&d.push(`file '${N.name}' is stored as '${R.filename}' (type ${R.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let N=await Yc(e,(0,se.normalizeGuid)(C.file.id,"file id")),R=(0,Fr.bytesToBase64)((0,Fr.base64ToBytes)(C.data));(N.status!=="available"||N.data!==R)&&d.push(N.status==="available"?`file '${C.file.name}' holds ${(0,Fr.base64ToBytes)(N.data).byteLength} byte(s) that differ from the ${(0,Fr.base64ToBytes)(R).byteLength} written`:`file '${C.file.name}' holds no content`)}let p=new Set(r.filter(C=>C.kind==="content").map(C=>(0,se.normalizeGuid)(C.file.id,"file id")));for(let[C,N]of c)!p.has(C)&&(await Yc(e,C)).status==="available"&&d.push(`file '${N.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let f=await TP(e,t),m=[...f.rows.keys()],h=f.etag!==u.etag||f.rows.size!==u.rows.size||m.some(C=>{var N,R;return((N=u.rows.get(C))===null||N===void 0?void 0:N.etag)!==((R=f.rows.get(C))===null||R===void 0?void 0:R.etag)}),v=m.length!==i.size||m.some(C=>!i.has(C)),b={},E=[];for(let[C,N]of f.rows){let R=c.has(C)||!a?N.etag:(s=a.get(C))!==null&&s!==void 0?s:null;b[C]=R,R!==N.etag&&E.push(N.filename)}return h||v||!f.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Fj({id:t,etag:f.etag,memberEtags:b},[...o,...E.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}ed.genPageApi={async get(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),{row:i,etag:a}=await Ug(e,on,n,al),o=await ol(e,n),s={},l=[];for(let{row:c,etag:d}of o){let p=(0,se.normalizeGuid)(String((r=c[Dt])!==null&&r!==void 0?r:""),Dt);s[p]=d;let f=await Yc(e,p);l.push({...c,content:f})}let u=await Bg(e,n);return{raw:{project:i,files:l,conversation:u},etag:a,memberEtags:s}},async getPublished(e,t){var r,n;let i=(0,se.normalizeGuid)(t,"id"),a=`/${on}(${i})`+(0,se.odataQuery)([["$select",al]]),o=await e.get(a);if(o.status===404)return null;(0,Ie.ensureSuccess)(o,e.apiUrl(a));let s=(r=o.body)!==null&&r!==void 0?r:{},l={},u=[],c=await ol(e,i,Mg);for(let{row:v,etag:b}of c){let E=(0,se.normalizeGuid)(String((n=v[Dt])!==null&&n!==void 0?n:""),Dt);l[E]=b,u.push({...v,content:await Yc(e,E,Mg)})}let d=v=>v.map(({row:b,etag:E})=>`${String(b[Dt])}@${String(E)}`).sort().join("|"),p=()=>new ke.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),f=await e.get(a);if(f.status===404)throw p();(0,Ie.ensureSuccess)(f,e.apiUrl(a));let m=await ol(e,i,Mg);if([(0,Ie.readEtag)(o),(0,Ie.readEtag)(f),...[...c,...m].map(v=>v.etag)].some(v=>!v))throw new ke.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Ie.readEtag)(f)!==(0,Ie.readEtag)(o)||d(m)!==d(c))throw p();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ie.readEtag)(o),memberEtags:l}},async list(e,t){let r=`/${on}`+(0,se.odataQuery)([["$select",al]]);return(await(0,Zc.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...ra}})).map(i=>{var a,o;return{type:"genPage",id:String((a=i[ll])!==null&&a!==void 0?a:""),name:String((o=i.name)!==null&&o!==void 0?o:""),isDirty:!1}})},async create(e,t,r){var n;let i=t;MP(e,i);let a=r?(0,se.normalizeGuid)(r,"id"):(0,UP.newId)();kP(e,a,i);let o=PP(a,i,void 0),s=LP(),l=[],u=!0;RP(e,o)?await OP(e,a,o,i,s):{warnings:l,turnRecorded:u}=await xP(e,a,o,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(p=>(0,se.normalizeGuid)(p.id,"file id"))),d=await FP(e,a,o,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var a,o;let s=r,l=(0,se.normalizeGuid)(t,"id");MP(e,s);let u=await xj(e,l,s);kP(e,l,u);let c=await ol(e,l),{row:d,etag:p}=await Ug(e,on,l,al);if(n&&p&&n!==p)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${p}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!p)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let f=new Map(c.map(({row:F})=>{var k,P;return[(0,se.normalizeGuid)(String((k=F[Dt])!==null&&k!==void 0?k:""),Dt),{filename:String((P=F.filename)!==null&&P!==void 0?P:""),filetype:Number(F.filetype)}]})),m=new Set(f.keys()),h=new Set(((a=u.files)!==null&&a!==void 0?a:[]).map(F=>(0,se.normalizeGuid)(F.id,"file id")));if(!i)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let v=new Set(Object.keys(i).map(F=>F.toLowerCase()));for(let F of h)if(!m.has(F)&&v.has(F))throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${F}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let F of m)if(!v.has(F))throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${F}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:F,etag:k})=>{var P;return[(0,se.normalizeGuid)(String((P=F[Dt])!==null&&P!==void 0?P:""),Dt),k]}));for(let[F,k]of Object.entries(i)){let P=F.toLowerCase();if(!m.has(P))continue;let V=b.get(P);if(!k||!V)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${k?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(k!==V)throw new ke.SdkError(Ie.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${k}, server ${V}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let E=PP(l,u,{rows:f,name:String((o=d.name)!==null&&o!==void 0?o:"")});if(E.length===0)return{id:l,etag:p,memberEtags:Object.fromEntries(c.map(({row:F,etag:k})=>{var P;return[(0,se.normalizeGuid)(String((P=F[Dt])!==null&&P!==void 0?P:""),Dt),k]}))};let C=LP(),N=[],R=!0;RP(e,E)?await OP(e,l,E,u,C):{warnings:N,turnRecorded:R}=await xP(e,l,E,u,C);let O=await FP(e,l,E,u,h,b,N);return R?O:{...O,intentPending:!0}},async delete(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),i=await Bg(e,n);await(0,Ie.deleteRecord)(e,on,n);let a=new Set(i.map(l=>{var u;return String((u=l[ta])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),o=!1;try{for(let l of await Bg(e,n)){let u=String((r=l[ta])!==null&&r!==void 0?r:"");u!==""&&a.add(u)}}catch{o=!0}let s=[];for(let l of a)try{await(0,Ie.deleteRecord)(e,sl,l)}catch(u){u instanceof ke.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||o)throw new ke.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${a.size} message(s) could not be (${s.join(", ")})`:"")+(o?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${sl} rows regarding '${n}'.`)}};function LP(){return`uxagentproject_${(0,UP.newId)()}`}function Fj(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function kP(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new ke.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function MP(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(o=>o.content.status==="available"&&!o.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(o=>o.content.status==="available"&&!o.unchanged&&qg(o.content.data)===void 0)&&!e.supportsBinaryPatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var aR=y(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.genPageRegistration=Po.GenPageAdapter=void 0;var Lj=GP(),kj=Nr(),me=Cr(),od=lt(),sd=cu(),na=te(),zP=df(),Vg=mp(),yi=2e8,tR=200000001,Rn={source:{name:"src/pages/page.tsx",fileType:yi},output:{name:"src/pages/page.compiled",fileType:tR},config:{name:"config.json",fileType:yi},prompt:{name:"firstPrompt.json",fileType:yi}},rR=Object.keys(Rn),Mj=["dataSources","model","connectorBindings","actionBindings"],Bj=["userMessage","agentMessage"],WP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Uj={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},$j="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function nR(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let o=0;o<32;o+=1)i.push(parseInt((r=n[o])!==null&&r!==void 0?r:"0",16)^parseInt(t[o],16));i[12]=4,i[16]=i[16]&3|8;let a=i.map(o=>(Number.isNaN(o)?0:o).toString(16)).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}function td(e,t){return nR(e,Uj[t])}function qj(e,t){let r=nR(e,$j),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function jP(e){return typeof e=="string"&&e.trim()!==""?e:(0,od.newId)()}function Pn(e){return(0,me.isJsonObject)(e)?e:{}}function To(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function rd(e){return JSON.parse(JSON.stringify(e))}function Vj(e){let t=Pn(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function nd(e){if(!e||e.status!=="available")return;let t=(0,sd.base64ToUtf8)(e.data);return(0,sd.utf8ToBase64)(t)===e.data?t:void 0}function id(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,me.isJsonObject)(t)?t:void 0}catch{return}}function HP(e,t){if(t===yi&&e.includes("page.tsx"))return"source";if(t===tR&&e.includes(".compiled"))return"output";if(t===yi&&e===Rn.config.name)return"config";if(t===yi&&e===Rn.prompt.name)return"prompt"}function KP(e){let t=e.toLowerCase();return rR.some(r=>Rn[r].name.toLowerCase()===t)}function Gg(e){return Object.fromEntries(e)}function iR(e,t,r,n){let i=[],a=new Set,o=new Set(t),s=l=>{if(a.has(l))return;let u=o.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(a.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),Gg(i)}function JP(e){var t,r,n;return iR({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Mj,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function QP(e){var t,r;return iR({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Bj,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function XP(e,t,r){let n=[];for(let[i,a]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return!1;e.dataSources=a}else if(i==="model"){if(typeof a!="string")return!1;e.model=a}else i==="connectorBindings"?e.connectorBindings=a:i==="actionBindings"?e.actionBindings=a:n.push([i,a]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=Gg(n)),!0}function YP(e,t,r){let n=[];for(let[i,a]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof a!="string")return!1;i==="userMessage"?e.firstPrompt=a:e.firstAgentMessage=a}else n.push([i,a]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=Gg(n)),!0}function cl(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var Gj=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function ZP(e){return cl(e)?[]:Gj.filter(t=>e[t]!==void 0).map(t=>(0,me.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function eR(){return(0,me.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function ad(e){return{status:"available",data:(0,sd.utf8ToBase64)(e)}}function ul(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var ld=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Pn(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(v=>{var b,E,C;let N=Pn(v);return{id:String((b=N.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((E=N.filename)!==null&&E!==void 0?E:""),fileType:Number((C=N.filetype)!==null&&C!==void 0?C:yi),content:Vj(N.content)}}),a=Array.isArray(r?.conversation)?r.conversation.map(v=>{var b,E;let C=Pn(v);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((E=C.createdon)!==null&&E!==void 0?E:"")}}):void 0,o=v=>a?{...v,conversation:a}:v,s=new Map,l=[],u=!0;for(let v of i){let b=HP(v.name,v.fileType);b?((s.has(b)||v.name!==Rn[b].name)&&(u=!1),s.set(b,v)):(KP(v.name)&&(u=!1),l.push(v))}if(!u||s.size===0)return o(ul(n,i));let c=ul(n,l),d={rows:{}};for(let[v,b]of s)d.rows[v]=b.id;let p=s.get("source");if(p){let v=nd(p.content);if(v===void 0)return o(ul(n,i));c.source=v}let f=s.get("output");f&&(d.output=f.content);let m=s.get("config");if(m){let v=id(nd(m.content));if(!v||!XP(c,d,v))return o(ul(n,i))}let h=s.get("prompt");if(h){let v=id(nd(h.content));if(!v||!YP(c,d,v))return o(ul(n,i))}return c.bag=d,o(c)}async toApiPayload(t,r,n){var i,a,o,s,l,u,c,d,p,f,m,h,v,b,E;if(r&&!To((i=t.conversation)!==null&&i!==void 0?i:[],(a=r.conversation)!==null&&a!==void 0?a:[]))throw new na.ValidationError("genPage",t.id,[(0,me.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let C=ZP(t);if(C.length>0)throw new na.ValidationError("genPage",t.id,C);let N=[],R=r===void 0,O=R&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(cl(O)){let P=(s=(o=O.bag)===null||o===void 0?void 0:o.rows)!==null&&s!==void 0?s:{},V=Z=>{var ye;return(ye=P[Z])!==null&&ye!==void 0?ye:td(O.id,Z)},q=(Z,ye,xe)=>{N.push({id:V(Z),name:Rn[Z].name,fileType:Rn[Z].fileType,content:ye,unchanged:xe})};if(O.source!==void 0){q("source",ad(O.source),!R&&r?.source===O.source&&P.source!==void 0);let Z=!R&&r?.source===O.source&&To((l=r?.dataSources)!==null&&l!==void 0?l:[],(u=O.dataSources)!==null&&u!==void 0?u:[]),ye=nd((c=O.bag)===null||c===void 0?void 0:c.output);Z&&P.output!==void 0&&(0,zP.isLoadableGenPageOutput)(ye)?q("output",{status:"retain"},!0):q("output",ad(await this.compile(O,O.source,n)),!1)}else{if(P.source!==void 0)throw new na.ValidationError("genPage",O.id,[eR()]);if(P.output!==void 0){if(!R&&!To((d=r?.dataSources)!==null&&d!==void 0?d:[],(p=O.dataSources)!==null&&p!==void 0?p:[]))throw new na.ValidationError("genPage",O.id,[(0,me.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);q("output",{status:"retain"},!0)}}let ze=JP(O),Tt=!R&&r!==void 0&&To(JP(r),ze);(R||P.config!==void 0||!Tt)&&q("config",ad(JSON.stringify(ze)),Tt&&P.config!==void 0);let Be=QP(O),Qe=!R&&r!==void 0&&To(QP(r),Be);(P.prompt!==void 0||Object.keys(Be).length>0&&!Qe)&&q("prompt",ad(JSON.stringify(Be)),Qe&&P.prompt!==void 0)}for(let P of(f=O.files)!==null&&f!==void 0?f:[]){let V=(m=r?.files)===null||m===void 0?void 0:m.find(q=>q.id===P.id);N.push({id:P.id,name:P.name,fileType:P.fileType,content:P.content,unchanged:V!==void 0&&To(V,P)})}let F=[];if(O.newTurn){let P=O.newTurn.id,V=q=>P?{id:qj(P,q)}:{};F.push({...V("user"),sender:"user",message:O.newTurn.prompt}),O.newTurn.agentMessage&&F.push({...V("agent"),sender:"agent",message:O.newTurn.agentMessage})}let k=(v=(h=O.bag)===null||h===void 0?void 0:h.config)!==null&&v!==void 0?v:{};return{name:O.name,files:N,...F.length>0?{messages:F,messageContext:{dataSources:(b=O.dataSources)!==null&&b!==void 0?b:[],model:(E=O.model)!==null&&E!==void 0?E:"",enabledTools:Array.isArray(k.enabledTools)?k.enabledTools:[],configurableTools:Array.isArray(k.configurableTools)?k.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:rd(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,a,o,s,l;if(!cl(t)&&!t.newTurn)return t;let u=rd(t);if(delete u.newTurn,!cl(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(a=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&a!==void 0?a:{}}};for(let d of(o=r.files)!==null&&o!==void 0?o:[]){let p=rR.find(m=>Rn[m].name===d.name&&Rn[m].fileType===d.fileType);if(!p||u.files.some(m=>m.id===d.id)||(c.rows[p]=d.id,d.content.status!=="available"))continue;let f=(0,sd.base64ToUtf8)(d.content.data);p==="output"?c.output={status:"available",data:d.content.data}:p==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,XP(u,c,(s=id(f))!==null&&s!==void 0?s:{})):p==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,YP(u,c,(l=id(f))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,a)=>i.id<a.id?-1:i.id>a.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,me.isJsonObject)(r)||typeof r.id=="string"&&WP.test(r.id)?t:{...t,newTurn:{...r,id:(0,od.newId)()}}}async compile(t,r,n){var i;let a=(i=t.dataSources)!==null&&i!==void 0?i:[],o=[],s=[];if(a.forEach((p,f)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,p);h&&h.columnDetailComplete===!0?o.push(h):s.push((0,me.issue)(`/dataSources/${f}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${p}' could not be read completely (a choice or lookup request failed), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${p}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new na.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new na.ValidationError("genPage",t.id,[(0,me.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=o.length>0?(0,Vg.buildGenPageRuntimeTypes)(o):void 0,c=o.length>0?(0,Vg.buildGenPageLegacyEnums)(o):void 0,d=(0,zP.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new na.ValidationError("genPage",t.id,d.diagnostics.map(zj));return d.code}metadataNeeds(t){return t.source===void 0||!Array.isArray(t.dataSources)?[]:t.dataSources.filter(r=>typeof r=="string"&&r!=="").map(r=>({entityLogicalName:r,fieldName:"",needsColumnDetail:!0}))}createDefault(t){var r,n;let i=jP(t.id),a={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(o=>{var s,l,u;return{id:jP(o.id),name:(s=o.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=o.fileType)!==null&&l!==void 0?l:yi,content:(u=o.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(a.source=t.source),t.dataSources!==void 0&&(a.dataSources=[...t.dataSources]);for(let o of["model","firstPrompt","firstAgentMessage"])t[o]!==void 0&&(a[o]=t[o]);return t.newTurn!==void 0&&(a.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(a.connectorBindings=rd(t.connectorBindings)),t.actionBindings!==void 0&&(a.actionBindings=rd(t.actionBindings)),a.source!==void 0&&(a.bag={rows:{source:td(i,"source"),output:td(i,"output"),config:td(i,"config")}}),a}assignMissingIds(t){if(t==null)return{id:(0,od.newId)()};if(!(0,me.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,od.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,me.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Pn(Pn(n.bag).rows).source!==void 0&&r.push(eR()),r.push(...ZP(t)),n.newTurn!==void 0){let s=Pn(n.newTurn);(!(0,me.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,me.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,me.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!WP.test(s.id))&&r.push((0,me.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,me.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!Vg.TABLE_LOGICAL_NAME.test(l)?r.push((0,me.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,me.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,me.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,me.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let a=cl(t),o=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Pn(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,me.issue)(u,"file-id-required","a generative-page file needs an id"));else{let v=o.get(d);v!==void 0?r.push((0,me.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${v}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):o.set(d,l)}let p=typeof c.name=="string"?c.name:"",f=p.split("/");p===""||/[\u0000-\u001F\u007F]/.test(p)||p.includes("\\")||f.some(v=>v===""||v==="."||v==="..")?r.push((0,me.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${p}'`)):a&&(KP(p)||HP(p,Number(c.fileType))!==void 0)&&r.push((0,me.issue)(u+"/name","file-name-reserved",`'${p}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,me.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Pn(m);h.status==="available"?typeof h.data!="string"&&r.push((0,me.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,me.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Po.GenPageAdapter=ld;function zj(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,me.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,me.issue)("/source",e.rule,`${t}: ${e.message}`)}function Wj(){return{adapter:new ld,api:Lj.genPageApi,publish:(e,t)=>(0,kj.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Po.genPageRegistration=Wj});var sR=y(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});dd.reconcileBpfSecurityRoles=void 0;var cd=be(),ud=ae(),jj="Global",oR={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Hj(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,ud.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,o=(n=(r=(0,cd.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[],s={},l=new Set;return Object.keys(oR).forEach(u=>{let c=o.find(d=>d.PrivilegeType===oR[u]);if(c){let d=(0,ud.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Kj(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,o=(n=(r=(0,cd.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(o.map(s=>(0,ud.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function Jj(e,t,r){if(r.length===0)return;let n={Privileges:r.map(a=>({Depth:jj,PrivilegeId:a}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,cd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Qj(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,cd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Xj(e,t,r){var n;if(!r||r.length===0)return;let i=await Hj(e,t.toLowerCase());for(let a of r){let o=(0,ud.normalizeGuid)(a.roleId,"roleId"),s=new Set(((n=a.access)!==null&&n!==void 0?n:[]).map(p=>i.byAccess[p]).filter(p=>!!p)),l=await Kj(e,o),u=new Set([...l].filter(p=>i.all.has(p))),c=[...s].filter(p=>!u.has(p)),d=[...u].filter(p=>!s.has(p));await Jj(e,o,c);for(let p of d)await Qj(e,o,p)}}dd.reconcileBpfSecurityRoles=Xj});var gR=y(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.bpfApi=void 0;var vr=Ai(),Yj=Pt(),yr=te(),It=be(),On=ae(),Zj=sR(),eH={"Content-Type":"application/json",Accept:"application/json"},pd={...eH,Prefer:"return=representation"},tH=new Set([408,502,503,504]),rH=`category eq ${vr.WorkflowCategory.BusinessProcessFlow} and type eq ${vr.WorkflowTypeCode.Definition} and businessprocesstype eq ${vr.BusinessProcessType.BusinessFlow}`,nH="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",iH="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",aH=["xaml","name","description","processorder"];async function lR(e,t){var r;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let n=String((r=t.record.uniquename)!==null&&r!==void 0?r:"");n!==""&&await(0,Zj.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function hR(e,t,r){let n={statecode:vr.StateCode.Activated,statuscode:vr.StatusCode.Activated},i=`/workflows(${t})`,a={...pd};return r&&(a["If-Match"]=r),(0,It.ensureSuccess)(await e.patch(i,n,{headers:a}),e.apiUrl(i))}async function uR(e,t,r){return(0,It.readEtag)(await hR(e,t,r))}function cR(e,t){return new yr.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+md(e))}async function fd(e,t){var r;let n=`/workflows(${t})${(0,On.odataQuery)([["$select","statecode"]])}`,i=(0,It.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(r=i.body)===null||r===void 0?void 0:r.statecode,o=Number(a);if(a==null||a===""||!Number.isFinite(o))throw new yr.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return o}async function zg(e,t,r){if(await fd(e,t)!==vr.StateCode.Activated)return{deactivated:!1,etag:null};let n={statecode:vr.StateCode.Draft,statuscode:vr.StatusCode.Draft},i=`/workflows(${t})`,a={...pd};r&&(a["If-Match"]=r);let o;try{o=await e.patch(i,n,{headers:a})}catch(l){return await dR(e,t,l)}if(tH.has(o.status))return await dR(e,t,new yr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${o.status} from an intermediary, so whether it committed is unknown.`));let s=(0,It.ensureSuccess)(o,e.apiUrl(i));return{deactivated:!0,etag:(0,It.readEtag)(s)}}async function dR(e,t,r){let n;try{n=await fd(e,t)}catch{n=void 0}if(n===vr.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===vr.StateCode.Activated)throw r;let i=new yr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw i.cause=r,i}async function pR(e,t){let r=(0,On.normalizeGuid)(t,"workflowid");try{return await hR(e,r,null),"restored"}catch{try{let n=await fd(e,r);return n===vr.StateCode.Activated?"restored":n===vr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function fR(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,a=r==="disabled"?new yr.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new yr.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${i}`);return a.cause=n,a}async function oH(e,t){try{return await fd(e,t),"survived"}catch(r){return r instanceof yr.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function sH(e,t,r){if(r)try{let{deactivated:n,etag:i}=await zg(e,t,r),a=n?i:r;if(a)return await(0,It.deleteRecord)(e,"workflows",t,a),"removed"}catch{}return oH(e,t)}function md(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function mR(e,t){return new yr.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${md(e)}`)}function lH(e,t){let r=new yr.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${md(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function uH(e,t){let r=new yr.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${md(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function cH(e,t){let r=new yr.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function dH(e){let t={};for(let r of aH)e[r]!==void 0&&(t[r]=e[r]);return t}hd.bpfApi={async get(e,t){let n=`/workflows(${(0,On.normalizeGuid)(t,"id")})${(0,On.odataQuery)([["$select",iH]])}`,i=(0,It.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,It.readEtag)(i)}},async list(e,t){let r=[rH];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,On.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,On.odataQuery)([["$select",nH],["$filter",r.join(" and ")]])}`;return(await(0,Yj.collectPages)(e,n,"listArtifacts('bpf')")).map(a=>{var o,s;return{type:"bpf",id:(o=a.workflowid)!==null&&o!==void 0?o:"",name:(s=a.name)!==null&&s!==void 0?s:"",entityLogicalName:a.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,On.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",a=(0,It.ensureSuccess)(await e.post(i,r.record,{headers:pd}),e.apiUrl(i)),o=(0,It.readEtag)(a);if(!o)throw mR(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=o;try{r.status==="Active"&&(s=await uR(e,n,o)),await lR(e,r)}catch(l){let u=await sH(e,n,s);throw u==="survived"?lH(n,l):u==="unknown"?uH(n,l):l instanceof yr.SdkError&&l.code===It.VERSION_CONFLICT_CODE?cH(n,l):l}if(!s)throw mR(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,a=(0,On.normalizeGuid)(t,"id"),o=(0,It.requireEtag)(n,"bpf",a),{deactivated:s,etag:l,uncertainCause:u}=await zg(e,a,o);try{if(u!==void 0)throw u;let c=o;if(s){if(!l)throw cR(a,"deactivation");c=l}let d=`/workflows(${a})`,p=(0,It.ensureSuccess)(await e.patch(d,dH(i.record),{headers:{...pd,"If-Match":c}}),e.apiUrl(d)),f=(0,It.readEtag)(p);if(i.status==="Active"){if(!f)throw cR(a,"definition write");f=await uR(e,a,f)}return await lR(e,i),{id:a,etag:f}}catch(c){if(s){let d=await pR(e,a);if(d!=="restored")throw fR(a,"to apply an edit, the edit failed",d,c)}throw c}},async delete(e,t){let r=(0,On.normalizeGuid)(t,"id"),{deactivated:n}=await zg(e,r,null);try{await(0,It.deleteRecord)(e,"workflows",r)}catch(i){if(n){let a=await pR(e,r);if(a!=="restored")throw fR(r,"so it could be deleted, the delete failed",a,i)}throw i}}}});var ZR=y(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.bpfRegistration=Oo.BpfAdapter=void 0;var gd=Ai(),pH=gR(),Wg=Kn(),ia=_i(),TR=Qn(),er=Cr(),jt=lt(),sn=te(),fH=100,Hg='<?xml version="1.0" encoding="utf-16"?>',vR=1033,PR="mxswa:Workflow",mH="mxswa:ActivityReference.Properties",hH="mcwo:StepLabel",gH="mcwb:Control",yR="mcwb:Control.ControlDisplayName",RR="mcwb:Control.DataFieldName",OR="DataFieldName",bR="ControlDisplayName",xR="Literal",vd="x:Null",wR="x:String",Kg="x:Key",Jg="DisplayName",bd="Activities",vH="StepLabels",FR="StageId",LR="StageCategory",kR="NextStageId",MR="ProcessStepId",Qg="IsProcessRequired",BR="EntityComposite",UR="StageComposite",$R="StepComposite";function jg(e){return(0,er.isJsonObject)(e)?e:{}}function ln(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function aa(e,t){var r;return(r=ln(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function un(e){return aa(e,mH)}function _t(e,t){var r;return(r=ln(e).find(n=>n.getAttribute(Kg)===t))!==null&&r!==void 0?r:null}function Ro(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Fn(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function qR(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function dl(e){var t;let r=(t=e.getAttribute(Jg))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function VR(e,t){var r;let n=(r=e.getAttribute(Jg))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Jg,i>=0?n.slice(0,i+2)+t:t)}function GR(e,t){let r=_t(e,vH),n=aa(r,hH);n&&n.setAttribute("Description",t)}function yH(e){let t=_t(e,LR);if(!t||t.tagName===vd)return;let r=Fn(t).trim();return r===""?void 0:Number(r)}function bH(e){let t=_t(e,kR);if(!t||t.tagName===vd)return;let r=Fn(t).trim();return r===""?void 0:r}function zR(e){let t=WR(e);if(!t)return;let r=HR(t,OR,RR);return r===""?void 0:r}function Xg(e,t){let r=ln(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ln(n))r.push(i)}return null}function WR(e){let t=_t(un(e),bd);return t?Xg(t,gH):null}function jR(e,t){let r=e.attributes;for(let n=0;n<r.length;n+=1)if(r[n].name===t)return!0;return!1}function HR(e,t,r){var n;return jR(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":SH(e,r)}function AR(e,t,r,n){if(jR(e,t)){e.setAttribute(t,n);return}if(aa(e,r)){wH(e,r,n);return}throw new sn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function wH(e,t,r){let n=aa(e,t),i=n?Xg(n,xR):null;i&&i.setAttribute("Value",r)}function KR(e){return dl(e)}function wd(e){let t=aa(e,PR),r=[];for(let n of ln(t).filter(i=>Ro(i,BR))){let i=_t(un(n),bd);for(let a of ln(i).filter(o=>Ro(o,UR)))r.push({el:a,entity:KR(n)})}return r}function Yg(e){let t=_t(un(e),bd);return ln(t).filter(r=>Ro(r,$R))}function AH(e){let t=un(e),r=Fn(_t(t,Qg)).trim().toLowerCase(),n=zR(e),i={id:Fn(_t(t,MR)),name:dl(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function EH(e,t){let r=un(e),n=yH(r),i=bH(r),a={id:Fn(_t(r,FR)),name:dl(e),entityLogicalName:t,steps:Yg(e).map(AH)};return n!==void 0&&(a.category=n),i!==void 0&&(a.nextStageId=i),a}function CH(e){return wd(e).map(({el:t,entity:r})=>EH(t,r))}function xn(e){return new sn.NotImplementedError("bpf-structural-authoring",`${e} is not supported yet (this phase authors identity, stage/step names, step required, step field binding, stage categories, and adding/removing/reordering stages & steps on a single-table process; branching, actions, security-role wiring and multi-table processes land in later phases). The rest of the process round-trips losslessly.`)}function SH(e,t){var r;let n=aa(e,t),i=n?Xg(n,xR):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Zg(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let o=0;o<i.length;o+=1)n.setAttribute(i[o].name,i[o].value);let a=t.childNodes;for(let o=0;o<a.length;o+=1){let s=a[o];s.nodeType===1?n.appendChild(Zg(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function JR(e){return _t(un(e),bd)}function NH(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,a=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,jt.newId)(),{body:o}=Ad(e0(i,(0,jt.newId)(),t.id,a));return Zg(e,wd((0,ia.parseXmlRoot)(o,"<Activity/>"))[0].el)}function DH(e,t){let{body:r}=Ad(e0("account",(0,jt.newId)(),(0,jt.newId)(),t.id));return Zg(e,Yg(wd((0,ia.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function QR(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function XR(e,t,r,n){let i=_t(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw xn(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let a=i.parentNode;if(n===void 0||n===""){if(i.tagName!==vd){let s=t.createElement(vd);s.setAttribute(Kg,r),a.replaceChild(s,i)}return}if(i.tagName===wR){Fn(i)!==n&&qR(i,t,n);return}let o=t.createElement(wR);o.setAttribute(Kg,r),o.appendChild(t.createTextNode(n)),a.replaceChild(o,i)}function IH(e,t,r){XR(e,t,LR,r===void 0?void 0:String(r))}function _H(e,t,r){XR(e,t,kR,r)}function YR(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(r(e[n])!==t[n])return!1;return!0}function ER(e){return Fn(_t(un(e),FR))}function CR(e){return Fn(_t(un(e),MR))}function SR(e,t,r){var n,i,a,o;let s=un(e);r.name!==dl(e)&&(VR(e,r.name),GR(s,r.name));let l=Fn(_t(s,Qg)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=_t(s,Qg);u&&qR(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((a=zR(e))!==null&&a!==void 0?a:"")){let u=WR(e);if(!u)throw new sn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(o=r.fieldName)!==null&&o!==void 0?o:"";AR(u,OR,RR,c),c!==""&&HR(u,bR,yR)===""&&AR(u,bR,yR,c)}}function NR(e,t,r,n){var i;let a=un(e);if(!a)throw new sn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==dl(e)&&(VR(e,r.name),GR(a,r.name)),IH(a,t,r.category),_H(a,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw xn("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw xn("stage actions or conditional branching");let o=JR(e);if(!o)throw new sn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new sn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Yg(e);if(YR(l,s.map(d=>d.id),CR)){l.forEach((d,p)=>SR(d,t,s[p]));return}let u=new Map(l.map(d=>[CR(d),d]));if(ln(o).some(d=>!Ro(d,$R)))throw xn("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var p;return(p=u.get(d.id))!==null&&p!==void 0?p:DH(t,d)});QR(o,c),c.forEach((d,p)=>SR(d,t,s[p]))}function TH(e,t,r){let n=aa(e,PR);if(!n)throw new sn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw xn("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new sn.InvalidArgumentError("a BPF must have at least one stage");let i=wd(e),a=i.map(p=>p.el);if(YR(a,r.stages.map(p=>p.id),ER)){i.forEach(({el:p,entity:f},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==f)throw xn(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${f}')`);NR(p,t,h,h.nextStageId)});return}let o=ln(n).filter(p=>Ro(p,BR));if(o.length!==1)throw xn("adding, removing or reordering stages on a multi-table process");let s=o[0],l=KR(s),u=JR(s);if(!u)throw new sn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ln(u).some(p=>!Ro(p,UR)))throw xn("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let p of r.stages)if(p.entityLogicalName&&p.entityLogicalName.trim()!==""&&p.entityLogicalName!==l)throw xn(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(a.map(p=>[ER(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:NH(t,p,l)});QR(u,d),d.forEach((p,f)=>{let m=f<d.length-1?r.stages[f+1].id:void 0;NR(p,t,r.stages[f],m)})}function Ad(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function PH(e){var t,r,n,i,a,o;(0,TR.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,Wg.mergeAttrs)(s.a,[]),c:(0,Wg.spliceChildren)(s.c,[])};return{root:(0,Wg.rebuildRaw)(f,(0,ia.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Hg,eol:(a=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&a!==void 0?a:"lf"}}let l=e.stages[0],u=(o=l?.steps)===null||o===void 0?void 0:o[0],c=e0(e.entityLogicalName,(0,jt.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,jt.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,jt.newId)()),{body:d}=Ad(c);return{root:(0,ia.parseXmlRoot)(d,"<Activity/>"),prolog:Hg,eol:"lf"}}function RH(e){let{root:t,prolog:r,eol:n}=PH(e);TH(t,t.ownerDocument,e);let i=(0,ia.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
-`)),r+i}function OH(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var yd=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,TR.installDomShim)();let i=t,a=typeof i.xaml=="string"?i.xaml:"",o={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(o.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(o.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(o.order=Number(i.processorder)),a.trim()!==""){let{prolog:s,body:l}=Ad(a),u=(0,ia.parseXmlRoot)(l,"<Activity/>");o.stages=CH(u),o.bag={xaml:(0,ia.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(a)?"crlf":"lf"}}return o}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,jt.newId)(),name:t.name,uniquename:OH(t),primaryentity:t.entityLogicalName,xaml:RH(t),category:gd.WorkflowCategory.BusinessProcessFlow,type:gd.WorkflowTypeCode.Definition,businessprocesstype:gd.BusinessProcessType.BusinessFlow,scope:gd.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:fH};t.description!==void 0&&(n.description=t.description);let i={record:n,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new sn.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let a=t.stages&&t.stages.length>0?t.stages.map(IR):[IR({id:(0,jt.newId)(),name:"New Stage",steps:[]})],o={id:t.id&&t.id.trim()!==""?t.id:(0,jt.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:a};return t.uniqueName&&(o.uniqueName=t.uniqueName),t.description!==void 0&&(o.description=t.description),t.order!==void 0&&(o.order=t.order),t.globalActions!==void 0&&(o.globalActions=t.globalActions),t.securityRoles!==void 0&&(o.securityRoles=t.securityRoles),o}assignMissingIds(t){let r=jg(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,jt.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(a=>this.assignMissingIds(a))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,er.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof n}`)),r;let i=Array.isArray(n)?n:[];i.length>30&&r.push((0,er.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let a=new Set,o=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=jg(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,er.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):o.has(p.toLowerCase())?r.push((0,er.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${o.get(p.toLowerCase())})`)):o.set(p.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&a.add(l.entityLogicalName);let f=Array.isArray(l.steps)?l.steps:[];f.length===0&&r.push((0,er.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,er.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let m=new Map;f.forEach((h,v)=>{let b=`${c}/steps/${v}`,E=typeof jg(h).id=="string"?h.id.trim():"";E===""?r.push((0,er.issue)(`${b}/id`,"step-id-required","a step needs an id")):m.has(E.toLowerCase())?r.push((0,er.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(E.toLowerCase(),v)}),l.branch&&!DR(i,l.branch.nextStageId)&&r.push((0,er.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!DR(i,l.nextStageId)&&r.push((0,er.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),a.size>5&&r.push((0,er.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${a.size}`));let s=xH(i);return s>=0&&r.push((0,er.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Oo.BpfAdapter=yd;function xH(e){let t=new Map(e.map(r=>[r.id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function DR(e,t){return e.some(r=>r.id===t)}function IR(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(_R):[_R({id:(0,jt.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,jt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(r=e.entityLogicalName)!==null&&r!==void 0?r:"",steps:n};return e.category!==void 0&&(i.category=e.category),e.nextStageId!==void 0&&(i.nextStageId=e.nextStageId),e.relationshipName!==void 0&&(i.relationshipName=e.relationshipName),e.actions!==void 0&&(i.actions=e.actions),e.branch!==void 0&&(i.branch=e.branch),i}function _R(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,jt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(r.fieldName=e.fieldName),e.required!==void 0&&(r.required=e.required),r}function e0(e,t,r,n){return`${Hg}<Activity x:Class="XrmWorkflow00000000000000000000000000000000" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mcwb="clr-namespace:Microsoft.Crm.Workflow.BusinessProcessFlowActivities;assembly=Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mcwo="clr-namespace:Microsoft.Crm.Workflow.ObjectModel;assembly=Microsoft.Crm, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxs="clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxswa="clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:srs="clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:this="clr-namespace:" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><x:Members><x:Property Name="InputEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /><x:Property Name="CreatedEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /></x:Members><this:XrmWorkflow00000000000000000000000000000000.InputEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.InputEntities><this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings><mxswa:Workflow><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.EntityComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="EntityStep1: ${e}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StageComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StageStep2: New Stage"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StepComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StepStep3: New Step"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><Sequence DisplayName="ControlStep4"><mcwb:Control ControlId="${t}" IsSystemControl="False" IsUnbound="False" SystemStepType="0"><mcwb:Control.ClassId><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ClassId><mcwb:Control.ControlDisplayName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ControlDisplayName><mcwb:Control.DataFieldName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.DataFieldName><mcwb:Control.Parameters><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.Parameters></mcwb:Control></Sequence></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Step" LabelId="${n}" LanguageCode="${vR}" /></sco:Collection><x:String x:Key="ProcessStepId">${n}</x:String><x:Boolean x:Key="IsProcessRequired">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Stage" LabelId="${r}" LanguageCode="${vR}" /></sco:Collection><x:String x:Key="StageId">${r}</x:String><x:Null x:Key="StageCategory" /><x:Null x:Key="NextStageId" /></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><x:Null x:Key="RelationshipName" /><x:Null x:Key="AttributeName" /><x:Boolean x:Key="IsClosedLoop">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></mxswa:Workflow></Activity>`}function FH(){return{adapter:new yd,api:pH.bpfApi,languageSensitive:!0}}Oo.bpfRegistration=FH});var eO=y(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});Ed.buildRegistrations=void 0;var LH=I_(),kH=z_(),MH=d2(),BH=I2(),UH=j2(),$H=dP(),qH=_P(),VH=aR(),GH=ZR();function zH(e){let t=new Map;return t.set("form",(0,LH.formRegistration)(e)),t.set("view",(0,kH.viewRegistration)()),t.set("businessRule",(0,MH.businessRuleRegistration)()),t.set("app",(0,BH.appRegistration)(e)),t.set("command",(0,UH.commandRegistration)()),t.set("chart",(0,$H.chartRegistration)()),t.set("dashboard",(0,qH.dashboardRegistration)(e)),t.set("genPage",(0,VH.genPageRegistration)()),t.set("bpf",(0,GH.bpfRegistration)()),t}Ed.buildRegistrations=zH});var uO=y(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.removeRowSummary=Me.configureRowSummary=Me.buildGptDynamicPrompt=Me.setAppAiFeatures=Me.getAiReadiness=Me.saveSettingValue=Me.retrieveSetting=Me.AI_GATE=void 0;var Lr=be(),Ge=ae(),tO=lt(),Ln=te();Me.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var aO={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},WH=new Set(Object.entries(Me.AI_GATE).filter(([e,t])=>aO[e]===t).map(([e])=>e)),jH={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function t0(e){return jH[e]}var Cd=1e6;function HH(e,t){let r=t0(t),n=()=>{throw new Ln.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Cd} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=a=>r?a?r.enabled:r.disabled:a?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Cd?n():String(e);if(typeof e=="string"){let a=e.trim(),o=a.toLowerCase();if(o==="true")return i(!0);if(o==="false")return i(!1);if(/^[0-9]+$/.test(a)){let s=a.replace(/^0+(?=[0-9])/,"");return s.length>String(Cd).length||Number(s)>Cd?n():s}}return n()}function KH(e,t){let r=t0(t);return r?e===r.enabled:e!=="0"}async function JH(e,t){var r,n,i;let a=`/appmodules${(0,Ge.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(t)}'`]])}`,o=await e.get(a);return o.status>=200&&o.status<300?(i=((n=(r=o.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function QH(e,t){var r,n;let i=`/appmodules${(0,Ge.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(t)}'`]])}`,a;try{a=await e.get(i)}catch(l){throw new Ln.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(a.status<200||a.status>=300)throw new Ln.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${a.status}. Retry, or omit appModuleId to verify by name.`);let o=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o))throw new Ln.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(o.length===0)return;let s=(n=o[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ln.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var rO=new WeakMap;async function XH(e,t){var r,n,i;let a=rO.get(e);if(a||(a=new Map,rO.set(e,a)),a.has(t))return a.get(t);let o=`/settingdefinitions${(0,Ge.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(t)}'`]])}`,s=await e.get(o),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&a.set(t,l),l}async function YH(e,t,r){var n,i;let a=await XH(e,r);if(!t||!a)return;let o=`/appsettings${(0,Ge.odataQuery)([["$select","value"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${a}`]])}`,s=await e.get(o);if(s.status<200||s.status>=300)return;let l=(i=(n=s.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];return l.length>0?{exists:!0,value:l[0].value}:{exists:!1}}var ZH=4,eK=500,nO=20,iO=3e4;function tK(e){if(e===void 0)return ZH;if(!Number.isFinite(e))throw new Ln.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${nO}; got ${e}.`);return Math.min(nO,Math.max(1,Math.floor(e)))}function rK(e){if(e===void 0)return eK;if(!Number.isFinite(e))throw new Ln.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${iO}; got ${e}.`);return Math.min(iO,Math.max(0,Math.floor(e)))}async function nK(e,t,r,n,i,a,o){let s,l,u,c=!1;for(let d=0;d<a;d+=1){d>0&&await new Promise(f=>setTimeout(f,o*d));let p;try{let f=await t();f?(p=await YH(e,f,n),p===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(f){p=void 0,u=f.message}c=p!==void 0,l=p?.exists;try{s=(await Sd(e,n,{appUniqueName:r})).value}catch{}if(p?.exists&&p.value===i)return{result:"proven",effectiveValue:p.value,appOverrideExists:!0}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function oO(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?t0(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Sd(e,t,r={}){var n,i;let a=[`SettingName='${(0,Ge.odataPathLiteral)(t)}'`];r.appUniqueName&&a.push(`AppUniqueName='${(0,Ge.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${a.join(",")})`,l=(i=(n=(0,Lr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Me.retrieveSetting=Sd;async function sO(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Lr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Me.saveSettingValue=sO;async function iK(e,t={}){let r={};for(let[n,i]of Object.entries(Me.AI_GATE)){let{value:a,dataType:o}=await Sd(e,i,t);r[n]={enabled:oO(a,o,n),setting:i,value:a}}return r}Me.getAiReadiness=iK;async function aK(e,t,r,n={}){var i,a;if(!t||!t.trim())throw new Ln.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=tK(n.verifyAttempts),s=rK(n.verifyDelayMs),l=[];for(let[h,v]of Object.entries(r)){if(v===void 0)continue;let b=aO[h];b&&l.push({feature:h,setting:b,requestedValue:HH(v,h)})}let u=[],c=n.appModuleId?(0,Ge.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await QH(e,t);if(h&&(0,Ge.normalizeGuid)(h,"appModuleId")!==c)throw new Ln.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,p=async()=>c||(d||(d=await JH(e,t)),d),f=new Map,m=async h=>{if(WH.has(h))return;let v=Me.AI_GATE[h];if(v){if(!f.has(v))try{let{value:b,dataType:E}=await Sd(e,v);f.set(v,{enabled:oO(b,E,h),setting:v,value:b})}catch{f.set(v,void 0)}return f.get(v)}};for(let{feature:h,setting:v,requestedValue:b}of l)try{await sO(e,v,b,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let E=await nK(e,p,t,v,b,o,s),C={feature:h,setting:v,requestedValue:b,effectiveValue:E.effectiveValue,appOverrideExists:E.appOverrideExists};if(E.result==="proven")u.push({...C,status:"applied"});else if(E.result==="absent"){let N=KH(b,h)?await m(h):void 0;N&&!N.enabled?u.push({...C,status:"skipped",reason:`the write was issued and no app-scope override holding '${b}' was observed for '${v}' after ${o} attempt(s); the org readiness gate '${N.setting}' reads '${N.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...C,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${b}' was observed for '${v}' after ${o} attempt(s) \u2014 it reads '${(i=E.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...C,status:"unverified",reason:`the write was issued but could not be confirmed: ${(a=E.reason)!==null&&a!==void 0?a:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(E){u.push({feature:h,setting:v,requestedValue:b,status:"failed",reason:E.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}Me.setAppAiFeatures=aK;var oK="GptPowerPrompt",sK='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function lO(e){var t,r,n,i;let a=e.entityLogicalName,o=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{o.push({type:"data",id:`${a}.${s.logical}`,text:s.display}),l<e.columns.length-1&&o.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:o,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:a,displayName:a,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Me.buildGptDynamicPrompt=lO;async function lK(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Ge.odataPathLiteral)(t)}')${(0,Ge.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,Lr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function uK(e,t,r={}){var n,i,a,o,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,Ge.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,Lr.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(c)return{modelId:c._aimodel_value,aiSkillConfigId:c.aiskillconfigid};let d=`/msdyn_aitemplates${(0,Ge.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${oK}'`],["$top",1]])}`,p=((s=(o=(a=(0,Lr.ensureSuccess)(await e.get(d),e.apiUrl(d)).body)===null||a===void 0?void 0:a.value)===null||o===void 0?void 0:o[0])!==null&&s!==void 0?s:{}).msdyn_aitemplateid,f=(0,tO.newId)(),m=(0,tO.newId)(),h=JSON.stringify(lO(t)),v={ModelId:f,RunConfigurationId:m,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:h,Source:sK,RunConfiguration:""};(0,Lr.ensureSuccess)(await e.post("/AIModelPublish",v),e.apiUrl("/AIModelPublish"));try{let b=await lK(e,t.entityLogicalName),E={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${b})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},C=(0,Lr.ensureSuccess)(await e.post("/aiskillconfigs",E),e.apiUrl("/aiskillconfigs")),N=(0,Lr.requireCreatedId)(C,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:N}}catch(b){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw b}}Me.configureRowSummary=uK;async function cK(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,Ge.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Ge.odataLiteral)(i)}'`],["$top",1]])}`,o=((n=(r=(0,Lr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!o)return;let s=(0,Ge.normalizeGuid)(o.aiskillconfigid,"aiskillconfigid"),l=o._aimodel_value?(0,Ge.normalizeGuid)(o._aimodel_value,"_aimodel_value"):void 0,u=`/aiskillconfigs(${s})`;if((0,Lr.ensureSuccess)(await e.delete(u),e.apiUrl(u)),l){let c=`/msdyn_aimodels(${l})`;(0,Lr.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Me.removeRowSummary=cK});var pO=y(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.findArtifact=xo.resolveArtifact=void 0;var dt=ae(),kn=lu(),dK=gu(),pK=Pt(),fK=be(),cO=te();async function dO(e,t,r){let n="/uxagentprojects"+(0,dt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,dt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,pK.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(a=>({id:String(a.uxagentprojectid),name:String(a.name)}))}async function mK(e,t,r){var n,i,a,o,s,l,u,c,d,p,f,m,h;switch(t){case"app":{let v=(0,dK.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,dt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),E=(i=(0,fK.ensureSuccess)(await e.get(v),e.apiUrl(v)).body)===null||i===void 0?void 0:i.value,C=E&&E[0];return C?[{id:String(C.appmoduleid),name:String(C.name),appModuleIdUnique:String(C.appmoduleidunique)}]:[]}case"dashboard":return(await(0,kn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"command":{let v=await(0,kn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,dt.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return v&&v.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,kn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,dt.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(b=>({id:String(b.formid),name:String(b.name)}));case"chart":return(await(0,kn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,dt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,dt.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryvisualizationid),name:String(b.name)}));case"view":return(await(0,kn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,dt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,dt.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(b=>({id:String(b.savedqueryid),name:String(b.name)}));case"webResource":return(await(0,kn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,dt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(b=>({id:String(b.webresourceid),name:String(b.name)}));case"solution":return(await(0,kn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,dt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(b=>({id:String(b.solutionid),name:String(b.uniquename)}));case"genPage":return dO(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}xo.resolveArtifact=mK;async function hK(e,t,r){var n,i,a,o,s,l,u;let c=(0,dt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,dt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let v=await(0,kn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,dt.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return v&&v.length?String(r.entity):null}if(t==="genPage"){let v=await dO(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(v.length>1)throw new cO.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",v.length);return v.length===1?v[0].id:null}let p=gK(t,c,d,r),f=t!=="app",m=await(0,kn.queryRecords)(e,p.set,{select:[p.idField],filter:p.filter,top:f?2:1});if(f&&m&&m.length>1)throw new cO.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][p.idField];return h!=null?String(h):null}xo.findArtifact=hK;function gK(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,dt.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var mO=y(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});Dd.seedRecordGraph=void 0;var fO=lu(),vK=xl(),Nd=ae(),yK=te();async function bK(e,t,r={}){var n,i,a,o,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(p=>(0,vK.resolveEntitySetName)(e,p)),c={},d=p=>{var f;return(f=c[p])!==null&&f!==void 0?f:l[p]};for(let p of t){let f=p.entityLogical.toLowerCase(),m=(a=p.matchOn)===null||a===void 0?void 0:a.toLowerCase(),h=[];for(let O of p.records){let F={...O.body};for(let k of(o=O.binds)!==null&&o!==void 0?o:[]){let P=k.parentEntity.toLowerCase(),V=(s=d(P))===null||s===void 0?void 0:s[k.parentIndex];if(!V)throw new yK.InvalidArgumentError(`Cannot resolve bind '${k.navProperty}' on a '${f}' record: parent '${k.parentEntity}'[${k.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let q=(0,Nd.assertODataName)(await u(P),`entity set for parent '${k.parentEntity}'`),ze=(0,Nd.normalizeGuid)(V,`parent id for bind '${k.navProperty}'`);F[`${k.navProperty}@odata.bind`]=`/${q}(${ze})`}h.push(F)}let v=m?h.map(O=>{let F=O[m];return F!=null&&F!==""?String(F):null}):h.map(()=>null),b=new Map;if(m){let O=(0,Nd.assertODataName)(m,"RecordGraph matchOn key"),F=[...new Set(v.filter(k=>k!==null))];if(F.length){let k=F.map(V=>`${O} eq '${(0,Nd.odataLiteral)(V)}'`).join(" or "),P=await(0,fO.queryRecords)(e,f,{select:[O,`${f}id`],filter:k,top:5e3});for(let V of P??[]){let q=V[O];q!=null&&b.set(String(q).toLowerCase(),String(V[`${f}id`]))}}}let E=[],C=new Map,N=h.map((O,F)=>{let k=v[F];if(k&&b.has(k.toLowerCase()))return null;if(k){let P=k.toLowerCase(),V=C.get(P);if(V!==void 0)return V;let q=E.push(O)-1;return C.set(P,q),q}return E.push(O)-1}),R=E.length?await(0,fO.createRecordsBulk)(e,f,E):[];c[f]=h.map((O,F)=>{let k=v[F];return k&&b.has(k.toLowerCase())?b.get(k.toLowerCase()):R[N[F]]})}return{createdIds:c}}Dd.seedRecordGraph=bK});var SO=y(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.getEntityPrivileges=bt.addEntityPrivilegesToRole=bt.deleteSecurityRole=bt.createPersonaRole=bt.createSecurityRole=bt.SDK_ROLE_MARKER=void 0;var kr=be(),it=ae(),tr=te(),Id={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},n0={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},hO={user:1,businessUnit:2,parentChild:3,organization:4},r0={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};bt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function wK(e){return Object.prototype.hasOwnProperty.call(Id,e)?Id[e]:void 0}function AK(e){return Object.prototype.hasOwnProperty.call(n0,e)}var gO=new WeakMap,vO=new WeakMap;async function wO(e,t){var r,n;(0,it.assertODataName)(t,"entity logical name");let i=gO.get(e);i||(i=new Map,gO.set(e,i));let a=i.get(t);if(a)return a;let o=`/EntityDefinitions(LogicalName='${(0,it.odataPathLiteral)(t)}')${(0,it.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,kr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new tr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function EK(e){var t,r,n;let i=vO.get(e);if(i)return i;let a=`/businessunits${(0,it.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,kr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new tr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,it.normalizeGuid)(l,"businessUnitId");return vO.set(e,u),u}async function AO(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new tr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let a=(r=i.scope)!==null&&r!==void 0?r:"user";if(!AK(a))throw new tr.InvalidArgumentError(`Unknown privilege scope '${a}' for entity '${i.entity}'.`);let o=await wO(e,i.entity);for(let s of i.access){let l=wK(s);if(!l)throw new tr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=o.find(m=>m.PrivilegeType===l);if(!u)throw new tr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=r0[a];if(u[c]===!1)throw new tr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${a}' scope.`);let d=(0,it.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),p=n.get(d);if(!p){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:a,entities:new Set([i.entity])});continue}if(p.scope===a){p.entities.add(i.entity);continue}if(!(p.entities.size===1&&p.entities.has(i.entity))){let m=[...p.entities].sort().join(", ");throw new tr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}p.scope=hO[a]>hO[p.scope]?a:p.scope}}return[...n.entries()].map(([i,a])=>({entity:[...a.entities].sort().join(", "),privilegeId:i,privilegeName:a.privilegeName,privilegeType:a.privilegeType,scope:a.scope}))}async function CK(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(o=>({Depth:n0[o.scope],PrivilegeId:o.privilegeId}))},a=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,kr.ensureSuccess)(await e.post(a,i),e.apiUrl(a))}async function yO(e,t,r,n,i){var a,o;let s=`/${t}(${r})/${n}${(0,it.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((o=(a=(0,kr.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||a===void 0?void 0:a.value)!==null&&o!==void 0?o:[]).length>0}async function SK(e,t,r){var n,i;let a=[],o=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,it.normalizeGuid)(l,"teamId");if(!await yO(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,kr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,it.normalizeGuid)(l,"userId");if(!await yO(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,kr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}return{teams:a,users:o}}async function bO(e,t,r){var n,i;let a=`/roles${(0,it.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,it.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,kr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var p;return d.ismanaged!==!0&&((p=d.description)!==null&&p!==void 0?p:"")===bt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new tr.InvalidArgumentError(`A role named '${t}' already exists in this business unit and was not created by the SDK; refusing to modify or assign it. Choose a different persona/role name.`);if(l.length>1)throw new tr.InvalidArgumentError(`Multiple (${l.length}) SDK-owned roles named '${t}' exist in this business unit; refusing to reuse one arbitrarily. Remove the duplicate role(s) and retry.`);let c=l[0].roleid;return c?(0,it.normalizeGuid)(c,"roleId"):void 0}function NK(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,it.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,it.normalizeGuid)(n,"userId"))}}function EO(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function CO(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let a=t.businessUnitId?(0,it.normalizeGuid)(t.businessUnitId,"businessUnitId"):await EK(e),o=await AO(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=NK(t.assignTo),l=await bO(e,i,a),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:bt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${a})`};try{let f=(0,kr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,it.normalizeGuid)((0,kr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let m;try{m=await bO(e,i,a)}catch{m=void 0}if(!m)throw f;l=m}}await CK(e,l,o,u);let c=await SK(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:EO(o),assignedTeams:c.teams,assignedUsers:c.users}}bt.createSecurityRole=CO;async function DK(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let a=[...t.jobs.flatMap(o=>{var s;return(s=o.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return CO(e,{name:i,businessUnitId:t.businessUnitId,privileges:a,assignTo:t.assignTo})}bt.createPersonaRole=DK;async function IK(e,t){let n=`/roles(${(0,it.normalizeGuid)(t,"roleId")})`;(0,kr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}bt.deleteSecurityRole=IK;async function _K(e,t,r){let n=(0,it.normalizeGuid)(t,"roleId");if(r.length===0)throw new tr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await AO(e,r),a={Privileges:i.map(s=>({Depth:n0[s.scope],PrivilegeId:s.privilegeId}))},o=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,kr.ensureSuccess)(await e.post(o,a),e.apiUrl(o)),EO(i)}bt.addEntityPrivilegesToRole=_K;var TK=new Map(Object.keys(Id).map(e=>[Id[e],e]));async function PK(e,t){return(await wO(e,t)).map(n=>{let i=Object.keys(r0).filter(o=>n[r0[o]]!==!1),a=TK.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...a?{access:a}:{},scopes:i}})}bt.getEntityPrivileges=PK});var PO=y(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.createMakerSdk=rr.MakerSdk=rr.PUSH_NOT_ATTEMPTED_CODE=rr.ALREADY_EXISTS_CODE=void 0;var NO=Xd(),ne=te(),br=ca(),RK=Iv(),Pd=xv(),pl=Uv(),OK=Zd(),xK=ay(),i0=oy(),FK=wy(),at=xl(),DO=of(),Mn=lu(),_d=ow(),Fo=pu(),LK=mu(),wt=fw(),kK=df(),MK=wf(),BK=eO(),Td=lt(),UK=ha(),cn=rg(),bi=rp(),$K=3e5,wr=be(),wi=ae(),Lo=uO(),IO=pO(),qK=mO(),VK=wh(),fl=SO();function GK(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new Pd.WorkspaceManager(zK,e.instanceUrl,(0,OK.assertStorageContract)(t))}rr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";rr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var zK="<injected workspaceStorage>",Rd=class{constructor(t){var r,n;this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:UK.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:$K,this.compiler={load:(0,kK.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=GK(t),this.versions=new pl.VersionManager(this.workspace),this.dataverse=new xK.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,BK.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let a=this.artifactKey(t,r),s=((i=this.artifactLocks.get(a))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(a,l),l.then(()=>{this.artifactLocks.get(a)===l&&this.artifactLocks.delete(a)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){var i,a,o;let s=this.requireRegistration(t,"fetchArtifact"),{raw:l,etag:u,memberEtags:c,siblingEtags:d}=await s.api.get(this.dataverse,r),p=s.adapter.fromApiResponse(l);if(!n?.overwrite&&await this.versions.isDirty(t,r)){let m=(a=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&a!==void 0?a:null;if(m&&u&&m!==u)throw new ne.LocalEditsWouldBeLostError(t,r,m,u);let h=await this.workspace.readArtifact(t,r);if(h){let v=await this.versions.getMeta(t,r);if(v&&!v.etag&&u){if(!(0,bi.deepEqual)(v.snapshot,p))throw new ne.LocalEditsWouldBeLostError(t,r,m,u);await this.versions.storeMeta(t,r,{...v,etag:u,fetchedAt:(0,wr.nowIso)()})}return(0,cn.cloneJson)(h)}}await this.workspace.writeArtifact(t,r,p);let f=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:u,languageCode:this.languageCode,projectionVersion:pl.PROJECTION_VERSION,fetchedAt:(0,wr.nowIso)(),snapshot:(0,cn.cloneJson)(p),...c?{memberEtags:c}:{},...d?{siblingEtags:d}:{},...f?.refreshGeneration?{refreshGeneration:f.refreshGeneration,observedGeneration:(o=f.observedGeneration)!==null&&o!==void 0?o:0}:{}}),(0,cn.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,wt.fetchSolutionComponents)(this.dataverse,t),i=[],a=[];for(let o of n)try{let s=await this.resolveComponentType(o);if(!s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"unsupported"});continue}let l=await this.fetchArtifact(s,o.objectId);i.push({type:s,id:o.objectId,name:typeof l.name=="string"?l.name:(r=o.displayName)!==null&&r!==void 0?r:o.objectId,entityLogicalName:typeof l.entityLogicalName=="string"?l.entityLogicalName:void 0,lastFetched:(0,wr.nowIso)(),isDirty:!1})}catch(s){a.push({componentId:o.objectId,componentType:o.componentType,workflowCategory:o.workflowCategory,reason:"failed",error:oa(s)})}return await this.workspace.updateManifest({lastSyncAt:(0,wr.nowIso)()}),{summaries:i,skipped:a}}async fetchEntityMetadata(t){let r=await(0,i0.fetchEntityMetadataFromApi)(this.dataverse,t);return await this.workspace.writeEntityMetadata(t,r),r}generateGenPageRuntimeTypes(t,r){return(0,FK.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,i0.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,i0.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,at.createTable)(this.dataverse,t)}createColumn(t,r){return(0,at.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,at.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,at.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,at.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,DO.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,DO.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,at.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,at.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,at.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,at.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,at.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,at.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large}),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,wi.xmlText)(t)}</entity></entities></importexportxml>`;(0,wr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,at.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,at.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,at.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,at.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,at.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,at.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,at.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,fl.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,fl.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,fl.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,fl.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,fl.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Mn.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Mn.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Mn.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Mn.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Mn.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Mn.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Mn.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,qK.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,IO.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,IO.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,MK.deleteAppCascade)(this.dataverse,t,r),i=(0,wi.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Mn.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Mn.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,_d.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,_d.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,_d.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,_d.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Fo.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Fo.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ne.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:LK.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Fo.setAppSetting)(this.dataverse,t,Fo.HEADER_AND_NAVIGATION_REFRESH,r?Fo.APP_SETTING_ON:Fo.APP_SETTING_OFF)}getSolution(t){return(0,wt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,wt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,wt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,wt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,wt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,wt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,wt.exportSolution)(this.dataverse,t)}importSolution(t){return(0,wt.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,wt.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=await this.getArtifactUnlocked(t,r);return await this.acknowledgeRefresh(t,r),n})}async getArtifactUnlocked(t,r){return(0,cn.cloneJson)(await this.readRaw(t,r))}async acknowledgeRefresh(t,r){var n,i,a;let o=this.artifactKey(t,r),s=await this.versions.getMeta(t,r);this.baselineObserved.has(o)||this.baselineObserved.set(o,(n=s?.observedGeneration)!==null&&n!==void 0?n:0);let l=(i=s?.refreshGeneration)!==null&&i!==void 0?i:0;s&&l!==((a=s.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...s,observedGeneration:l}),this.observedGenerations.set(o,l)}async observedAtInvocation(t,r,n){var i,a;if(n!==void 0)return n;let o=this.baselineObserved.get(this.artifactKey(t,r));return o!==void 0?o:(a=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&a!==void 0?a:0}artifactKey(t,r){return`${t}\0${(0,Pd.canonicalArtifactId)(r)}`}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var a,o;let s=await this.observedAtInvocation(t,r,i);if(((o=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.refreshGeneration)!==null&&o!==void 0?o:0)>s)throw new ne.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new ne.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new ne.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=await this.versions.getMeta(t,r);if(!n)return"skipped";let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,a=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&a<=this.cacheStalenessMs)return"fresh";if(await this.versions.isDirty(t,r))return"skipped";let o=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return(0,bi.deepEqual)(o,s)?"refreshed-unchanged":"refreshed-changed"}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.getArtifactUnlocked(t,r),a=br.JsonPointer.resolve(i,n);if(a===void 0)throw new ne.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,RK.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.workspace.readEntityMetadata(t);if(!r)throw new ne.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(a=>a.logicalName===r);if(!i)throw new ne.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,a),s=br.JsonPointer.resolve(o,n);if(s===void 0)throw new ne.PathNotFoundError(t,r,n);let l=Bn(s)&&Bn(i)?{...s,...i}:i;return br.JsonPointer.set(o,n,(0,cn.cloneJson)(l)),this.assertStructurallyValid(t,r,o,n),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,a){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,o),l=br.JsonPointer.resolve(s,n);if(l===void 0)throw new ne.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Bn(l)||!Bn(i))throw new ne.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(a?.position!==void 0)throw new ne.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let p of Object.keys(i)){if(p==="id")throw new ne.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let f=(0,cn.cloneJson)(i[p]),m=(0,Td.isValueMapKey)(p)||(0,Td.pointerTouchesValueMap)(n);d[p]=m?f:Array.isArray(f)?f.map(h=>Bn(h)?this.assignMissingIds(t,h):h):Bn(f)?this.assignMissingIds(t,f):f}for(let p of Object.keys(d))br.JsonPointer.set(s,br.JsonPointer.append(n,p),d[p]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Td.pointerTouchesValueMap)(n)?(0,cn.cloneJson)(i):this.assignMissingIds(t,(0,cn.cloneJson)(i)),c=jK(l,a?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,a){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,o),u=br.JsonPointer.resolve(l,n);if(u===void 0)throw new ne.PathNotFoundError(t,r,n);let c=br.JsonPointer.resolve(l,i);if(c===void 0)throw new ne.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new ne.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ne.ValidationError(t,r,i,"cannot move an element into its own subtree");br.JsonPointer.remove(l,n);let d=(s=a?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),TO(c);let p=br.JsonPointer.resolve(l,_O(n));return Array.isArray(p)&&p!==c&&TO(p),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,i);if(br.JsonPointer.resolve(a,n)===void 0)throw new ne.PathNotFoundError(t,r,n);return br.JsonPointer.remove(a,n),this.assertStructurallyValid(t,r,a,_O(n)),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var a,o,s;let l=this.registrations.get(t),u=(s=(o=l==null?void 0:(a=l.adapter).validate)===null||o===void 0?void 0:o.call(a,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new ne.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Lo.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Lo.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Lo.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Lo.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Lo.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Lo.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,VK.findDefaultViews)(this.dataverse,t,n),a=[];for(let o of i)await this.fetchArtifact("view",o.id),await this.updateElement("view",o.id,"/columns",r),(await this.pushArtifact("view",o.id)).saved&&a.push(o.id);if(a.length){let o=await this.publishArtifact("view",a[0]);if(o.publish.kind==="failed")throw new ne.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${o.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),a=i.id;if(!a)throw new ne.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,a,async()=>(await this.workspace.writeArtifact(t,a,i),(0,cn.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.requireRegistration(t,"deleteRemoteArtifact").api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:a}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let o of a)await this.withArtifactLock(o.type,o.id,()=>this.adoptBracket(o));return i}async publishArtifactUnlocked(t,r,n){var i;let a=await this.readRaw(t,r),o=this.registrations.get(t);if(!o?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=o.publishScope)===null||i===void 0?void 0:i.call(o,r,a),l=o.rebaselineAfterPublish==="bracket"?await this.captureBracket(o,t,r):void 0,u=s?await this.captureSiblings(s,t,r):[];try{await o.publish(this.dataverse,r,a)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:oa(d)},...s?{publishScope:s}:{}},siblings:[]}}if(o.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(o,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,a);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){var i;try{let a=(i=await this.versions.getMeta(r,n))===null||i===void 0?void 0:i.etag;if(!a||!t.api.readToken)return;let{raw:o,etag:s}=await t.api.get(this.dataverse,n);return s!==a||await t.api.readToken(this.dataverse,n)!==a?void 0:{type:r,id:n,reg:t,heldEtag:a,content:this.bracketContent(t,o)}}catch{return}}async captureSiblings(t,r,n){var i,a;let o=t.envelope==="entity"?(i=t.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;if(!o)return[];let s=[],l;try{l=await this.workspace.listArtifacts()}catch{return[]}for(let u of l){let c=this.registrations.get(u.type);if(u.type===r&&(0,Pd.canonicalArtifactId)(u.id)===(0,Pd.canonicalArtifactId)(n)||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope)continue;try{let f=await this.workspace.readArtifact(u.type,u.id),m=f?c.publishScope(u.id,f):void 0;if(m?.envelope!=="entity"||((a=m.entityLogicalName)===null||a===void 0?void 0:a.toLowerCase())!==o)continue}catch{continue}let p=await this.captureBracket(c,u.type,u.id);p&&s.push(p)}return s}async adoptBracket(t){try{let r=await this.versions.getMeta(t.type,t.id);if(!r||r.etag!==t.heldEtag)return;let{raw:n,etag:i}=await t.reg.api.get(this.dataverse,t.id);if(!i||i===t.heldEtag||!(0,bi.deepEqual)(this.bracketContent(t.reg,n),t.content))return;await this.versions.storeMeta(t.type,t.id,{...r,etag:i,fetchedAt:(0,wr.nowIso)()})}catch{}}bracketContent(t,r){var n,i,a;let o=t.adapter.fromApiResponse(r);return(a=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,o))!==null&&a!==void 0?a:o}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${oa(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let a=t.adapter.fromApiResponse({...n,...i});return(0,bi.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:a,etag:o,memberEtags:s,siblingEtags:l}=await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(a),c=d=>{var p,f,m;return(m=(f=(p=t.adapter).baselineContent)===null||f===void 0?void 0:f.call(p,d))!==null&&m!==void 0?m:d};if(!o||!(0,bi.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:o,fetchedAt:(0,wr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}})}catch{}}async verifyPublished(t,r,n){var i,a,o,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,wi.normalizeGuid)(r,"id")})${(0,wi.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},p=await this.workspace.readArtifact("app",r);if(!p)return{kind:"verified"};let f=[];return((a=p.name)!==null&&a!==void 0?a:"")!==((o=d.name)!==null&&o!==void 0?o:"")&&f.push("name"),((s=p.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&f.push("description"),f.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${f.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:oa(u).message}}}async verifyPublishedContent(t,r,n,i){var a,o,s;try{let l=p=>{var f,m,h;return(h=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,p))!==null&&h!==void 0?h:p},u=l(i),c=(a=await this.versions.getMeta(r,n))===null||a===void 0?void 0:a.snapshot;if(c===void 0||!(0,bi.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(o=t.api).getPublished)===null||s===void 0?void 0:s.call(o,this.dataverse,n));return d?(0,bi.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:oa(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r){var n,i;let a=this.requireRegistration(t,"pushArtifact"),o=await this.readLocal(t,r),s=(i=(n=a.adapter).normalize)===null||i===void 0?void 0:i.call(n,o);s&&s!==o&&(await this.workspace.writeArtifact(t,r,s),o=s);let l=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,l,a),this.assertProjectionMatches(t,r,l);let u=await this.buildMetadataContext(a.adapter,o),c=await a.adapter.toApiPayload(o,l?.snapshot,u);return await this.assertSemanticallyComplete(a,t,r,o,l===null,l?.everActivated),{type:t,id:r,reg:a,json:o,meta:l,payload:c}}async assertSemanticallyComplete(t,r,n,i,a,o){var s;let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,c=u?await this.workspace.readEntityMetadata(u):null,d=((s=c?.attributes)!==null&&s!==void 0?s:[]).map(f=>({logicalName:f.logicalName,displayName:f.displayName,attributeType:f.attributeType,isCustomAttribute:f.isCustomAttribute,...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.options?{options:f.options.map(m=>({value:m.value,label:m.label}))}:{},...f.targets?{targets:f.targets}:{}})),p=l.call(t.adapter,i,d,{isCreate:a,everActivated:o});if(p.length>0)throw new ne.ValidationError(r,n,p)}async pushArtifactUnlocked(t,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,r))}async executePrepared(t){var r,n,i,a,o,s,l,u,c;let{type:d,id:p,reg:f,json:m,meta:h,payload:v}=t;try{let b=h?await f.api.update(this.dataverse,p,v,h.etag,h.memberEtags,h.siblingEtags):await this.createWithMintedId(f,d,p,v),E=p;h||(b.serverIdentity&&f.adapter.applyServerIdentity&&f.adapter.applyServerIdentity(m,b.serverIdentity),b.id&&b.id!==p&&(m.id=b.id,await this.workspace.deleteArtifact(d,p),E=b.id));let C=h&&b.readBack!==void 0?this.adoptReadBack(f,b.readBack):void 0,N=C?.artifact?{artifact:C.artifact,baseline:C.artifact}:f.adapter.committed?f.adapter.committed(m,v,{intentPending:b.intentPending===!0}):{artifact:m,baseline:m};(!h||N.artifact!==m)&&await this.workspace.writeArtifact(d,E,N.artifact);let R=C?.artifact!==void 0&&!(0,bi.deepEqual)(C.artifact,m),O=((r=h?.refreshGeneration)!==null&&r!==void 0?r:0)+(R?1:0),F=[...(n=b.warnings)!==null&&n!==void 0?n:[],...C?.warning?[C.warning]:[],...C?.artifact!==void 0&&!this.adoptedAsSent(f,C.artifact,b.readBack,v)?[`Saved, but the server holds something other than what was pushed (the platform rewrites a form on save \u2014 empty labels, column display names \u2014 or another writer saved in between); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,E,{etag:C&&!C.artifact?null:b.etag,...O>0?{refreshGeneration:O,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:pl.PROJECTION_VERSION,fetchedAt:(0,wr.nowIso)(),snapshot:(0,cn.cloneJson)(N.baseline),...b.memberEtags?{memberEtags:b.memberEtags}:{},...b.siblingEtags?{siblingEtags:b.siblingEtags}:{}}),{type:d,id:E,saved:!0,shipped:!1,publish:(a=b.publish)!==null&&a!==void 0?a:{kind:"notRequested"},...b.publish&&b.publish.kind!=="notRequested"?(()=>{var k;let P=(k=f.publishScope)===null||k===void 0?void 0:k.call(f,E,m);return P?{publishScope:P}:{}})():{},...R?{refreshed:!0}:{},...F.length>0?{warnings:F}:{}}}catch(b){let E=(0,ne.readPartialTokens)(b);if(E&&h){let C={...(o=h.memberEtags)!==null&&o!==void 0?o:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},N={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,p,{...h,...Object.keys(C).length>0?{memberEtags:C}:{},...Object.keys(N).length>0?{siblingEtags:N}:{}})}if(b instanceof ne.SdkError&&b.code===rr.ALREADY_EXISTS_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:b};if(b instanceof ne.SdkError&&b.code===NO.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:b};if(b instanceof ne.SdkError&&b.code===NO.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:b};if(b instanceof ne.SdkError&&b.code===wr.VERSION_CONFLICT_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ne.VersionConflictError(d,p,(c=h?.etag)!==null&&c!==void 0?c:null,null,b.message)};throw b}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ne.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==pl.PROJECTION_VERSION)throw new ne.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${pl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(a){throw!(a instanceof ne.SdkError)||a.code!==wr.VERSION_CONFLICT_CODE?a:new ne.SdkError(rr.ALREADY_EXISTS_CODE,`Cannot create ${r} '${n}': a record already exists at that id, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${r}', '${n}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`)}}async buildMetadataContext(t,r){var n,i;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[],o=new Set(a.map(u=>u.entityLogicalName).filter(u=>!!u)),s=new Set(a.filter(u=>u.needsColumnDetail).map(u=>u.entityLogicalName)),l=new Map;for(let u of o){let c=await this.workspace.readEntityMetadata(u);if(c&&s.has(u)&&(c.columnDetailComplete!==!0||c.attributes.some(d=>typeof d.attributeTypeName!="string"))&&(c=null),!c)try{await this.fetchEntityMetadata(u),c=await this.workspace.readEntityMetadata(u)}catch{}c&&l.set(u,c)}return{resolveField:(u,c)=>{let d=l.get(u),p=d?.attributes.find(f=>f.logicalName===c);return p?{displayName:p.displayName,attributeType:p.attributeType}:void 0},resolveEntity:u=>l.get(u),loadTypeScript:()=>this.compiler.load()}}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map;for(let i=0;i<t.length;i+=1){let a=t[i];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id))}catch(o){r.set(i,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:oa(o)})}}if(r.size>0)return t.map((i,a)=>{var o;return(o=r.get(a))!==null&&o!==void 0?o:{type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ne.SdkError(rr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let n=[];for(let i of t)try{n.push(await this.pushArtifact(i.type,i.id))}catch(a){n.push({type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:oa(a)})}return n}async warmBatchMetadata(t){var r,n,i;let a=new Set;for(let o of t){let s=this.registrations.get(o.type);if(!s)continue;let l;try{l=await this.readLocal(o.type,o.id)}catch{continue}let u=l.entityLogicalName;u&&a.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&a.add(c.entityLogicalName)}for(let o of a)if(!await this.workspace.readEntityMetadata(o))try{await this.fetchEntityMetadata(o)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Td.assignMissingIds)(r)}async resolveComponentType(t){switch(t.componentType){case wt.SolutionComponentType.SavedQuery:return"view";case wt.SolutionComponentType.SavedQueryVisualization:return"chart";case wt.SolutionComponentType.AppModule:return"app";case wt.SolutionComponentType.UxAgentProject:return"genPage";case wt.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case wt.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,wi.normalizeGuid)(t,"formId")})${(0,wi.odataQuery)([["$select","type"]])}`,i=(0,wr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)),a=Number(i.body.type);return a===0||a===10}async isBusinessFlowWorkflow(t){let n=`/workflows(${(0,wi.normalizeGuid)(t,"workflowId")})${(0,wi.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,wr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n));return Number(i.body.businessprocesstype)===0}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new ne.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};rr.MakerSdk=Rd;function WK(e){return new Rd(e)}rr.createMakerSdk=WK;function oa(e){return e instanceof Error?e:new Error(String(e))}function Bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _O(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function TO(e){e.length===0||!e.every(t=>Bn(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function jK(e,t){if(t===void 0||t==="end")return e.length;if(t==="start")return 0;if("index"in t)return Math.max(0,Math.min(t.index,e.length));if("before"in t){let n=e.findIndex(i=>Bn(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Bn(n)&&n.id===t.after);return r<0?e.length:r+1}});var RO=y(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.ARTIFACT_TYPES=void 0;Od.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var xO=y(OO=>{"use strict";Object.defineProperty(OO,"__esModule",{value:!0})});var LO=y(FO=>{"use strict";Object.defineProperty(FO,"__esModule",{value:!0})});var MO=y(kO=>{"use strict";Object.defineProperty(kO,"__esModule",{value:!0})});var UO=y(BO=>{"use strict";Object.defineProperty(BO,"__esModule",{value:!0})});var qO=y($O=>{"use strict";Object.defineProperty($O,"__esModule",{value:!0})});var GO=y(VO=>{"use strict";Object.defineProperty(VO,"__esModule",{value:!0})});var WO=y(zO=>{"use strict";Object.defineProperty(zO,"__esModule",{value:!0})});var HO=y(jO=>{"use strict";Object.defineProperty(jO,"__esModule",{value:!0})});var JO=y(KO=>{"use strict";Object.defineProperty(KO,"__esModule",{value:!0})});var XO=y(QO=>{"use strict";Object.defineProperty(QO,"__esModule",{value:!0})});var ZO=y(YO=>{"use strict";Object.defineProperty(YO,"__esModule",{value:!0})});var t1=y(e1=>{"use strict";Object.defineProperty(e1,"__esModule",{value:!0})});var n1=y(r1=>{"use strict";Object.defineProperty(r1,"__esModule",{value:!0})});var a1=y(i1=>{"use strict";Object.defineProperty(i1,"__esModule",{value:!0})});var s1=y(o1=>{"use strict";Object.defineProperty(o1,"__esModule",{value:!0})});var u1=y(l1=>{"use strict";Object.defineProperty(l1,"__esModule",{value:!0})});var d1=y(c1=>{"use strict";Object.defineProperty(c1,"__esModule",{value:!0})});var f1=y(p1=>{"use strict";Object.defineProperty(p1,"__esModule",{value:!0})});var h1=y(m1=>{"use strict";Object.defineProperty(m1,"__esModule",{value:!0})});var v1=y(g1=>{"use strict";Object.defineProperty(g1,"__esModule",{value:!0})});var y1=y(ue=>{"use strict";var HK=ue&&ue.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Pe=ue&&ue.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&HK(t,e,r)};Object.defineProperty(ue,"__esModule",{value:!0});ue.createMakerSdk=void 0;var KK=PO();Object.defineProperty(ue,"createMakerSdk",{enumerable:!0,get:function(){return KK.createMakerSdk}});Pe(RO(),ue);Pe(xO(),ue);Pe(LO(),ue);Pe(MO(),ue);Pe(UO(),ue);Pe(qO(),ue);Pe(GO(),ue);Pe(WO(),ue);Pe(HO(),ue);Pe(JO(),ue);Pe(XO(),ue);Pe(ZO(),ue);Pe(t1(),ue);Pe(n1(),ue);Pe(mu(),ue);Pe(a1(),ue);Pe(s1(),ue);Pe(u1(),ue);Pe(d1(),ue);Pe(f1(),ue);Pe(h1(),ue);Pe(v1(),ue);Pe(te(),ue)});var o0=y(dn=>{"use strict";var JK=dn&&dn.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),QK=dn&&dn.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),A1=dn&&dn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&JK(t,e,r);return QK(t,e),t};Object.defineProperty(dn,"__esModule",{value:!0});dn.NodeFileSystemStorage=void 0;var Je=A1(require("fs")),At=A1(require("path")),b1=te(),w1=ep();async function E1(e){let t;try{t=await Je.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Je.promises.unlink(e)}catch{await Je.promises.rmdir(e)}return}if(!t.isDirectory()){await Je.promises.unlink(e);return}for(let r of await Je.promises.readdir(e))await E1(At.join(e,r));await Je.promises.rmdir(e)}var a0=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(At.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Je.existsSync(r);){n.unshift(At.basename(r));let i=At.dirname(r);if(i===r)return At.resolve(t);r=i}return At.resolve(Je.realpathSync(r),...n)}assertWithinRoot(t,r){let n=At.resolve(this.root),i=At.resolve(t);if(i!==n&&!i.startsWith(n+At.sep))throw new b1.PathTraversalError(t,this.root);let a=this.realPathThroughNearestAncestor(n),o=r?this.realPathThroughNearestAncestor(i):At.resolve(this.realPathThroughNearestAncestor(At.dirname(i)),At.basename(i));if(o!==a&&!o.startsWith(a+At.sep))throw new b1.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Je.existsSync(r))return null;try{return await(0,w1.retryTransientIoAsync)(()=>Je.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=At.dirname(n);await Je.promises.mkdir(i,{recursive:!0});let a=At.join(i,`.${At.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Je.promises.writeFile(a,r,"utf8"),await(0,w1.retryTransientIoAsync)(()=>Je.promises.rename(a,n))}catch(o){try{Je.existsSync(a)&&await Je.promises.unlink(a)}catch{}throw o}}async deleteFile(t){let r=this.pathFor(t);Je.existsSync(r)&&await Je.promises.unlink(r)}async deleteByPrefix(t){await E1(this.pathFor(t,!1))}async ensureContainer(t){await Je.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Je.existsSync(this.pathFor(t))}};dn.NodeFileSystemStorage=a0});var C1=y(Ht=>{"use strict";var XK=Ht&&Ht.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),YK=Ht&&Ht.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ZK=Ht&&Ht.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&XK(t,e,r);return YK(t,e),t};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.loadNodeTypeScript=Ht.createNodeWorkspaceStorage=Ht.NodeFileSystemStorage=void 0;var eJ=o0(),tJ=o0();Object.defineProperty(Ht,"NodeFileSystemStorage",{enumerable:!0,get:function(){return tJ.NodeFileSystemStorage}});function rJ(e){return new eJ.NodeFileSystemStorage(e)}Ht.createNodeWorkspaceStorage=rJ;async function nJ(){return await Promise.resolve().then(()=>ZK(require("typescript")))}Ht.loadNodeTypeScript=nJ});var Un={};module.exports=Mr(Un);qn(Un,ce(y1()),module.exports);qn(Un,ce(C1()),module.exports);
+`),diagnostics:u}}Ee.compileGenPage=oU});var wf=b(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.isFailureAfterPrimaryWrite=Uo.failedAfterPrimaryWrite=void 0;var Ww=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function aU(e){return typeof e=="object"&&e!==null&&(e[Ww]=!0),e}Uo.failedAfterPrimaryWrite=aU;function sU(e){return typeof e=="object"&&e!==null&&e[Ww]===!0}Uo.isFailureAfterPrimaryWrite=sU});var Nu=b(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.appApi=Yr.deleteAppResolvingOnce=Yr.mainFormSetShapeIssues=Yr.unpublishedAppModulesQuery=void 0;var Vo=Rt(),lU=Rf(),uU=lf(),jw=nr(),cU=Au(),dU=wf(),Ae=be(),oe=ae(),Nf=lt(),pU=ql(),fe=re(),fU=(0,oe.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Af="appmoduleid,name,uniquename,description,aiappdescription";function If(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,oe.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Yr.unpublishedAppModulesQuery=If;function Ef(e,t){return If(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Su(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,oe.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function qo(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function mU(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Tf(e,t){if(typeof e!="string")return!1;try{return(0,oe.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function qi(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function hU(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function rA(e,t){var r,n;let i=u=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,oe.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,oe.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function gU(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,oe.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var Hw="627090ff-40a3-4053-8790-584edc5be201";function _n(e){return e instanceof Error?e.message:String(e)}async function vU(e,t){var r;try{let n=`/roles${(0,oe.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${Hw}`]])}`,i=await(0,Vo.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${Hw}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,Ae.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${_n(n)}); it will not be visible or playable until a role is granted access to it.`}}async function yU(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,Vo.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(p=>String(p[u])).filter(p=>p&&p!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${_n(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,oe.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,oe.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,oe.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,oe.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,oe.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,oe.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var Kw=new WeakMap;async function bU(e,t){let r=Kw.get(e);r||(r=new Map,Kw.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await wU(e,t);return i&&r.set(t,i),i}async function Jw(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function wU(e,t){let r=`/EntityDefinitions(LogicalName='${(0,oe.odataPathLiteral)(t)}')${(0,oe.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function Qw(e,t,r){let n=[],i=qi(t.entities),o=4,a=await Jw(i,o,g=>bU(e,g)),s=i.filter((g,y)=>!a[y]);if(s.length>0)throw new fe.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of qi(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of qi(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of qi(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of qi(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),p=new Map((r??[]).map(g=>[g.table,g])),f=await Jw(i,o,g=>yU(e,g,!p.has(g.toLowerCase()))),m=f.flatMap(g=>g.warnings),h=new Set([...qi(t.components.forms),...qi(t.components.dashboards)].map(cr));return f.forEach((g,y)=>{let w=p.get(i[y].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:m}}function cr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_f="/components/mainFormsByTable",Xw=50;function nA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function iA(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:_f,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${_f}/${nA(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let p=`${l}/${d}`;typeof c!="string"||!Df.test(cr(c))?r.push({pointer:p,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(cr(c))?r.push({pointer:p,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(cr(c))})}return r}Yr.mainFormSetShapeIssues=iA;async function Yw(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=iA(n,t.entities);if(i.length>0)throw new fe.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,Vo.collectPages)(e,`/systemforms${(0,oe.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,oe.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),p=new Set,f=new Set;for(let h of d)typeof h.formid=="string"&&(p.add(cr(h.formid)),Number(h.formactivationstate)===1&&f.add(cr(h.formid)));let m=u.map(cr);m.forEach((h,g)=>{let y=`${_f}/${nA(l)}/${g}`;p.has(h)?f.has(h)||o.push({pointer:y,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:y,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:m,catalog:p})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=cr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new fe.ValidationError("app",r,o);return a}async function oA(e,t,r){var n,i;let o=g=>({kind:"inconclusive",reason:g}),a=await e.get(If("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(a.status<200||a.status>=300)return o(`reading the app returned HTTP ${a.status}`);let s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s)||s.length===0)return o("reading the app returned no row");let l=s.length===1?s:s.filter(g=>Number(g?.componentstate)===1),u=l.length===1?(i=l[0])===null||i===void 0?void 0:i.appmoduleidunique:"";if(typeof u!="string"||!Df.test(cr(u)))return o(`no single current layer among ${s.length} app row(s)`);let c;try{let g=await(0,Vo.collectPages)(e,`/appmodulecomponents${(0,oe.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${cr(u)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(g.some(y=>typeof y.objectid!="string"))return o("a form component carries no object id");c=g.map(y=>cr(String(y.objectid)))}catch(g){return o(`reading its form components failed (${_n(g)})`)}let d=new Map,p=[];for(let g of new Set(c)){let y=r.find(w=>w.catalog.has(g));y?d.set(g,y.table):p.push(g)}if(p.some(g=>!Df.test(g)))return o("a form component carries an object id that is not a GUID");let f=new Set(r.map(g=>g.table)),m=new Set;for(let g=0;g<p.length;g+=Xw){let y=p.slice(g,g+Xw);try{let w=await(0,Vo.collectPages)(e,`/systemforms${(0,oe.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",y.map(C=>`formid eq ${C}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let C of w){if(typeof C.formid!="string"||typeof C.type!="number"||C.type===2&&(typeof C.objecttypecode!="string"||C.objecttypecode===""))continue;let S=cr(C.formid);m.add(S);let T=C.type===2?String(C.objecttypecode).toLowerCase():"";f.has(T)&&d.set(S,T)}}catch(w){return o(`classifying its form components failed (${_n(w)})`)}}let h=p.filter(g=>!m.has(g));return h.length>0?o(`form component(s) ${h.join(", ")} could not be classified`):{kind:"read",tables:r.map(g=>{let y=[...d].filter(([,w])=>w===g.table).map(([w])=>w);return{table:g.table,members:y,extras:y.filter(w=>!g.allowed.includes(w)),missing:g.allowed.filter(w=>!y.includes(w))}})}}async function AU(e,t,r){let n=await oA(e,t,r);if(n.kind==="inconclusive")throw new fe.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${n.reason}.`);let i=n.tables.filter(o=>o.extras.length>0||o.missing.length>0);if(i.length>0)throw new fe.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${i.map(o=>`'${o.table}': unexpected [${o.extras.join(", ")}], missing [${o.missing.join(", ")}]`).join("; ")}.`)}async function EU(e,t,r){let n;try{n=await oA(e,t,r)}catch(o){n={kind:"inconclusive",reason:_n(o)}}if(n.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${n.reason}).`];let i=[];for(let o of n.tables)o.extras.length>0&&i.push(`Main-form components outside the allow-list remain for table '${o.table}': [${o.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),o.missing.length>0&&i.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${o.table}': [${o.missing.join(", ")}]; re-push to retry.`);return i}async function Zw(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,Ae.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function CU(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,oe.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function eA(e,t,r){var n;if(r.length===0)return;let i=CU(t),o=await e.get(i);if(o.status<200||o.status>=300)throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the unpublished-aware read returned HTTP ${o.status}. Re-push to retry.`);let a=qo(o),s=a?.appmoduleidunique;if(typeof s!="string"||!s)throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the app did not return an 'appmoduleidunique' to file components under. Re-push to retry.`);let l=`/appmodulecomponents${(0,oe.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,oe.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${u.status}. Re-push to retry.`);let c=(n=u.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(c))throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let d=new Set(c.map(f=>f.objectid).filter(f=>typeof f=="string").map(f=>f.toLowerCase())),p=r.filter(f=>!d.has(f.metadataId.toLowerCase()));if(p.length>0)throw new fe.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${p.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${p.map(f=>`'${f.logicalName}' (expected objectid ${f.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function SU(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await DU(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${_n(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${_n(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${_n(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await e.delete(n);return s(l.status===404?{kind:"deleted"}:sA(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await lA(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function NU(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function DU(e,t,r){var n,i,o;let a=Su(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function aA(e,t){var r;let n=(0,oe.normalizeGuid)(t,"id"),i=h=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${h} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)},o=`/appmodules(${n})${fU}`,a;try{a=await e.get(o)}catch(h){return i(`reading the app failed (${h.message}).`)}if(a.status<200||a.status>=300)return i(a.status===404?"reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap.":`reading the app returned HTTP ${a.status}.`);let s=(r=a.body)===null||r===void 0?void 0:r.uniquename;if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let l=await rA(e,s);if(!l)return{uniquename:s,appEtag:(0,Ae.readEtag)(a)};let u=(0,oe.normalizeGuid)(l,"sitemapId"),c=await Pf(e,u),d=Su(u,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(d)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${u}' returned HTTP ${p.status}.`);let f=qo(p);if(!f)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(f.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Tf(f.sitemapid,u))return i(`sitemap '${u}' was read back as a row carrying sitemapid '${String(f.sitemapid)}'.`);let m=f.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,Ae.readEtag)(a),sitemapEtag:c}}async function _U(e,t,r){let n=(0,oe.normalizeGuid)(t,"id"),i=await aA(e,n);await r?.(i.sitemapXml),await cA(e,n,i)}Yr.deleteAppResolvingOnce=_U;async function IU(e,t){let r=await lA(e,t);if(r.kind!=="deleted")throw r.error}function sA(e,t){try{return(0,Ae.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return uA(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}async function lA(e,t){let r=`batch_${(0,Nf.newId)()}`,n=`changeset_${(0,Nf.newId)()}`,i=t.map((p,f)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${f+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r
+`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r
+`),a=e.apiUrl("/$batch"),s;try{s=await e.postBatch(o,r)}catch(p){return{kind:"unknown",error:p}}let l=sA(s,a);if(l.kind!=="deleted")return l;let u=`app '${t[0].path}'`;if(typeof s.body!="string"||s.body.length===0)return{kind:"unknown",error:new fe.ConnectionError(a,s.status,`atomic delete of ${u} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let c=(0,pU.parseChangeSetStatuses)(s.body,i.map((p,f)=>String(f+1)));if(c===void 0)return{kind:"unknown",error:new fe.ConnectionError(a,s.status,`atomic delete of ${u} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let d=c.find(p=>p<200||p>=300);return d!==void 0?{kind:"refused",error:new fe.ConnectionError(a,d,`atomic delete of ${u} was rolled back: the change set reported HTTP ${d}`)}:c.length!==i.length?{kind:"unknown",error:new fe.ConnectionError(a,s.status,`atomic delete of ${u} cannot be confirmed: the $batch response reported ${c.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function Pf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,Ae.readEtag)(r)}catch{return null}}async function TU(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,Ae.ensureSuccess)(n,e.apiUrl(r)),(0,Ae.readEtag)(n)}async function Cf(e,t,r,n){if(!n)return null;let i=await Pf(e,t);if(!i)return null;try{let o=await e.get(Su(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=qo(o);return!a||!Tf(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function uA(e){return e>=400&&e<500&&e!==408&&e!==429}function Sf(e,t,r){if(!e)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function cA(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await PU(e,n,Sf(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new fe.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await IU(e,[{path:n,etag:Sf(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:Sf(r.sitemapEtag,t,"sitemap")}])}async function PU(e,t,r){(0,Ae.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function tA(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,lU.collectGenPageIds)(t))]}catch(i){throw new fe.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${_n(i)}).`)}if(r.length===0)return;let n=await(0,uU.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new fe.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function RU(e){var t,r;if(e.status!==400)return!1;let n=e.body;return String((r=(t=n?.error)===null||t===void 0?void 0:t.message)!==null&&r!==void 0?r:"").includes("retrieval of version numbers failed")}Yr.appApi={async get(e,t){var r;let n=(0,oe.normalizeGuid)(t,"id"),i=await TU(e,n),o=Ef(Af,n),a=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=qo(a))!==null&&r!==void 0?r:{};if(!s.appmoduleid)throw new fe.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let l=await rA(e,s.uniquename),u=l?(0,oe.normalizeGuid)(l,"sitemapId"):void 0,c=null;if(u){c=await Pf(e,u);let p=Su(u,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),f=(0,Ae.ensureSuccess)(await e.get(p),e.apiUrl(p)),m=qo(f),h=g=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': its sitemap '${u}' was located by unique name, but ${g}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!m)return h("the by-id read returned no row");if(m.sitemapnameunique!==s.uniquename)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${u}' now carries sitemapnameunique '${String(m.sitemapnameunique)}', not '${String(s.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Tf(m.sitemapid,u))return h(`the by-id read returned a row carrying sitemapid '${String(m.sitemapid)}'`);if(typeof m.sitemapxml!="string")return h("the by-id read returned no sitemapxml");s.$sitemap=m}let d=i??mU(s);return{raw:s,etag:c,...s.appmoduleid?{siblingEtags:{[(0,oe.normalizeGuid)(s.appmoduleid,"appmoduleid")]:d}}:{}}},async list(e,t){let r=Ef(Af);return(await(0,Vo.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await tA(e,n.sitemapxml);let i=await Yw(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await gU(e),a=n.iconWebResourceId||o?.id;if(!a)throw new fe.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||hU(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,Ae.ensureSuccess)(await(0,Ae.resendDeadlockVictim)(()=>e.post(c,(0,Ae.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),p=(0,Ae.resolveCreatedId)(d,"appmoduleid","app module",r),f=null,m=null,h=[];s&&h.push(s);let g={kind:"notRequested"},y=n.sitemapId?(0,oe.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Nf.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let T="/sitemaps",O=(0,Ae.echoWrite)("sitemapid"),k=await e.post(`${T}${O.query}`,{sitemapid:y,sitemapnameunique:l,...C},O.options);w=uA(k.status);let F=(0,Ae.ensureSuccess)(k,e.apiUrl(T));m=(0,Ae.readEtag)(F),f=m??await Cf(e,y,C,l);let P=await Qw(e,n,i);h.push(...P.warnings);let q=P.components;q.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:y}),await Zw(e,p,q),await eA(e,p,P.tables),i&&await AU(e,p,i);let V=await vU(e,p);V&&h.push(V),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,cU.applyAppSettings)(e,p,n.appSettings)),n.published!==!1&&(await(0,jw.publishAppModule)(e,p),g={kind:"submitted"})}catch(T){let O=await SU(e,p,{sitemapId:y,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:m});throw(0,dU.failedAfterPrimaryWrite)(NU(T,O,{appId:p,sitemapId:y,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let T=await e.get(`/appmodules(${p})?$select=appmoduleid`);T.status>=200&&T.status<300&&(S=(0,Ae.readEtag)(T))}catch{}return{id:p,etag:f,serverIdentity:{sitemapId:y},siblingEtags:{[p]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,p,f,m;let h=r,g=(0,oe.normalizeGuid)(t,"id");if(await tA(e,h.sitemapxml),!h.sitemapId)throw new fe.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let y=(0,oe.normalizeGuid)(h.sitemapId,"sitemapId");if(!n)throw new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': no concurrency token is held for its sitemap row, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the app and re-apply the change.`);let w=await Yw(e,h,g),C=await Qw(e,h,w),S=`/appmodules(${g})`,T=(a=o?.[g])!==null&&a!==void 0?a:null,O=!0,k=!1,F;try{let ot=Ef(Af,g),Kn=await e.get(ot);if(Kn.status>=200&&Kn.status<300){let Br=(s=qo(Kn))!==null&&s!==void 0?s:{};k=!0,F=typeof Br.uniquename=="string"&&Br.uniquename?Br.uniquename:void 0,O=String((l=Br.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Br.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((p=Br.aiappdescription)!==null&&p!==void 0?p:"")!==String(h.appModuleAiDescription)}}catch{}let P=T;if(O){let ot=k?T:null,Kn=ot?(0,Ae.echoWrite)("appmoduleid",{"If-Match":ot}):{query:"",options:void 0},Br=await e.patch(`${S}${Kn.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Kn.options);if(RU(Br))throw new fe.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,Ae.ensureSuccess)(Br,e.apiUrl(S)),P=(0,Ae.readEtag)(Br)}let q={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},V=F||h.appModuleUniqueName||void 0,Ve=(0,Ae.echoWrite)("sitemapid",{"If-Match":n}),Pt=`/sitemaps(${y})`,Je;try{Je=(0,Ae.ensureSuccess)(await e.patch(`${Pt}${Ve.query}`,{...q},Ve.options),e.apiUrl(Pt))}catch(ot){throw(0,fe.withPartialTokens)(ot,{siblingEtags:{[g]:P}})}let Ge=[...C.warnings];try{await Zw(e,g,C.components),await eA(e,g,C.tables)}catch(ot){Ge.push(`App '${g}': one or more components were not pinned (${ot.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Ge.push(...await EU(e,g,w));let Z={kind:"notRequested"},ye=P,hn=(f=(0,Ae.readEtag)(Je))!==null&&f!==void 0?f:await Cf(e,y,q,V);if(h.published===!0){try{await(0,jw.publishAppModule)(e,g),Z={kind:"submitted"}}catch(ot){Z={kind:"failed",error:ot},Ge.push(`App '${g}': saved, but publishing failed (${ot.message}). The app remains unpublished; re-push to retry.`)}if(Z.kind==="submitted"){ye=null;try{let ot=await e.get(`/appmodules(${g})?$select=appmoduleid`);ot.status>=200&&ot.status<300&&(ye=(0,Ae.readEtag)(ot)),hn=(m=await Cf(e,y,q,V))!==null&&m!==void 0?m:hn}catch{}}}return{id:g,etag:hn,siblingEtags:{[g]:ye},publish:Z,...Ge.length>0?{warnings:Ge}:{}}},async delete(e,t){let r=(0,oe.normalizeGuid)(t,"id");await cA(e,r,await aA(e,r))}}});var Rf=b(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.deleteAppCascade=Go.collectGenPageIds=void 0;var OU=Nu(),xU=re(),Of=ae(),LU=iu();function dA(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new LU.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new xU.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,Of.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}Go.collectGenPageIds=dA;async function kU(e,t,r){let n=(0,Of.normalizeGuid)(t,"appModuleId");(0,Of.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,OU.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...dA(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}Go.deleteAppCascade=kU});var pA={};gn(pA,{Guid:()=>L});var L,ze=R(()=>{"use strict";L=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var M,ht=R(()=>{"use strict";Be();M=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!I.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return I.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var fA={};gn(fA,{ScriptUtilities:()=>I});var I,Be=R(()=>{"use strict";ze();ht();I=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return M.IsNullOrEmpty(t.ToString())?!0:L.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:M.IsTrue(n)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let r=new Set;return e.getAllUniqueTagNamesHelper(t,r),r}static getAllUniqueTagNamesHelper(t,r){if(t.nodeType===Node.ELEMENT_NODE&&(r.add(t.tagName),t.hasChildNodes()))for(let n=0;n<t.children.length;n++)this.getAllUniqueTagNamesHelper(t.children.item(n),r)}}});var Du,_u,Vi,Iu,xf,Tu,Lf=R(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Du||(Du={}));_u=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Vi=class extends _u{key;oldValue;newValue;constructor(t,r,n,i){super(Du.FormElementNodeChange,t),this.key=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},Iu=class extends _u{property;oldValue;newValue;constructor(t,r,n,i){super(Du.FormElementAttributeChange,t),this.property=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},xf=class{changeSet;reversedChangeSet;constructor(t){this.changeSet=t,this.changeSet&&(this.reversedChangeSet=this.changeSet.slice().reverse())}length(){return this.changeSet?this.changeSet.length:0}apply(){this.changeSet&&this.changeSet.length>0&&this.changeSet.forEach(t=>{t.apply()})}revert(){this.reversedChangeSet&&this.reversedChangeSet.length>0&&this.reversedChangeSet.forEach(t=>{t.revert()})}},Tu=class{isTracking;_trackedChanges;_trackedChangeSets;constructor(t=!1){this.isTracking=t,this._trackedChanges=[],this._trackedChangeSets=[]}addChange(t){this.isTracking&&this._trackedChanges.push(t)}collectChanges(){let t=new xf(this._trackedChanges.slice());return this._trackedChanges=[],t}pushChangeSet(t){this._trackedChangeSets.push(t)}popChangeSet(){if(this._trackedChangeSets?.length>0)return this._trackedChangeSets.pop()}getChangeSets(){return this._trackedChangeSets}}});var mA={};gn(mA,{ChartGridMode:()=>dr,ColumnLayoutWidths:()=>UU,ComponentCategory:()=>Ru,ComponentType:()=>kf,ControlLayoutTypes:()=>Vf,DisplayConditionsInfo:()=>BU,ElementNames:()=>A,ElementProperties:()=>v,ElementType:()=>Mf,EntityAttributeProperty:()=>Bf,EventType:()=>ws,FormActivationState:()=>qf,FormCanvasServiceScope:()=>YU,FormDesignerSideBarTab:()=>Ff,FormPresentation:()=>$f,FormState:()=>Pu,FormType:()=>We,HeaderDensityType:()=>ci,LookUpTable:()=>Zr,MORE_TAB_PREFIX:()=>VU,NavBarChildElementType:()=>Uf,PREVIEW_ID_HEADER_FLYOUT:()=>jU,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>KU,PREVIEW_ID_NAVIGATION_AREA:()=>zU,PREVIEW_ID_QUICKCREATE_ROOT:()=>QU,PREVIEW_ID_TAB:()=>JU,PREVIEW_ID_TAB_LIST:()=>HU,PREVIEW_ID_TAB_PANEL:()=>WU,PropertyModelKeys:()=>Wf,PropertyModelSectionKeys:()=>qU,RELATED_TAB_ID:()=>jf,RELATED_TAB_PREFIX:()=>GU,SectionDefaultProperties:()=>$U,SectionLayoutTypes:()=>Te,TabContentType:()=>Gf,TabDefaultProperties:()=>di,TabLayoutTypes:()=>Ie,TelemetryPropertyNames:()=>XU,UnboundControlPropertyKeys:()=>zf,compositeAddressFields:()=>MU,compositeFieldNames:()=>Qt,compositeFields:()=>FU});var We,kf,Ff,A,v,Mf,Qt,FU,MU,Bf,Zr,Pu,ci,$f,BU,Uf,qf,Ie,$U,di,Te,Vf,Gf,UU,zf,Wf,qU,ws,dr,jf,VU,GU,zU,WU,jU,HU,KU,JU,QU,XU,Ru,YU,te=R(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(We||(We={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(kf||(kf={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Ff||(Ff={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(A||(A={}));v={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(Mf||(Mf={}));Qt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},FU=[Qt.fullname,Qt.yomifullname,Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto],MU=[Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Bf||(Bf={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Zr||(Zr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Pu||(Pu={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ci||(ci={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})($f||($f={}));BU={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Uf||(Uf={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(qf||(qf={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(Ie||(Ie={}));$U={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},di={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(Te||(Te={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(Vf||(Vf={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Gf||(Gf={}));UU={ONE_COLUMN:"100",TWO_COLUMN:"50",THREE_COLUMN:"33.33",FOUR_COLUMN:"25"};(function(e){e.minValue="MinValue",e.maxValue="MaxValue",e.precision="Precision",e.maxLength="MaxLength",e.entityLogicalName="EntityLogicalName",e.defaultViewId="DefaultViewId",e.optionSetDefaultValue="DefaultValue",e.optionSetId="OptionSetId"})(zf||(zf={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(Wf||(Wf={}));qU={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(ws||(ws={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(dr||(dr={}));jf="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",VU="more_tab_",GU="related_tab_",zU="preview_id_navigation_area",WU="tab-section",jU="headerFieldsFlyout",HU="tablist",KU="header_overflowButton",JU="tab",QU="quickCreateRoot",XU={defaultVisibility:"Default visibility"};(function(e){e.input="input",e.layout="layout",e.grid="grid",e.relatedData="relatedData",e.display="display",e.powerbi="powerbi",e.artificialIntelligence="artificialIntelligence",e.media="media",e.collaboration="collaboration",e.more="more",e.test="test",e.popular="popular"})(Ru||(Ru={}));YU="CellCanvasServiceScope"});var hA={};gn(hA,{Attribute:()=>Ou,FormElementNode:()=>H});var Ou,H,et=R(()=>{"use strict";Be();ht();Lf();te();ze();Ou=class{key;value;constructor(t,r){this.key=t,this.value=r}},H=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${L.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(A.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Ou(t,r))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let r=this.properties.findIndex(n=>n.key===t);r>-1&&this.properties.splice(r,1)})}trackPropertyCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.properties.slice();t(),r.addChange(new Vi(this,"properties",n,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.childrenNodes.slice();t(),r.addChange(new Vi(this,"childrenNodes",n,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.parentNode;if(t(),n===this.parentNode)return;r.addChange(new Vi(this,"parentNode",n,this.parentNode))}else t()}trackAttributeValueChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=t.value;if(i===r)return;t.value=r,n.addChange(new Iu(this,t,i,r))}else t.value=r}trackObjectPropertyChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=this[t];if(i===r)return;this[t]=r,n.addChange(new Vi(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){I.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(I.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:M.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=I.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case A.formCell:let t=this.getAncestor(A.formSection);return t||(t=this.getAncestor(A.formHeader),t)||(t=this.getAncestor(A.formFooter),t)?t:null;case A.formSection:return this.getAncestor(A.formTab);case A.formTab:return this.getAncestor(A.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(A.form);return t?t.changeTracker():null}}});var gA={};gn(gA,{ControlClassId:()=>_,ControlNamePrefixes:()=>xu,getControlDisplayNames:()=>ZU});function ZU(e){return{[_.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[_.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[_.ACIControl]:e("controls.controlNames.aci"),[_.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[_.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[_.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[_.ArticleContentControl]:e("controls.controlNames.articleContent"),[_.BooleanControl]:e("controls.controlNames.twoOption"),[_.ButtonControl]:e("controls.controlNames.button"),[_.CheckboxControl]:e("controls.controlNames.checkbox"),[_.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[_.ConnectionControl]:e("controls.controlNames.connection"),[_.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[_.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[_.DashboardControl]:e("controls.controlNames.dashboard"),[_.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[_.EditFilterControl]:e("controls.controlNames.editFilter"),[_.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[_.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[_.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[_.KBViewerControl]:e("controls.controlNames.kbViewer"),[_.LabelControl]:e("controls.controlNames.label"),[_.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[_.MapLinkControl]:e("controls.controlNames.mapLink"),[_.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[_.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[_.PowerBIControl]:e("controls.controlNames.powerBI"),[_.ProcessControl]:e("controls.controlNames.process"),[_.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[_.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[_.ReportControl]:e("controls.controlNames.report"),[_.StreamsControl]:e("controls.controlNames.streams"),[_.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[_.CurrencyControl]:e("controls.controlNames.currency"),[_.DateTimeControl]:e("controls.controlNames.dateAndTime"),[_.DecimalControl]:e("controls.controlNames.decimal"),[_.DurationControl]:e("controls.controlNames.duration"),[_.EmailAddressControl]:e("controls.controlNames.email"),[_.FileControl]:e("controls.controlNames.file"),[_.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[_.IframeControl]:e("controls.controlNames.iframe"),[_.ImageControl]:e("controls.controlNames.image"),[_.LookupControl]:e("controls.controlNames.lookup"),[_.MapsControl]:e("controls.controlNames.maps"),[_.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[_.ChoiceControl]:e("controls.controlNames.choice"),[_.QuickViewControl]:e("controls.controlNames.quickView"),[_.QuickFormControl]:e("controls.controlNames.quickForm"),[_.CustomControl]:e("controls.controlNames.customControl"),[_.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[_.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[_.SubgridControl]:e("controls.controlNames.subgrid"),[_.TextAreaControl]:e("controls.controlNames.textArea"),[_.TextboxControl]:e("controls.controlNames.textBox"),[_.TickerControl]:e("controls.controlNames.ticker"),[_.UrlControl]:e("controls.controlNames.url"),[_.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[_.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[_.IntegerControl]:e("controls.controlNames.integer"),[_.TimerControl]:e("controls.controlNames.timer"),[_.TimelineControl]:e("controls.controlNames.timeline"),[_.EmailBodyControl]:e("controls.controlNames.emailBody"),[_.PartyListControl]:e("controls.controlNames.partyList"),[_.TimezoneControl]:e("controls.controlNames.timezone"),[_.LanguageControl]:e("controls.controlNames.language"),[_.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[_.ChoicesControl]:e("controls.controlNames.choices"),[_.RegardingControl]:e("controls.controlNames.regarding"),[_.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[_.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[_.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[_.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[_.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[_.KBEditorControl]:e("controls.controlNames.KBEditor"),[_.LinkControl]:e("controls.controlNames.link")}}var _,xu,Gi=R(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(_||(_={}));xu={[_.WebResourceHTMLControl]:"WebResource",[_.WebResourceImageControl]:"WebResource",[_.IframeControl]:"IFRAME",[_.SearchWidgetControl]:"Search widget",[_.SubgridControl]:"Subgrid",[_.TimelineControl]:"Timeline",[_.QuickViewControl]:"QuickviewControl"}});var zi=b((KX,yA)=>{var As=new Proxy(function(){return As},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:As},apply:function(){return As},construct:function(){return{}}}),vA=function(){return As};Object.setPrototypeOf(vA,As);yA.exports=vA});var Et,In,bA,wA,zo=R(()=>{"use strict";Et="cds-designer-models",In="FormCustomControl",bA="FormCell",wA="Form"});var Wo,Ct,Es=R(()=>{"use strict";Wo=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,r){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(r),!0)}upsert(t,r){this.update(t,r)||this.add(t,r)}sortedUpsert(t,r){if(!this.update(t,r)){let n=0;for(;n<this.keys.length&&this.keys[n]<t;)n++;this.keys.splice(n,0,t),this.values.splice(n,0,r)}}clear(){this.keys=[],this.values=[]}containsKey(t){return this.keys.indexOf(t)!==-1}containsValue(t){return this.values.indexOf(t)!==-1}count(){return this.keys.length}getValue(t){let r=this.keys.indexOf(t);return r!==-1?this.values[r]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let r=this.keys.indexOf(t);return r!==-1?(this.keys.splice(r,1),this.values.splice(r,1),!0):!1}update(t,r){let n=this.keys.indexOf(t);return n!==-1?(this.values[n]=r,!0):!1}},Ct=class{data={};add(t,r){return this.containsKey(t)?!1:(this.data[t]=r,!0)}upsert(t,r){this.data[t]=r}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let r in this.data)if(this.data[r]===t)return!0;return!1}count(){return Object.keys(this.data).length}getValue(t){return this.containsKey(t)?this.data[t]:!1}getKeys(){return Object.keys(this.data)}getValues(){let t=[];for(let r in this.data)t.push(this.data[r]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,r){return this.containsKey(t)?(this.data[t]=r,!0):!1}getInternalObject(){return this.data}}});var Wi,Hf=R(()=>{"use strict";Es();te();Wi=class e{static lockedFieldCount=new Ct;static dependencyFieldCount=new Ct;static getNecessaryLookUpTable(t){switch(t){case Zr.DependencyFieldTable:return e.dependencyFieldCount;case Zr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Zr.DependencyFieldTable:e.dependencyFieldCount=new Ct;case Zr.LockedFieldTable:e.lockedFieldCount=new Ct}}}});var Lu,AA=R(()=>{"use strict";ze();Be();te();et();Lu=class extends H{constructor(t){super(A.controlDescription,t)}get forControl(){let t=this.getProperty(v.ForControl);return I.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set forControl(t){this.setProperty(v.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(A.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!I.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!I.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)I.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});var CA,SA,St,x,EA,pi,ji,jo,Kf,Jf,Ho=R(()=>{"use strict";CA={Name:"Name",Value:"Value",Type:"Type",TypeGroup:"TypeGroup",Usage:"Usage",Static:"Static",Primary:"Primary",Columns:"Columns",EnableViewPicker:"EnableViewPicker",EntityName:"EntityName",FilteredViewIds:"FilteredViewIds",ReferencingName:"ReferencingName",RelationshipName:"RelationshipName",RelationshipType:"RelationshipType",TargetEntityType:"TargetEntityType",ViewId:"ViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DefaultViewId:"DefaultViewId",BindAttribute:"BindAttribute",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",QuickForms:"QuickForms",EntityNameKey:"EntityNameKey",CardFormType:"Form.Card",CardFormId:"CardFormId",Hidden:"Hidden",Required:"Required",DefaultValue:"DefaultValue"},SA={GroupDefinition:"GroupDefinition"},St={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(x||(x={}));(function(e){e.BooleanType="CC_FlipLabel_Name",e.DateTimeType="CC_TextBox_Name",e.DecimalType="CC_TextBox_Name",e.DoubleType="CC_TextBox_Name",e.IntegerType="CC_TextBox_Name",e.LookupType="CC_TextBox_Name",e.MemoType="CC_TextArea_Name",e.MoneyType="CC_TextBox_Name",e.OptionSetType="CC_OptionSet_Name",e.StringType="CC_TextBox_Name",e.GridType="CC_ReadOnlyGrid_Name",e.UnboundCustomControlType="CC_UnboundCustomControl_Name"})(EA||(EA={}));(function(e){e.ArcKnobControl="MscrmControls.Knob.ArcKnobControl",e.CardFeedNameControl="MscrmControls.CardFeedContainer.CardFeedContainer",e.CheckboxControl="MscrmControls.FieldControls.CheckboxControl",e.DateTimeControl="MscrmControls.FieldControls.DateTimeControl",e.DurationControl="MscrmControls.FieldControls.DurationControl",e.EditableGridControl="MscrmControls.Grid.GridControl",e.EmailEngagementActionsControl="MscrmControls.EmailEngagement.EmailEngagementActionsControl",e.FormComponent="MscrmControls.ModelForm.ModelFormControl",e.LanguageCodeControl="MscrmControls.FieldControls.LanguagePickerControl",e.LinearSliderControl="MscrmControls.Slider.LinearSliderControl",e.MultiSelectOptionSetControl="MscrmControls.MultiSelectPicklist.UpdMSPicklistControl",e.OptionSetControl="MscrmControls.OptionSet.OptionSetControl",e.PowerBIPCFControl="MscrmControls.PowerBIPCFControl",e.PredictiveScoringWidget="MscrmControls.Sales.PredictiveScoringWidget.PredictiveScoringWidget",e.ReadonlyGrid="MscrmControls.Grid.ReadOnlyGrid",e.SimilarCasesGrid="MscrmControls.Containers.SimilarCasesGridControl",e.StarRatingControl="MscrmControls.Rating.StarRatingControl",e.TimeZoneControl="MscrmControls.FieldControls.TimeZonePickListControl",e.ModelFormControl="MscrmControls.ModelForm.ModelFormControl",e.AutoCompleteControl="MscrmControls.AutoComplete.AutoCompleteControl",e.CanvasAppControl="MscrmControls.Canvas.CanvasControl",e.PowerAppsOneGrid="Microsoft.PowerApps.PowerAppsOneGrid"})(pi||(pi={}));(function(e){e[e.Read=0]="Read",e[e.Edit=1]="Edit",e[e.Both=2]="Both",e[e.Container=3]="Container",e[e.Unknown=4]="Unknown"})(ji||(ji={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(jo||(jo={}));Kf=[x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.LookupSimple],Jf=[x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.FP,x.Decimal]});function Tn(){return en||(en=window._makerConfig,en&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(en={...en,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),en?.region==="prod"&&(en={endpoints:{eu:{ch:{graphql:"https://graph-make.ch-cm001.gateway.prod.cm.powerapps.com/"},de:{graphql:"https://graph-make.de-cm001.gateway.prod.cm.powerapps.com/"},fr:{graphql:"https://graph-make.fr-cm001.gateway.prod.cm.powerapps.com/"},no:{graphql:"https://graph-make.no-cm001.gateway.prod.cm.powerapps.com/"},default:{graphql:"https://graph-make.eu-cm001.gateway.prod.cm.powerapps.com/"}}},...en}),en||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var en,ku=R(()=>{"use strict";});function NA(e,t,r){if(!e)return Fu.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Fu.add("")),!1;if(e){if(e=e.toLowerCase(),Fu.has(e))return!1;if(!(e in t))return window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoNonExistent",eventInfo:{missinggeo:e,parent:r}}),Fu.add(e),!1}return!0}function eq(e){return NA(e,Qf,"Location dictionary")?Qf[e.toLowerCase()]:"us"}function tq(){let e=Tn().location.toLowerCase();return NA(e,Qf,"Current location dictionary")?e:"us"}var Fu,Qf,uY,DA=R(()=>{"use strict";ku();Fu=new Set,Qf={cae:"ae",nae:"ae",eas:"as",seas:"as",eau:"au",seau:"au",sbr:"br",cca:"ca",eca:"ca",nch:"ch",wch:"ch",nde:"de",wcde:"de",neu:"eu",weu:"eu",cfr:"fr",sfr:"fr",cin:"in",sin:"in",ejp:"jp",wjp:"jp",suk:"uk",wuk:"uk",eus:"us",wus:"us",cus:"us",ude:"us",udc:"us",ugtx:"us",ugva:"us",eus2:"us",wus2:"us",nza:"za",wza:"za",cne2:"cn",cnn2:"cn",skr:"kr",ckr:"kr",eno:"no",wno:"no",wrx:"us",erx:"us",wex:"us",eex:"us",unitedstates:"us",europe:"eu",asia:"as",australia:"au",japan:"jp",canada:"ca",india:"in",italy:"it",unitedstatesfirstrelease:"us",unitedkingdom:"uk",southamerica:"br",france:"fr",unitedarabemirates:"ae",germany:"de",sweden:"se",switzerland:"ch",korea:"kr",norway:"no",usgov:"us",usgovhigh:"us",usdod:"us",china:"cn",usnat:"us",ussec:"us",southafrica:"za",singapore:"sg",newzealand:"nz",poland:"pl",qatar:"qa",as:"as",au:"au",ca:"ca",in:"in",jp:"jp",kr:"kr",nz:"nz",ae:"ae",qa:"qa",us:"us",uk:"uk",eu:"eu",de:"de",ch:"ch",no:"no",fr:"fr",se:"se",it:"it",pl:"pl",be:"eu",bel:"eu",gr:"eu",grc:"eu",lt:"eu",ltu:"eu",pt:"eu",prt:"eu",bg:"eu",bgr:"eu",es:"eu",esp:"eu",lu:"eu",lux:"eu",ro:"eu",rou:"eu",cz:"eu",cze:"eu",hu:"eu",hun:"eu",si:"eu",svn:"eu",dk:"eu",dnk:"eu",hr:"eu",hrv:"eu",mt:"eu",mlt:"eu",sk:"eu",svk:"eu",nit:"it",nl:"eu",nld:"eu",fi:"eu",fin:"eu",ee:"eu",est:"eu",cy:"eu",cyp:"eu",at:"eu",aut:"eu",swe:"se",cse:"se",ie:"eu",irl:"eu",lv:"eu",lva:"eu",cpl:"pl",nnz:"nz",cqa:"qa",sg:"sg",br:"br",za:"za",sa:"za"};uY=eq(tq())});var z,dY,_A=R(()=>{"use strict";z={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},dY={[z.USWest]:{geoName:"us",regionShortName:"wus"},[z.USCentral]:{geoName:"us",regionShortName:"cus"},[z.USEast]:{geoName:"us",regionShortName:"eus"},[z.USEast2]:{geoName:"us",regionShortName:"eus2"},[z.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[z.USWest2]:{geoName:"us",regionShortName:"wus2"},[z.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[z.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[z.UKSouth]:{geoName:"uk",regionShortName:"suk"},[z.UKWest]:{geoName:"uk",regionShortName:"wuk"},[z.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[z.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[z.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[z.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[z.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[z.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[z.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[z.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[z.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[z.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[z.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[z.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[z.AsiaEast]:{geoName:"as",regionShortName:"eas"},[z.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[z.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[z.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[z.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[z.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[z.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[z.UAENorth]:{geoName:"ae",regionShortName:"nae"},[z.UAECentral]:{geoName:"ae",regionShortName:"cae"},[z.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[z.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[z.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[z.NorwayEast]:{geoName:"no",regionShortName:"eno"},[z.NorwayWest]:{geoName:"no",regionShortName:"wno"},[z.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[z.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[z.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[z.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[z.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[z.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[z.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[z.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[z.GovernmentUSDodCentral]:{regionShortName:"udc"},[z.GovernmentUSDodEast]:{regionShortName:"ude"},[z.ChinaEast]:{regionShortName:"cne"},[z.ChinaEast2]:{regionShortName:"cne2"},[z.ChinaEast3]:{regionShortName:"cne3"},[z.ChinaNorth]:{regionShortName:"cnn"},[z.ChinaNorth2]:{regionShortName:"cnn2"},[z.ChinaNorth3]:{regionShortName:"cnn3"},[z.UssecEast]:{geoName:"us",regionShortName:"erx"},[z.UssecWest]:{geoName:"us",regionShortName:"wrx"},[z.UsnatEast]:{geoName:"us",regionShortName:"eex"},[z.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var IA=R(()=>{"use strict";ku();});var Cs=R(()=>{"use strict";ku();DA();_A();IA();});function Ss(e,t){return TA?TA.isOverridden(e,t):{overridden:!1}}var TA,Ns=R(()=>{"use strict";});var Xf=R(()=>{"use strict";Cs();Ns();});function rq(e,t){let{region:r}=Tn();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ss(e.packageName,t);if(s.overridden)return typeof s.value=="string"?nq(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function nq(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function iq(e){let t=e.packageName;if(Mu.has(t)){let r=`settings has already been created for this package ${t}`;throw console.error(r),new Error(r)}if(Object.keys(e.settings).some(r=>Zf(t,r))){let r=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.settings).forEach(r=>{if(Object.keys(e.settings[r].values).filter(i=>i!=="default").some(i=>!$u(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Ds(e){iq(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:rq(e,r)}}),Mu.set(e.packageName,e),Object.defineProperties({},t)}function Yf(e,t){return Mu.has(e)?!!Mu.get(e).settings[t]:!1}var Mu,Bu=R(()=>{"use strict";Cs();Ns();em();_s();Mu=new Map});function PA(e,t){let{region:r}=Tn();return()=>{let n=Ss(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function oq(e){let t=e.packageName;if(Uu.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>Yf(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!$u(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function tm(e){oq(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:PA(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:PA(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Uu.set(e.packageName,e),Object.defineProperties(r,t)}function Zf(e,t){return Uu.has(e)?!!Uu.get(e).features[t]:!1}var Uu,em=R(()=>{"use strict";Cs();_s();Ns();Bu();Uu=new Map});var OA=b((FY,RA)=>{"use strict";RA.exports=function(t,r){if(r=r.split(":")[0],t=+t,!t)return!1;switch(r){case"http":case"ws":return t!==80;case"https":case"wss":return t!==443;case"ftp":return t!==21;case"gopher":return t!==70;case"file":return!1}return t!==0}});var kA=b(rm=>{"use strict";var aq=Object.prototype.hasOwnProperty,sq;function xA(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function LA(e){try{return encodeURIComponent(e)}catch{return null}}function lq(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=xA(n[1]),o=xA(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function uq(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(aq.call(e,i)){if(n=e[i],!n&&(n===null||n===sq||isNaN(n))&&(n=""),i=LA(i),n=LA(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}rm.stringify=uq;rm.parse=lq});var om=b((BY,qA)=>{"use strict";var MA=OA(),qu=kA(),BA=/[\n\r\t]/g,cq=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,dq=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,pq=/^[a-zA-Z]:/,fq=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function im(e){return(e||"").toString().replace(fq,"")}var nm=[["#","hash"],["?","query"],function(t,r){return tn(r.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],FA={hash:1,query:1};function $A(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new rn(unescape(e.pathname),{});else if(i==="string"){n=new rn(e,{});for(o in FA)delete n[o]}else if(i==="object"){for(o in e)o in FA||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=cq.test(e.href))}return n}function tn(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function UA(e,t){e=im(e),e=e.replace(BA,""),t=t||{};var r=dq.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):tn(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&tn(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||tn(n),slashesCount:a,rest:s}}function mq(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function rn(e,t,r){if(e=im(e),e=e.replace(BA,""),!(this instanceof rn))return new rn(e,t,r);var n,i,o,a,s,l,u=nm.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=qu.parse),t=$A(t),i=UA(e||"",t),n=!i.protocol&&!i.slashes,d.slashes=i.slashes||n&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||pq.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!tn(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);p<u.length;p++){if(a=u[p],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=mq(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&tn(d.protocol)&&(d.pathname="/"+d.pathname),MA(d.port,d.protocol)||(d.host=d.hostname,d.port=""),d.username=d.password="",d.auth&&(s=d.auth.indexOf(":"),~s?(d.username=d.auth.slice(0,s),d.username=encodeURIComponent(decodeURIComponent(d.username)),d.password=d.auth.slice(s+1),d.password=encodeURIComponent(decodeURIComponent(d.password))):d.username=encodeURIComponent(decodeURIComponent(d.auth)),d.auth=d.password?d.username+":"+d.password:d.username),d.origin=d.protocol!=="file:"&&tn(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function hq(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||qu.parse)(t)),n[e]=t;break;case"port":n[e]=t,MA(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<nm.length;a++){var s=nm[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&tn(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function gq(e){(!e||typeof e!="function")&&(e=qu.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||tn(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&tn(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}rn.prototype={set:hq,toString:gq};rn.extractProtocol=UA;rn.location=$A;rn.trimLeft=im;rn.qs=qu;qA.exports=rn});var vq,VA=R(()=>{"use strict";vq=de(om());});function am(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var Vu=R(()=>{"use strict";});var sm,lm,um=R(()=>{"use strict";Vu();sm=class{features=new Map;register(t,r){let n=am(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},lm=new sm});var cm=R(()=>{"use strict";});function $u(e){return yq.has(e)}var yq,_s=R(()=>{"use strict";Xf();em();Bu();Ns();Xf();VA();um();Vu();cm();yq=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var bq,GA=R(()=>{"use strict";_s();bq=Ds({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var Gu,$,W,Hi,Ko,zu,zA,WA,dm,Is=R(()=>{"use strict";Es();Gu=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return dm.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));Hi=class extends Gu{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ko=class e extends Gu{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?zu.Persistent:parseInt(zu[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(zu||(zu={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(zA||(zA={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(WA||(WA={}));dm=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new Wo;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ko.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ko.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ko.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ko.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var JA,fm,Jo,Ki,pm,Wu,Qo,Pn,De,jA,HA,KA,_r=R(()=>{"use strict";JA={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},fm={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(Jo||(Jo={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(Ki||(Ki={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(pm||(pm={}));Wu=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(Qo||(Qo={}));Pn=class{static StartTag="<"},De={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:Ki.Left,labelPosition:Qo.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(jA||(jA={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(HA||(HA={}));(function(e){e.IsHeader="IsHeader",e.IsFooter="IsFooter",e.ContainedInHeader="ContainedInHeader",e.ContainedInFooter="ContainedInFooter",e.NoElementFound="NoElementFound",e.NoTarget="NoTarget",e.CannotAddControlToHeader="CannotAddControlToHeader",e.CannotAddControlToFooter="CannotAddControlToFooter"})(KA||(KA={}))});var mm,QA=R(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(mm||(mm={}))});var ZA,wq,XA,FZ,MZ,Ts,YA,BZ,$Z,eE=R(()=>{"use strict";ZA=de(zi());Be();zo();GA();Is();_r();Ho();te();wq=de(Ti());QA();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(XA||(XA={}));FZ={Read:ji.Read,Edit:ji.Edit,Both:ji.Both,Container:ji.Container},MZ={input:jo.Input,bound:jo.Bound,output:jo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(Ts||(Ts={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(YA||(YA={}));BZ=new Set([x.Currency,x.Decimal,x.FP,x.Multiple,x.SingleLineEmail,x.SingleLinePhone,x.SingleLineText,x.SingleLineTextArea,x.SingleLineURL,x.SingleLineTickerSymbol,x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.Enum,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.TwoOptions,x.Boolean,x.PowerBIReport,x.DateAndTimeDateAndTime,x.DateAndTimeDateOnly,x.OptionSet,x.MultiSelectOptionSet,x.CardForm]),$Z={numbers:[x.WholeNone,x.FP,x.Decimal,x.Currency],text:[x.SingleLineText,x.SingleLineTextArea,x.Multiple],lookup:[x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding],dates:[x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime],allFields:[x.TwoOptions,x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime,x.FP,x.Decimal,x.WholeNone,x.WholeDuration,x.WholeTimeZone,x.WholeLanguage,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.Multiple,x.OptionSet,x.SingleLineText,x.SingleLineTextArea,x.SingleLineEmail,x.SingleLineURL,x.SingleLineTickerSymbol,x.SingleLinePhone]}});var Ir,ju,tE=R(()=>{"use strict";Ir=de(zi());ze();Be();ht();zo();Ho();eE();Is();te();et();_r();ju=class extends H{constructor(t){super(A.customControl,t)}customControlId;get id(){let t=this.getProperty(v.id);return I.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(St.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===St.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===St.name)?.value,o={Name:i,Type:x.Grid,Columns:[]},l=this.getParameters().get(St.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===v.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(v.Name)}get formFactor(){return this.getProperty(v.formFactor)}set formFactor(t){this.setProperty(v.formFactor,t)}async toJSON(t){if(this.id)return null;let r=await this.parametersToJSON(t),n=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(n)?-1:n,Name:this.name,Version:null,Parameters:r,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(Pn.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),p=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:p})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:SA.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===Ts.dataset?o.get(St.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:x.Grid}}):c.propertyType===Ts.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Ir.trackInfoTrace)(Et,{eventName:`${In}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===St.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===v.Type),s=o&&!o.ofTypeGroup.every(l=>!Kf.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===pi.FormComponent){let d=this.getFormComponentValueByParameterName(v.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(CA.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(v.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(v.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(v.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(v.DependentAttributeType),AllowFilterOff:M.IsStrictTrue(this.getFormComponentValueByParameterName(v.AllowFilterOff)),DisableQuickFind:M.IsStrictTrue(this.getFormComponentValueByParameterName(v.DisableQuickFind)),EnableViewPicker:!M.IsStrictTrue(this.getFormComponentValueByParameterName(v.DisableViewPicker))}}return{Name:t,Usage:l,Static:u,Primary:c,Value:this.getParameterValue(t)}}else{let l=new Error(`No lookup manifest info for ${t}`);(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let f=a.value;return{Type:f,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,f)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let p=new Error(`No property type info for ${t}`);(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,Ir.trackWarningTrace)(Et,{eventName:`${In}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return x.LookupCustomer;case $.Owner:return x.LookupOwner;case $.PartyList:return x.LookupPartyList;default:return n===W.Regarding?x.LookupRegarding:x.LookupSimple}}isLookupType(t){return Kf.includes(t)}isNumberTypeProperty(t,r){return Jf.includes(r)||t.ofTypeGroup.some(n=>Jf.includes(n))}isDataSet(t){return St.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var j,hm=R(()=>{"use strict";j=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var U,Xo,je,Hu=R(()=>{"use strict";ze();Es();Be();ht();Is();Gi();hm();_r();U=class{static get TextBoxControl(){return"4273EDBD-AC1D-40d3-9FB2-095C621B552D"}static get TickerControl(){return"1E1FC551-F7A8-43af-AC34-A8DC35C7B6D4"}static get UrlControl(){return"71716B6C-711E-476c-8AB8-5D11542BFB47"}static get PhoneNumberControl(){return"8C10015A-B339-4982-9474-A95FE05631A5"}static get EmailAddressControl(){return"ADA2203E-B4CD-49be-9DDF-234642B43B52"}static get RadioControl(){return"67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"}static get LookupControl(){return"270BD3DB-D9AF-4782-9025-509E298DEC0A"}static get DateTimeControl(){return"5B773807-9FB2-42db-97C3-7A91EFF8ADFF"}static get IntegerControl(){return"C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F"}static get MoneyControl(){return"533B9E00-756B-4312-95A0-DC888637AC78"}static get FloatControl(){return"0D2C745A-E5A8-4c8f-BA63-C6D3BB604660"}static get DecimalControl(){return"C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E"}static get TextAreaControl(){return"E0DECE4B-6FC8-4a8f-A065-082708572369"}static get PicklistControl(){return"3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"}static get HiddenInputControl(){return"5546E6CD-394C-4BEE-94A8-4425E17EF6C6"}static get GridControl(){return"E7A81278-8635-4D9E-8D4D-59480B391C5B"}static get CheckBoxControl(){return"B0C6723A-8503-4fd7-BB28-C8A06AC933C2"}static get IframeControl(){return"FD2A7985-3187-444e-908D-6624B21F69C0"}static get SocialInsightControl(){return"86B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get OrgInsightsControl(){return"76B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get DurationControl(){return"AA987274-CE4E-4271-A803-66164311A958"}static get RegardingControl(){return"F3015350-44A2-4aa0-97B5-00166532B5E9"}static get PartyListControl(){return"CBFB742C-14E7-4a17-96BB-1A13F7F64AA2"}static get TimeLineControl(){return"06375649-c143-495e-a496-c962e5b4488e"}static get TimeLineControlUC(){return"06375649-C143-495E-A496-C962E5B4488E"}static get TimeZonePicklistControl(){return"7C624A0B-F59E-493d-9583-638D34759266"}static get LanguagePickerControl(){return"671A9387-CA5A-4d1e-8AB7-06E39DDCF6B5"}static get AccessTeamTablePickerControl(){return"3F4E2A56-F102-4B4D-AB9C-F1574CA5BFDA"}static get KBViewerControl(){return"A62B6FA9-169E-406C-B1AA-EAB828CB6026"}static get PicklistStatusControl(){return"5D68B988-0661-4db2-BC3E-17598AD3BE6C"}static get EmailBodyControl(){return"6F3FB987-393B-4d2d-859F-9D0F0349B6AD"}static get PicklistLookupControl(){return"2305E33A-BAD3-4022-9E15-1856CF218333"}static get RelationshipRolePicklistControl(){return"5F986642-5961-4D9F-AB5E-643D71E231E9"}static get RelatedInformationControl(){return"163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8"}static get CoverPagePicklistControl(){return"4168A05C-D857-46AF-8457-5BB47EB04EA1"}static get MailMergeLanguagePickerControl(){return"B634828E-C390-444A-AFE6-E07315D9D970"}static get ConnectionControl(){return"3246F906-1F71-45F7-B11F-D7BE0F9D04C9"}static get ConnectionRoleObjectTypeListControl(){return"821ACF1A-7E46-4A0C-965D-FE14A57D78C7"}static get MapsControl(){return"62B0DF79-0464-470F-8AF7-4483CFEA0C7D"}static get MapLinkControl(){return"91DC0675-C8B9-4421-B1E0-261CEBF02BAC"}static get WebResourceHtmlControl(){return"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"}static get WebResourceImageControl(){return"587CDF98-C1D5-4BDE-8473-14A0BC7644A7"}static get WebResourceSilverlightControl(){return"080677DB-86EC-4544-AC42-F927E74B491F"}static get ReportControl(){return"A28F441B-916C-4865-87FD-0C5D53BD59C9"}static get ArticleContentControl(){return"F02EF977-2564-4B9A-B2F0-DF083D8A019B"}static get ProcessControl(){return"06E9F7AF-1F54-4681-8EEC-1E21A1CEB465"}static get ActivitiesWallControl(){return"6636847D-B74D-4994-B55A-A6FAF97ECEA2"}static get QuickFormControl(){return"69AF7DCA-2E3B-4EE7-9201-0DA731DD2413"}static get QuickFormCollectionControl(){return"5C5600E0-1D6E-4205-A272-BE80DA87FD42"}static get LinkControl(){return"DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"}static get CompositionLinkControl(){return"DB1284EF-9FFC-4E99-B382-0CC082FE2364"}static get ErrorStatusControl(){return"F4C16ECA-CA81-4E39-9448-834B8378721E"}static get ActivitiesContainerControl(){return"C72511AB-84E5-4FB7-A543-25B4FC01E83E"}static get AccessPrivilegeControl(){return"F93A31B2-99AC-4084-8EC2-D4027C31369A"}static get TimerControl(){return"9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E"}static get DynamicPropertyListControl(){return"6896F004-B17A-4202-861E-8B7EA2080E0B"}static get ButtonControl(){return"00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20"}static get SearchWidgetControl(){return"E616A57F-20E0-4534-8662-A101B5DDF4E0"}static get EmailRecipientActivityControl(){return"26E9760F-7454-40DE-BB07-F6DCCCB82040"}static get LabelControl(){return"39354E4A-5015-4D74-8031-EA9EB73A1322"}static get CustomControl(){return"F9A8A302-114E-466A-B582-6771B2AE0D92"}static get EditFilterControl(){return"1479835F-F852-4679-B864-C6892A2844C9"}static get RichEditorControl(){return"F94DB24F-263D-44A7-B38E-A35E9854812B"}static get PowerBIControl(){return"8C54228C-1B25-4909-A12A-F2B968BB0D62"}static get EmailEngagementActionsControl(){return"F454228D-1D25-4319-E12F-D27968BC0234"}static get ACIControl(){return"C8BFBBEF-6851-4401-A0CC-7450062FE085"}static get ChoicesControl(){return"4AA28AB7-9C13-4F57-A73D-AD894D048B5F"}static get ReferencePanelSubgridControl(){return"02D4264B-47E2-4B4C-AA95-F439F3F4D458"}static get ReferencePanelSearchWidget(){return"7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F"}static get ReferencePanelQuickFormCollectionControl(){return"B68B05F0-A46D-43F8-843B-917920AF806A"}static get SpacerControl(){return"E4BAB03A-A9A5-4C23-CC3B-54AA680150E2"}},Xo=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},je=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new Ct;static initializeFieldControls(){let t=new Ct,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new L(U.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new L(U.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new L(U.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new L(U.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new L(U.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new L(U.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new L(U.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new L(U.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new L(U.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new L(U.TimeZonePicklistControl));let p=e.getControlName($.WholeNumber,W.None);t.add(p,new L(U.IntegerControl));let f=e.getControlName($.DateTime,W.DateOnly);t.add(f,new L(U.DateTimeControl));let m=e.getControlName($.DateTime,W.DateAndTime);t.add(m,new L(U.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new L(U.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new L(U.LookupControl));let y=e.getControlName($.FloatingPointNumber,W.None);t.add(y,new L(U.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new L(U.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new L(U.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new L(U.TextAreaControl));let T=e.getControlName($.MultipleLineofText,W.Text);t.add(T,new L(U.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.TextArea);t.add(O,new L(U.TextAreaControl));let k=e.getControlName($.MultipleLineofText,W.Email);t.add(k,new L(U.EmailBodyControl));let F=e.getControlName($.OptionSet,W.None);t.add(F,new L(U.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new L(U.RadioControl));let q=e.getControlName($.Image,W.None);t.add(q,new L(U.WebResourceImageControl));let V=e.getControlName($.Image,W.None);t.add(V,new L(U.WebResourceHtmlControl));let Ve=e.getControlName($.TwoOptions,"Radio");t.add(Ve,new L(U.RadioControl));let Pt=e.getControlName($.TwoOptions,"CheckBox");t.add(Pt,new L(U.CheckBoxControl));let Je=e.getControlName($.TwoOptions,"List");t.add(Je,new L(U.PicklistControl));let Ge=e.getControlName($.State,W.None);t.add(Ge,new L(U.PicklistControl));let Z=e.getControlName($.Status,W.None);t.add(Z,new L(U.PicklistStatusControl));let ye=e.getControlName($.OwnerType,W.None);t.add(ye,new L(U.LookupControl));let hn=e.getControlName($.PartyListType,W.None);t.add(hn,new L(U.PartyListControl));let ot=e.getControlName($.LookupType,W.Regarding);t.add(ot,new L(U.RegardingControl));let Kn=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(Kn,new L(U.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!I.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=I.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return I.IsNullOrUndefined(t.control)||I.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===U.CustomControl}static initializeUnboundControls(){let t=new Ct;return t.add(U.ACIControl,j.ACIControl),t.add(U.IframeControl,j.IframeControl),t.add(U.SearchWidgetControl,j.SearchWidgetControl),t.add(U.MapsControl,j.MapsControl),t.add(U.QuickFormCollectionControl,j.QuickFormCollectionControl),t.add(U.GridControl,j.SubGridControl),t.add(U.WebResourceImageControl,j.WebResourceImageControl),t.add(U.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add(U.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add(U.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add(U.ReferencePanelSubgridControl,j.SubGridControl),t.add(U.TimerControl,j.TimerControl),t.add(U.TimeLineControl,j.NotesControl),t.add(U.TimeLineControlUC,j.NotesControl),t.add(U.SocialInsightControl,j.SocialInsightControl),t.add(Xo.RelationshipAssistant,j.CustomControl),t}static initializeReferencePanelControls(){let t=new Ct;return t.add(U.IframeControl,j.IframeControl),t.add(U.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add(U.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add(U.ReferencePanelSubgridControl,j.SubGridControl),t.add(U.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add(U.WebResourceImageControl,j.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Wo;return t.add(Jo.IFRAME,!0),t.add(Jo.SPACER,!0),t.add(Jo.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.control)||I.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!I.IsNullOrUndefined(t)&&!I.IsNullOrUndefined(t.Name)&&t.Name.indexOf(De.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=M.EmptyString;if(I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.control)||I.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.guidString)?M.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===U.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===U.CustomControl&&!I.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case j.IframeControl:case j.ACIControl:case j.SocialInsightControl:return 6;case j.SubGridControl:case j.CustomControl:return 4;case j.WebResourceImageControl:return 15;case j.WebResourceHtmlControl:return 15;case j.MapsControl:return 8;case j.SearchWidgetControl:return 10;case j.NotesControl:case j.TimeLineControl:return 15;case j.TimerControl:return 2;default:}}static isLookUpControl(t){return!I.IsNullOrUndefined(t)&&t.ClassId.guidString===U.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!I.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!I.IsNullOrUndefined(t)&&(t.guidString===Xo.RelationshipAssistant||t.guidString===Xo.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!I.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!I.IsNullOrUndefined(t)&&t.guidString===Xo.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(I.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===U.CustomControl&&!I.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Ku,rE=R(()=>{"use strict";Ku=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let r=this.listeners.indexOf(t);r>-1&&this.listeners.splice(r,1)}emit(t){this.listeners.forEach(r=>r(t)),this.listenersOncer.forEach(r=>r(t)),this.listenersOncer=[]}pipe(t){return this.on(r=>t.emit(r))}}});var Ji,Yo,nE,iE,fi,oE,aE,gm=R(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ji||(Ji={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Yo||(Yo={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(nE||(nE={}));(function(e){e[e.None=0]="None",e[e.Create=1]="Create",e[e.Existing=2]="Existing",e[e.ReadOnly=3]="ReadOnly",e[e.Disabled=4]="Disabled",e[e.BulkEdit=6]="BulkEdit",e[e.Merge=7]="Merge",e[e.Print=8]="Print",e[e.FollowUp=9]="FollowUp"})(iE||(iE={}));(function(e){e[e.None=-1]="None",e[e.AppointmentBook=0]="AppointmentBook",e[e.Hardcoded=1]="Hardcoded",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.Dashboard=5]="Dashboard",e[e.Quick=6]="Quick",e[e.Mobile=7]="Mobile",e[e.Read=8]="Read",e[e.QuickCreate=9]="QuickCreate",e[e.Dialog=10]="Dialog",e[e.Card=11]="Card",e[e.TaskBasedForm=12]="TaskBasedForm",e[e.InteractionCentricDashboard=13]="InteractionCentricDashboard"})(fi||(fi={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(oE||(oE={}));(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(aE||(aE={}))});var Zo,sE=R(()=>{"use strict";_s();Zo=tm({packageName:"cds-designer-models",features:{showAllPCFControls:{owner:"anchoudh",description:"Do not only show the controls that exist on the whitelist",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},showTestControls:{owner:"lucorre",description:"Show advanced custom controls for testing (designated in Authoring Manifest with isTestOnly=true)",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},enablePrefetchGetMoreComponentsLocalization:{owner:"vajagarl",description:"Enables prefetching the localization files for controls displayed in custom control picker",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0}},showMapControl:{owner:"vayilavarapu",createdDate:"07/19/2022",description:"Show map control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableFallbackFormTemplate:{owner:"vajagarl",createdDate:"01/03/2023",description:"Enable default form template as fallback if unable to retrieve a form template from Dataverse",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableAutoInsertionOfCellInRow:{owner:"debeshd",createdDate:"09/01/2023",description:"Enable the auto insertion of cell in a row when a section is initialized",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableOneGridEvents:{owner:"aansu",createdDate:"08/21/2024",description:"Enable OneGrid events in form designer",enabledFor:{test:!0,preprod:!0,prod:!0,preview:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},disablePBIComponents:{owner:"adekulkarni",createdDate:"02/13/2025",description:"Disables PBI components and cleans them up from the form",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableAgentResponse:{owner:"jennietu",createdDate:"04/24/2025",description:"Enables agent response in form designer",enabledFor:{test:!0,preprod:!0,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableDelayedLocalizationForCustomControls:{owner:"aansu",createdDate:"06/08/2025",description:"Enables delayed localization of custom control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}}}})});function lE(e){return{...e,extractConfig:t=>Aq(t,Object.keys(e.fallback))}}function Aq(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var vm=R(()=>{"use strict";});var ym=b((fee,cE)=>{var Ps=new Proxy(function(){return Ps},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ps},apply:function(){return Ps},construct:function(){return{}}}),uE=function(){return Ps};Object.setPrototypeOf(uE,Ps);cE.exports=uE});var fE=b((mee,pE)=>{var Rs=new Proxy(function(){return Rs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Rs},apply:function(){return Rs},construct:function(){return{}}}),dE=function(){return Rs};Object.setPrototypeOf(dE,Rs);pE.exports=dE});var bm=b((hee,hE)=>{var Os=new Proxy(function(){return Os},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Os},apply:function(){return Os},construct:function(){return{}}}),mE=function(){return Os};Object.setPrototypeOf(mE,Os);hE.exports=mE});var vE=b((gee,gE)=>{function Eq(){this.__data__=[],this.size=0}gE.exports=Eq});var ea=b((vee,yE)=>{function Cq(e,t){return e===t||e!==e&&t!==t}yE.exports=Cq});var xs=b((yee,bE)=>{var Sq=ea();function Nq(e,t){for(var r=e.length;r--;)if(Sq(e[r][0],t))return r;return-1}bE.exports=Nq});var AE=b((bee,wE)=>{var Dq=xs(),_q=Array.prototype,Iq=_q.splice;function Tq(e){var t=this.__data__,r=Dq(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Iq.call(t,r,1),--this.size,!0}wE.exports=Tq});var CE=b((wee,EE)=>{var Pq=xs();function Rq(e){var t=this.__data__,r=Pq(t,e);return r<0?void 0:t[r][1]}EE.exports=Rq});var NE=b((Aee,SE)=>{var Oq=xs();function xq(e){return Oq(this.__data__,e)>-1}SE.exports=xq});var _E=b((Eee,DE)=>{var Lq=xs();function kq(e,t){var r=this.__data__,n=Lq(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}DE.exports=kq});var Ls=b((Cee,IE)=>{var Fq=vE(),Mq=AE(),Bq=CE(),$q=NE(),Uq=_E();function ta(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}ta.prototype.clear=Fq;ta.prototype.delete=Mq;ta.prototype.get=Bq;ta.prototype.has=$q;ta.prototype.set=Uq;IE.exports=ta});var PE=b((See,TE)=>{var qq=Ls();function Vq(){this.__data__=new qq,this.size=0}TE.exports=Vq});var OE=b((Nee,RE)=>{function Gq(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}RE.exports=Gq});var LE=b((Dee,xE)=>{function zq(e){return this.__data__.get(e)}xE.exports=zq});var FE=b((_ee,kE)=>{function Wq(e){return this.__data__.has(e)}kE.exports=Wq});var wm=b((Iee,ME)=>{var jq=typeof global=="object"&&global&&global.Object===Object&&global;ME.exports=jq});var Tr=b((Tee,BE)=>{var Hq=wm(),Kq=typeof self=="object"&&self&&self.Object===Object&&self,Jq=Hq||Kq||Function("return this")();BE.exports=Jq});var ks=b((Pee,$E)=>{var Qq=Tr(),Xq=Qq.Symbol;$E.exports=Xq});var GE=b((Ree,VE)=>{var UE=ks(),qE=Object.prototype,Yq=qE.hasOwnProperty,Zq=qE.toString,Fs=UE?UE.toStringTag:void 0;function e3(e){var t=Yq.call(e,Fs),r=e[Fs];try{e[Fs]=void 0;var n=!0}catch{}var i=Zq.call(e);return n&&(t?e[Fs]=r:delete e[Fs]),i}VE.exports=e3});var WE=b((Oee,zE)=>{var t3=Object.prototype,r3=t3.toString;function n3(e){return r3.call(e)}zE.exports=n3});var Qi=b((xee,KE)=>{var jE=ks(),i3=GE(),o3=WE(),a3="[object Null]",s3="[object Undefined]",HE=jE?jE.toStringTag:void 0;function l3(e){return e==null?e===void 0?s3:a3:HE&&HE in Object(e)?i3(e):o3(e)}KE.exports=l3});var Rn=b((Lee,JE)=>{function u3(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}JE.exports=u3});var Ju=b((kee,QE)=>{var c3=Qi(),d3=Rn(),p3="[object AsyncFunction]",f3="[object Function]",m3="[object GeneratorFunction]",h3="[object Proxy]";function g3(e){if(!d3(e))return!1;var t=c3(e);return t==f3||t==m3||t==p3||t==h3}QE.exports=g3});var YE=b((Fee,XE)=>{var v3=Tr(),y3=v3["__core-js_shared__"];XE.exports=y3});var tC=b((Mee,eC)=>{var Am=YE(),ZE=(function(){var e=/[^.]+$/.exec(Am&&Am.keys&&Am.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function b3(e){return!!ZE&&ZE in e}eC.exports=b3});var Em=b((Bee,rC)=>{var w3=Function.prototype,A3=w3.toString;function E3(e){if(e!=null){try{return A3.call(e)}catch{}try{return e+""}catch{}}return""}rC.exports=E3});var iC=b(($ee,nC)=>{var C3=Ju(),S3=tC(),N3=Rn(),D3=Em(),_3=/[\\^$.*+?()[\]{}|]/g,I3=/^\[object .+?Constructor\]$/,T3=Function.prototype,P3=Object.prototype,R3=T3.toString,O3=P3.hasOwnProperty,x3=RegExp("^"+R3.call(O3).replace(_3,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function L3(e){if(!N3(e)||S3(e))return!1;var t=C3(e)?x3:I3;return t.test(D3(e))}nC.exports=L3});var aC=b((Uee,oC)=>{function k3(e,t){return e?.[t]}oC.exports=k3});var mi=b((qee,sC)=>{var F3=iC(),M3=aC();function B3(e,t){var r=M3(e,t);return F3(r)?r:void 0}sC.exports=B3});var Qu=b((Vee,lC)=>{var $3=mi(),U3=Tr(),q3=$3(U3,"Map");lC.exports=q3});var Ms=b((Gee,uC)=>{var V3=mi(),G3=V3(Object,"create");uC.exports=G3});var pC=b((zee,dC)=>{var cC=Ms();function z3(){this.__data__=cC?cC(null):{},this.size=0}dC.exports=z3});var mC=b((Wee,fC)=>{function W3(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}fC.exports=W3});var gC=b((jee,hC)=>{var j3=Ms(),H3="__lodash_hash_undefined__",K3=Object.prototype,J3=K3.hasOwnProperty;function Q3(e){var t=this.__data__;if(j3){var r=t[e];return r===H3?void 0:r}return J3.call(t,e)?t[e]:void 0}hC.exports=Q3});var yC=b((Hee,vC)=>{var X3=Ms(),Y3=Object.prototype,Z3=Y3.hasOwnProperty;function e4(e){var t=this.__data__;return X3?t[e]!==void 0:Z3.call(t,e)}vC.exports=e4});var wC=b((Kee,bC)=>{var t4=Ms(),r4="__lodash_hash_undefined__";function n4(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=t4&&t===void 0?r4:t,this}bC.exports=n4});var EC=b((Jee,AC)=>{var i4=pC(),o4=mC(),a4=gC(),s4=yC(),l4=wC();function ra(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}ra.prototype.clear=i4;ra.prototype.delete=o4;ra.prototype.get=a4;ra.prototype.has=s4;ra.prototype.set=l4;AC.exports=ra});var NC=b((Qee,SC)=>{var CC=EC(),u4=Ls(),c4=Qu();function d4(){this.size=0,this.__data__={hash:new CC,map:new(c4||u4),string:new CC}}SC.exports=d4});var _C=b((Xee,DC)=>{function p4(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}DC.exports=p4});var Bs=b((Yee,IC)=>{var f4=_C();function m4(e,t){var r=e.__data__;return f4(t)?r[typeof t=="string"?"string":"hash"]:r.map}IC.exports=m4});var PC=b((Zee,TC)=>{var h4=Bs();function g4(e){var t=h4(this,e).delete(e);return this.size-=t?1:0,t}TC.exports=g4});var OC=b((ete,RC)=>{var v4=Bs();function y4(e){return v4(this,e).get(e)}RC.exports=y4});var LC=b((tte,xC)=>{var b4=Bs();function w4(e){return b4(this,e).has(e)}xC.exports=w4});var FC=b((rte,kC)=>{var A4=Bs();function E4(e,t){var r=A4(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}kC.exports=E4});var Xu=b((nte,MC)=>{var C4=NC(),S4=PC(),N4=OC(),D4=LC(),_4=FC();function na(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}na.prototype.clear=C4;na.prototype.delete=S4;na.prototype.get=N4;na.prototype.has=D4;na.prototype.set=_4;MC.exports=na});var $C=b((ite,BC)=>{var I4=Ls(),T4=Qu(),P4=Xu(),R4=200;function O4(e,t){var r=this.__data__;if(r instanceof I4){var n=r.__data__;if(!T4||n.length<R4-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new P4(n)}return r.set(e,t),this.size=r.size,this}BC.exports=O4});var Cm=b((ote,UC)=>{var x4=Ls(),L4=PE(),k4=OE(),F4=LE(),M4=FE(),B4=$C();function ia(e){var t=this.__data__=new x4(e);this.size=t.size}ia.prototype.clear=L4;ia.prototype.delete=k4;ia.prototype.get=F4;ia.prototype.has=M4;ia.prototype.set=B4;UC.exports=ia});var VC=b((ate,qC)=>{var $4="__lodash_hash_undefined__";function U4(e){return this.__data__.set(e,$4),this}qC.exports=U4});var zC=b((ste,GC)=>{function q4(e){return this.__data__.has(e)}GC.exports=q4});var jC=b((lte,WC)=>{var V4=Xu(),G4=VC(),z4=zC();function Yu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new V4;++t<r;)this.add(e[t])}Yu.prototype.add=Yu.prototype.push=G4;Yu.prototype.has=z4;WC.exports=Yu});var KC=b((ute,HC)=>{function W4(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}HC.exports=W4});var QC=b((cte,JC)=>{function j4(e,t){return e.has(t)}JC.exports=j4});var Sm=b((dte,XC)=>{var H4=jC(),K4=KC(),J4=QC(),Q4=1,X4=2;function Y4(e,t,r,n,i,o){var a=r&Q4,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,p=!0,f=r&X4?new H4:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var g=a?n(h,m,d,t,e,o):n(m,h,d,e,t,o);if(g!==void 0){if(g)continue;p=!1;break}if(f){if(!K4(t,function(y,w){if(!J4(f,w)&&(m===y||i(m,y,r,n,o)))return f.push(w)})){p=!1;break}}else if(!(m===h||i(m,h,r,n,o))){p=!1;break}}return o.delete(e),o.delete(t),p}XC.exports=Y4});var Nm=b((pte,YC)=>{var Z4=Tr(),eV=Z4.Uint8Array;YC.exports=eV});var eS=b((fte,ZC)=>{function tV(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}ZC.exports=tV});var rS=b((mte,tS)=>{function rV(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}tS.exports=rV});var sS=b((hte,aS)=>{var nS=ks(),iS=Nm(),nV=ea(),iV=Sm(),oV=eS(),aV=rS(),sV=1,lV=2,uV="[object Boolean]",cV="[object Date]",dV="[object Error]",pV="[object Map]",fV="[object Number]",mV="[object RegExp]",hV="[object Set]",gV="[object String]",vV="[object Symbol]",yV="[object ArrayBuffer]",bV="[object DataView]",oS=nS?nS.prototype:void 0,Dm=oS?oS.valueOf:void 0;function wV(e,t,r,n,i,o,a){switch(r){case bV:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case yV:return!(e.byteLength!=t.byteLength||!o(new iS(e),new iS(t)));case uV:case cV:case fV:return nV(+e,+t);case dV:return e.name==t.name&&e.message==t.message;case mV:case gV:return e==t+"";case pV:var s=oV;case hV:var l=n&sV;if(s||(s=aV),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=lV,a.set(e,t);var c=iV(s(e),s(t),n,i,o,a);return a.delete(e),c;case vV:if(Dm)return Dm.call(e)==Dm.call(t)}return!1}aS.exports=wV});var uS=b((gte,lS)=>{function AV(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}lS.exports=AV});var hi=b((vte,cS)=>{var EV=Array.isArray;cS.exports=EV});var pS=b((yte,dS)=>{var CV=uS(),SV=hi();function NV(e,t,r){var n=t(e);return SV(e)?n:CV(n,r(e))}dS.exports=NV});var mS=b((bte,fS)=>{function DV(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}fS.exports=DV});var gS=b((wte,hS)=>{function _V(){return[]}hS.exports=_V});var bS=b((Ate,yS)=>{var IV=mS(),TV=gS(),PV=Object.prototype,RV=PV.propertyIsEnumerable,vS=Object.getOwnPropertySymbols,OV=vS?function(e){return e==null?[]:(e=Object(e),IV(vS(e),function(t){return RV.call(e,t)}))}:TV;yS.exports=OV});var AS=b((Ete,wS)=>{function xV(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}wS.exports=xV});var gi=b((Cte,ES)=>{function LV(e){return e!=null&&typeof e=="object"}ES.exports=LV});var SS=b((Ste,CS)=>{var kV=Qi(),FV=gi(),MV="[object Arguments]";function BV(e){return FV(e)&&kV(e)==MV}CS.exports=BV});var _m=b((Nte,_S)=>{var NS=SS(),$V=gi(),DS=Object.prototype,UV=DS.hasOwnProperty,qV=DS.propertyIsEnumerable,VV=NS((function(){return arguments})())?NS:function(e){return $V(e)&&UV.call(e,"callee")&&!qV.call(e,"callee")};_S.exports=VV});var TS=b((Dte,IS)=>{function GV(){return!1}IS.exports=GV});var Zu=b(($s,oa)=>{var zV=Tr(),WV=TS(),OS=typeof $s=="object"&&$s&&!$s.nodeType&&$s,PS=OS&&typeof oa=="object"&&oa&&!oa.nodeType&&oa,jV=PS&&PS.exports===OS,RS=jV?zV.Buffer:void 0,HV=RS?RS.isBuffer:void 0,KV=HV||WV;oa.exports=KV});var ec=b((_te,xS)=>{var JV=9007199254740991,QV=/^(?:0|[1-9]\d*)$/;function XV(e,t){var r=typeof e;return t=t??JV,!!t&&(r=="number"||r!="symbol"&&QV.test(e))&&e>-1&&e%1==0&&e<t}xS.exports=XV});var Im=b((Ite,LS)=>{var YV=9007199254740991;function ZV(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=YV}LS.exports=ZV});var FS=b((Tte,kS)=>{var eG=Qi(),tG=Im(),rG=gi(),nG="[object Arguments]",iG="[object Array]",oG="[object Boolean]",aG="[object Date]",sG="[object Error]",lG="[object Function]",uG="[object Map]",cG="[object Number]",dG="[object Object]",pG="[object RegExp]",fG="[object Set]",mG="[object String]",hG="[object WeakMap]",gG="[object ArrayBuffer]",vG="[object DataView]",yG="[object Float32Array]",bG="[object Float64Array]",wG="[object Int8Array]",AG="[object Int16Array]",EG="[object Int32Array]",CG="[object Uint8Array]",SG="[object Uint8ClampedArray]",NG="[object Uint16Array]",DG="[object Uint32Array]",Ce={};Ce[yG]=Ce[bG]=Ce[wG]=Ce[AG]=Ce[EG]=Ce[CG]=Ce[SG]=Ce[NG]=Ce[DG]=!0;Ce[nG]=Ce[iG]=Ce[gG]=Ce[oG]=Ce[vG]=Ce[aG]=Ce[sG]=Ce[lG]=Ce[uG]=Ce[cG]=Ce[dG]=Ce[pG]=Ce[fG]=Ce[mG]=Ce[hG]=!1;function _G(e){return rG(e)&&tG(e.length)&&!!Ce[eG(e)]}kS.exports=_G});var BS=b((Pte,MS)=>{function IG(e){return function(t){return e(t)}}MS.exports=IG});var US=b((Us,aa)=>{var TG=wm(),$S=typeof Us=="object"&&Us&&!Us.nodeType&&Us,qs=$S&&typeof aa=="object"&&aa&&!aa.nodeType&&aa,PG=qs&&qs.exports===$S,Tm=PG&&TG.process,RG=(function(){try{var e=qs&&qs.require&&qs.require("util").types;return e||Tm&&Tm.binding&&Tm.binding("util")}catch{}})();aa.exports=RG});var tc=b((Rte,GS)=>{var OG=FS(),xG=BS(),qS=US(),VS=qS&&qS.isTypedArray,LG=VS?xG(VS):OG;GS.exports=LG});var Pm=b((Ote,zS)=>{var kG=AS(),FG=_m(),MG=hi(),BG=Zu(),$G=ec(),UG=tc(),qG=Object.prototype,VG=qG.hasOwnProperty;function GG(e,t){var r=MG(e),n=!r&&FG(e),i=!r&&!n&&BG(e),o=!r&&!n&&!i&&UG(e),a=r||n||i||o,s=a?kG(e.length,String):[],l=s.length;for(var u in e)(t||VG.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||$G(u,l)))&&s.push(u);return s}zS.exports=GG});var rc=b((xte,WS)=>{var zG=Object.prototype;function WG(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||zG;return e===r}WS.exports=WG});var Rm=b((Lte,jS)=>{function jG(e,t){return function(r){return e(t(r))}}jS.exports=jG});var KS=b((kte,HS)=>{var HG=Rm(),KG=HG(Object.keys,Object);HS.exports=KG});var QS=b((Fte,JS)=>{var JG=rc(),QG=KS(),XG=Object.prototype,YG=XG.hasOwnProperty;function ZG(e){if(!JG(e))return QG(e);var t=[];for(var r in Object(e))YG.call(e,r)&&r!="constructor"&&t.push(r);return t}JS.exports=ZG});var Vs=b((Mte,XS)=>{var e9=Ju(),t9=Im();function r9(e){return e!=null&&t9(e.length)&&!e9(e)}XS.exports=r9});var ZS=b((Bte,YS)=>{var n9=Pm(),i9=QS(),o9=Vs();function a9(e){return o9(e)?n9(e):i9(e)}YS.exports=a9});var tN=b(($te,eN)=>{var s9=pS(),l9=bS(),u9=ZS();function c9(e){return s9(e,u9,l9)}eN.exports=c9});var iN=b((Ute,nN)=>{var rN=tN(),d9=1,p9=Object.prototype,f9=p9.hasOwnProperty;function m9(e,t,r,n,i,o){var a=r&d9,s=rN(e),l=s.length,u=rN(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var p=s[d];if(!(a?p in t:f9.call(t,p)))return!1}var f=o.get(e),m=o.get(t);if(f&&m)return f==t&&m==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){p=s[d];var y=e[p],w=t[p];if(n)var C=a?n(w,y,p,t,e,o):n(y,w,p,e,t,o);if(!(C===void 0?y===w||i(y,w,r,n,o):C)){h=!1;break}g||(g=p=="constructor")}if(h&&!g){var S=e.constructor,T=t.constructor;S!=T&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof T=="function"&&T instanceof T)&&(h=!1)}return o.delete(e),o.delete(t),h}nN.exports=m9});var aN=b((qte,oN)=>{var h9=mi(),g9=Tr(),v9=h9(g9,"DataView");oN.exports=v9});var lN=b((Vte,sN)=>{var y9=mi(),b9=Tr(),w9=y9(b9,"Promise");sN.exports=w9});var cN=b((Gte,uN)=>{var A9=mi(),E9=Tr(),C9=A9(E9,"Set");uN.exports=C9});var pN=b((zte,dN)=>{var S9=mi(),N9=Tr(),D9=S9(N9,"WeakMap");dN.exports=D9});var wN=b((Wte,bN)=>{var Om=aN(),xm=Qu(),Lm=lN(),km=cN(),Fm=pN(),yN=Qi(),sa=Em(),fN="[object Map]",_9="[object Object]",mN="[object Promise]",hN="[object Set]",gN="[object WeakMap]",vN="[object DataView]",I9=sa(Om),T9=sa(xm),P9=sa(Lm),R9=sa(km),O9=sa(Fm),Xi=yN;(Om&&Xi(new Om(new ArrayBuffer(1)))!=vN||xm&&Xi(new xm)!=fN||Lm&&Xi(Lm.resolve())!=mN||km&&Xi(new km)!=hN||Fm&&Xi(new Fm)!=gN)&&(Xi=function(e){var t=yN(e),r=t==_9?e.constructor:void 0,n=r?sa(r):"";if(n)switch(n){case I9:return vN;case T9:return fN;case P9:return mN;case R9:return hN;case O9:return gN}return t});bN.exports=Xi});var IN=b((jte,_N)=>{var Mm=Cm(),x9=Sm(),L9=sS(),k9=iN(),AN=wN(),EN=hi(),CN=Zu(),F9=tc(),M9=1,SN="[object Arguments]",NN="[object Array]",nc="[object Object]",B9=Object.prototype,DN=B9.hasOwnProperty;function $9(e,t,r,n,i,o){var a=EN(e),s=EN(t),l=a?NN:AN(e),u=s?NN:AN(t);l=l==SN?nc:l,u=u==SN?nc:u;var c=l==nc,d=u==nc,p=l==u;if(p&&CN(e)){if(!CN(t))return!1;a=!0,c=!1}if(p&&!c)return o||(o=new Mm),a||F9(e)?x9(e,t,r,n,i,o):L9(e,t,l,r,n,i,o);if(!(r&M9)){var f=c&&DN.call(e,"__wrapped__"),m=d&&DN.call(t,"__wrapped__");if(f||m){var h=f?e.value():e,g=m?t.value():t;return o||(o=new Mm),i(h,g,r,n,o)}}return p?(o||(o=new Mm),k9(e,t,r,n,i,o)):!1}_N.exports=$9});var ON=b((Hte,RN)=>{var U9=IN(),TN=gi();function PN(e,t,r,n,i){return e===t?!0:e==null||t==null||!TN(e)&&!TN(t)?e!==e&&t!==t:U9(e,t,r,n,PN,i)}RN.exports=PN});var LN=b((Kte,xN)=>{var q9=ON();function V9(e,t){return q9(e,t)}xN.exports=V9});var Bm=b((Jte,kN)=>{var G9=mi(),z9=(function(){try{var e=G9(Object,"defineProperty");return e({},"",{}),e}catch{}})();kN.exports=z9});var ic=b((Qte,MN)=>{var FN=Bm();function W9(e,t,r){t=="__proto__"&&FN?FN(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}MN.exports=W9});var $m=b((Xte,BN)=>{var j9=ic(),H9=ea();function K9(e,t,r){(r!==void 0&&!H9(e[t],r)||r===void 0&&!(t in e))&&j9(e,t,r)}BN.exports=K9});var UN=b((Yte,$N)=>{function J9(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}$N.exports=J9});var VN=b((Zte,qN)=>{var Q9=UN(),X9=Q9();qN.exports=X9});var HN=b((Gs,la)=>{var Y9=Tr(),jN=typeof Gs=="object"&&Gs&&!Gs.nodeType&&Gs,GN=jN&&typeof la=="object"&&la&&!la.nodeType&&la,Z9=GN&&GN.exports===jN,zN=Z9?Y9.Buffer:void 0,WN=zN?zN.allocUnsafe:void 0;function e5(e,t){if(t)return e.slice();var r=e.length,n=WN?WN(r):new e.constructor(r);return e.copy(n),n}la.exports=e5});var QN=b((ere,JN)=>{var KN=Nm();function t5(e){var t=new e.constructor(e.byteLength);return new KN(t).set(new KN(e)),t}JN.exports=t5});var YN=b((tre,XN)=>{var r5=QN();function n5(e,t){var r=t?r5(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}XN.exports=n5});var eD=b((rre,ZN)=>{function i5(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}ZN.exports=i5});var nD=b((nre,rD)=>{var o5=Rn(),tD=Object.create,a5=(function(){function e(){}return function(t){if(!o5(t))return{};if(tD)return tD(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();rD.exports=a5});var Um=b((ire,iD)=>{var s5=Rm(),l5=s5(Object.getPrototypeOf,Object);iD.exports=l5});var aD=b((ore,oD)=>{var u5=nD(),c5=Um(),d5=rc();function p5(e){return typeof e.constructor=="function"&&!d5(e)?u5(c5(e)):{}}oD.exports=p5});var lD=b((are,sD)=>{var f5=Vs(),m5=gi();function h5(e){return m5(e)&&f5(e)}sD.exports=h5});var dD=b((sre,cD)=>{var g5=Qi(),v5=Um(),y5=gi(),b5="[object Object]",w5=Function.prototype,A5=Object.prototype,uD=w5.toString,E5=A5.hasOwnProperty,C5=uD.call(Object);function S5(e){if(!y5(e)||g5(e)!=b5)return!1;var t=v5(e);if(t===null)return!0;var r=E5.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&uD.call(r)==C5}cD.exports=S5});var qm=b((lre,pD)=>{function N5(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}pD.exports=N5});var Vm=b((ure,fD)=>{var D5=ic(),_5=ea(),I5=Object.prototype,T5=I5.hasOwnProperty;function P5(e,t,r){var n=e[t];(!(T5.call(e,t)&&_5(n,r))||r===void 0&&!(t in e))&&D5(e,t,r)}fD.exports=P5});var hD=b((cre,mD)=>{var R5=Vm(),O5=ic();function x5(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?O5(r,s,l):R5(r,s,l)}return r}mD.exports=x5});var vD=b((dre,gD)=>{function L5(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}gD.exports=L5});var bD=b((pre,yD)=>{var k5=Rn(),F5=rc(),M5=vD(),B5=Object.prototype,$5=B5.hasOwnProperty;function U5(e){if(!k5(e))return M5(e);var t=F5(e),r=[];for(var n in e)n=="constructor"&&(t||!$5.call(e,n))||r.push(n);return r}yD.exports=U5});var Gm=b((fre,wD)=>{var q5=Pm(),V5=bD(),G5=Vs();function z5(e){return G5(e)?q5(e,!0):V5(e)}wD.exports=z5});var ED=b((mre,AD)=>{var W5=hD(),j5=Gm();function H5(e){return W5(e,j5(e))}AD.exports=H5});var ID=b((hre,_D)=>{var CD=$m(),K5=HN(),J5=YN(),Q5=eD(),X5=aD(),SD=_m(),ND=hi(),Y5=lD(),Z5=Zu(),e8=Ju(),t8=Rn(),r8=dD(),n8=tc(),DD=qm(),i8=ED();function o8(e,t,r,n,i,o,a){var s=DD(e,r),l=DD(t,r),u=a.get(l);if(u){CD(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var p=ND(l),f=!p&&Z5(l),m=!p&&!f&&n8(l);c=l,p||f||m?ND(s)?c=s:Y5(s)?c=Q5(s):f?(d=!1,c=K5(l,!0)):m?(d=!1,c=J5(l,!0)):c=[]:r8(l)||SD(l)?(c=s,SD(s)?c=i8(s):(!t8(s)||e8(s))&&(c=X5(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),CD(e,r,c)}_D.exports=o8});var zm=b((gre,PD)=>{var a8=Cm(),s8=$m(),l8=VN(),u8=ID(),c8=Rn(),d8=Gm(),p8=qm();function TD(e,t,r,n,i){e!==t&&l8(t,function(o,a){if(i||(i=new a8),c8(o))u8(e,t,a,r,TD,n,i);else{var s=n?n(p8(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),s8(e,a,s)}},d8)}PD.exports=TD});var Wm=b((vre,RD)=>{function f8(e){return e}RD.exports=f8});var xD=b((yre,OD)=>{function m8(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}OD.exports=m8});var FD=b((bre,kD)=>{var h8=xD(),LD=Math.max;function g8(e,t,r){return t=LD(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=LD(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),h8(e,this,s)}}kD.exports=g8});var BD=b((wre,MD)=>{function v8(e){return function(){return e}}MD.exports=v8});var qD=b((Are,UD)=>{var y8=BD(),$D=Bm(),b8=Wm(),w8=$D?function(e,t){return $D(e,"toString",{configurable:!0,enumerable:!1,value:y8(t),writable:!0})}:b8;UD.exports=w8});var GD=b((Ere,VD)=>{var A8=800,E8=16,C8=Date.now;function S8(e){var t=0,r=0;return function(){var n=C8(),i=E8-(n-r);if(r=n,i>0){if(++t>=A8)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}VD.exports=S8});var WD=b((Cre,zD)=>{var N8=qD(),D8=GD(),_8=D8(N8);zD.exports=_8});var HD=b((Sre,jD)=>{var I8=Wm(),T8=FD(),P8=WD();function R8(e,t){return P8(T8(e,t,I8),e+"")}jD.exports=R8});var JD=b((Nre,KD)=>{var O8=ea(),x8=Vs(),L8=ec(),k8=Rn();function F8(e,t,r){if(!k8(r))return!1;var n=typeof t;return(n=="number"?x8(r)&&L8(t,r.length):n=="string"&&t in r)?O8(r[t],e):!1}KD.exports=F8});var jm=b((Dre,QD)=>{var M8=HD(),B8=JD();function $8(e){return M8(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&B8(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}QD.exports=$8});var YD=b((_re,XD)=>{var U8=zm(),q8=jm(),V8=q8(function(e,t,r,n){U8(e,t,r,n)});XD.exports=V8});var pr,zs=R(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(pr||(pr={}))});function e_(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${ZD.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var ZD,G8,t_=R(()=>{"use strict";ZD=de(bm()),G8=de(ym());});var Hm,r_=R(()=>{"use strict";Bu();Hm=Ds({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var i_,o_,a_,s_,Km,z8,oc,n_,Jm=R(()=>{"use strict";i_=de(ym()),o_=de(fE()),a_=de(bm()),s_=de(LN()),Km=de(YD());zs();t_();r_();z8=60*1e3,oc=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=pr.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,r,n="PROD"){this.clientName=t,this.logger=r,this.endpointType=n,this.ecsEndpoint=n==="PROD"?Hm.prodEcsEndpoint:Hm.integrationEcsEndpoint}client=new o_.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=i_.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[a_.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:e_(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===pr.NotLoaded&&(this._status=pr.Initialized)}catch(s){this._status=pr.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*z8)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Km.default)({},t.fallback,n,t.override,n_)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,s_.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,Km.default)({},this.client.getConfig()?.config,this.clientConfigOverride,n_);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=pr.ConfigsLoaded;let{ConfigIDs:r,Headers:n}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:r,ETag:n?.ETag})};logEvent=(t,r)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...r})}},n_=(e,t)=>{if(Array.isArray(t))return t}});var u_=b((Fre,l_)=>{"use strict";var W8=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};l_.exports=W8});var Qm=b((Mre,d_)=>{var Ws=new Proxy(function(){return Ws},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ws},apply:function(){return Ws},construct:function(){return{}}}),c_=function(){return Ws};Object.setPrototypeOf(c_,Ws);d_.exports=c_});var m_=b((Bre,f_)=>{var js=new Proxy(function(){return js},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:js},apply:function(){return js},construct:function(){return{}}}),p_=function(){return js};Object.setPrototypeOf(p_,js);f_.exports=p_});var A_=b(($re,w_)=>{"use strict";var Xm=m_(),j8={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},H8={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},K8={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},y_={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Ym={};Ym[Xm.ForwardRef]=K8;Ym[Xm.Memo]=y_;function h_(e){return Xm.isMemo(e)?y_:Ym[e.$$typeof]||j8}var J8=Object.defineProperty,Q8=Object.getOwnPropertyNames,g_=Object.getOwnPropertySymbols,X8=Object.getOwnPropertyDescriptor,Y8=Object.getPrototypeOf,v_=Object.prototype;function b_(e,t,r){if(typeof t!="string"){if(v_){var n=Y8(t);n&&n!==v_&&b_(e,n,r)}var i=Q8(t);g_&&(i=i.concat(g_(t)));for(var o=h_(e),a=h_(t),s=0;s<i.length;++s){var l=i[s];if(!H8[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=X8(t,l);try{J8(e,l,u)}catch{}}}}return e}w_.exports=b_});function C_(e,t,r){let[n,i]=(0,ua.useState)(e.getConfig(t));return(0,ua.useEffect)(()=>{if(!r?.subscribe&&e.status===pr.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function S_(e){return function(t,r){return C_(e,t,r)}}function N_(e,t,r,n){let i=o=>{let a=C_(e,t,n),s={...o,...a};return ua.default.createElement(r,{...s})};return(0,E_.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function D_(e,t,r,n){return t.reduce((i,o)=>N_(e,o,i,n),r)}function __(e){return function(t,r,n){return N_(e,t,r,n)}}var E_,ua,Zm=R(()=>{"use strict";E_=de(A_()),ua=de(Qm());zs();});var T_=b((Vre,I_)=>{var Z8=zm(),e6=jm(),t6=e6(function(e,t,r){Z8(e,t,r)});I_.exports=t6});var ac=b((Gre,P_)=>{var r6=Qi(),n6=gi(),i6="[object Symbol]";function o6(e){return typeof e=="symbol"||n6(e)&&r6(e)==i6}P_.exports=o6});var O_=b((zre,R_)=>{var a6=hi(),s6=ac(),l6=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u6=/^\w*$/;function c6(e,t){if(a6(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||s6(e)?!0:u6.test(e)||!l6.test(e)||t!=null&&e in Object(t)}R_.exports=c6});var k_=b((Wre,L_)=>{var x_=Xu(),d6="Expected a function";function eh(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(d6);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(eh.Cache||x_),r}eh.Cache=x_;L_.exports=eh});var M_=b((jre,F_)=>{var p6=k_(),f6=500;function m6(e){var t=p6(e,function(n){return r.size===f6&&r.clear(),n}),r=t.cache;return t}F_.exports=m6});var $_=b((Hre,B_)=>{var h6=M_(),g6=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v6=/\\(\\)?/g,y6=h6(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(g6,function(r,n,i,o){t.push(i?o.replace(v6,"$1"):n||r)}),t});B_.exports=y6});var q_=b((Kre,U_)=>{function b6(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}U_.exports=b6});var H_=b((Jre,j_)=>{var V_=ks(),w6=q_(),A6=hi(),E6=ac(),C6=1/0,G_=V_?V_.prototype:void 0,z_=G_?G_.toString:void 0;function W_(e){if(typeof e=="string")return e;if(A6(e))return w6(e,W_)+"";if(E6(e))return z_?z_.call(e):"";var t=e+"";return t=="0"&&1/e==-C6?"-0":t}j_.exports=W_});var J_=b((Qre,K_)=>{var S6=H_();function N6(e){return e==null?"":S6(e)}K_.exports=N6});var X_=b((Xre,Q_)=>{var D6=hi(),_6=O_(),I6=$_(),T6=J_();function P6(e,t){return D6(e)?e:_6(e,t)?[e]:I6(T6(e))}Q_.exports=P6});var Z_=b((Yre,Y_)=>{var R6=ac(),O6=1/0;function x6(e){if(typeof e=="string"||R6(e))return e;var t=e+"";return t=="0"&&1/e==-O6?"-0":t}Y_.exports=x6});var rI=b((Zre,tI)=>{var L6=Vm(),k6=X_(),F6=ec(),eI=Rn(),M6=Z_();function B6(e,t,r,n){if(!eI(e))return e;t=k6(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=M6(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=eI(c)?c:F6(t[i+1])?[]:{})}L6(s,l,u),s=s[l]}return e}tI.exports=B6});var iI=b((ene,nI)=>{var $6=rI();function U6(e,t,r){return e==null?e:$6(e,t,r)}nI.exports=U6});function lI(e){let{query:t}=(0,sI.default)(window.location.href,!0);return V6(e,t),e}function V6(e,t){let r=q6+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+uI,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,aI.default)(u,c,s)}(0,oI.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var oI,aI,sI,uI,q6,cI=R(()=>{"use strict";oI=de(T_()),aI=de(iI()),sI=de(om());uI=".",q6="ecs"+uI});function lc(e,t,r){let n=lI(new oc(e,t,r));function i(o){(0,sc.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:z6(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>D_(n,o,a,s)}}function z6(e){let t=S_(e),r=__(e);return function(i){let o=lE(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===pr.ConfigsLoaded,lm.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var G6,sc,th=R(()=>{"use strict";G6=de(u_()),sc=de(Qm());vm();Jm();zs();Zm();cI();um();});var dI=R(()=>{"use strict";vm();Jm();th();zs();Zm();Vu();cm();});function uc(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,ca.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,ca.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,ca.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var ca,rh=R(()=>{"use strict";ca=de(zi());});var wne,Ane,Ene,pI=R(()=>{"use strict";dI();rh();({featuresClient:wne,createFeature:Ane,useFeaturesClientInitParams:Ene}=lc("PowerApps-Shell-Test",uc("shell-features")))});var hI=b((Sne,mI)=>{var Hs=new Proxy(function(){return Hs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Hs},apply:function(){return Hs},construct:function(){return{}}}),fI=function(){return Hs};Object.setPrototypeOf(fI,Hs);mI.exports=fI});var W6,j6,gI=R(()=>{"use strict";Cs();W6=de(hI()),j6=de(zi());});var vI=R(()=>{"use strict";pI();rh();gI();});var xne,da,Lne,yI=R(()=>{"use strict";vI();th();({featuresClient:xne,createFeature:da,useFeaturesClientInitParams:Lne}=lc("PowerApps-MakerPortal",uc("powerapps-features")))});var bI,wI,Bne,$ne,Une,qne,nh=R(()=>{"use strict";sE();yI();({feature:bI}=da({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:Zo.enableAutoInsertionOfCellInRow}})),{feature:wI}=da({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Zo.enableOneGridEvents}}),{feature:Bne}=da({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Zo.disablePBIComponents}}),{feature:$ne}=da({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:Zo.enableAgentResponse}}),{feature:Une,useFeature:qne}=da({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Zo.enableDelayedLocalizationForCustomControls}})});var CI=b((Gne,EI)=>{var Ks=new Proxy(function(){return Ks},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ks},apply:function(){return Ks},construct:function(){return{}}}),AI=function(){return Ks};Object.setPrototypeOf(AI,Ks);EI.exports=AI});var gt,vi=R(()=>{"use strict";ze();Be();ht();Hu();te();et();gt=class extends H{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(v.colspan);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){I.IsNullOrUndefined(t)||this.setProperty(v.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(v.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}set id(t){this.setProperty(v.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(v.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(v.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}get Name(){return this.getProperty(v.Name)}set Name(t){this.setProperty(v.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(v.languagecode)===r){i.setProperty(v.description,t);return}let n=new H(A.formLabel,null);n.setProperty(v.description,t),n.setProperty(v.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(v.languagecode)===t)return r.getProperty(v.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(v.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(v.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(v.availableforphone)}set availableforphone(t){I.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(v.availableforphone,String(t))}get visible(){return this.getProcessedValue(v.visible)}set visible(t){I.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(v.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(v.showlabel)}set showlabel(t){I.IsNullOrUndefined(t)||this.setProperty(v.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return I.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(A.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(A.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.DefaultViewId):M.EmptyString}set defaultviewid(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.DependentAttributeName):M.EmptyString}set dependentattributename(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.DependentAttributeType):M.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.FilterRelationshipName):M.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.AvailableViewIds):M.EmptyString}set availableviewids(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(A.formControl);if(t&&t.ClassId){let r=je.getUniqueIdentifierForControl(t);return!I.IsNullOrUndefined(r)&&je.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(A.formControl);if(t){let n=je.getUniqueIdentifierForControl(t).guidString,i=n===U.GridControl||n===U.TimeLineControl||n===U.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===A.formSection||this.NodeName===A.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(A.formControl);if(t){let n=je.getUniqueIdentifierForControl(t).guidString,i=n===U.MapsControl||n===U.WebResourceHtmlControl||n===U.WebResourceImageControl||n===U.IframeControl||n===U.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(A.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(A.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var pa,ih=R(()=>{"use strict";ht();te();et();pa=class extends H{constructor(t,r){super(A.dependency,t),M.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(v.id,t)}get id(){return this.getProperty(v.id)}setDefaultProperties(t){this.id=t}}});var SI,fa,oh=R(()=>{"use strict";Be();ih();te();et();vi();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(SI||(SI={}));fa=class extends gt{constructor(t,r){super(A.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(v.Name,t)}get eventName(){return this.getProperty(v.Name)}set application(t){this.setProperty(v.application,t)}get application(){return this.getProperty(v.application)}set attribute(t){this.setProperty(v.EventAttribute,t)}get attribute(){return this.getProperty(v.EventAttribute)}set relationship(t){this.setProperty(v.Relationship,t)}get relationship(){return this.getProperty(v.Relationship)}set control(t){this.setProperty(v.Control,t)}get control(){return this.getProperty(v.Control)}set active(t){this.setProperty(v.EventActive,t)}get active(){return this.getProperty(v.EventActive)}getAllHandlers(){let t=this.getChildren(A.EventHandlers);return t&&t.length?t[0].getChildren(A.handler):[]}getAllDependencies(){let t=this.getChildren(A.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(A.formDependencies);if(I.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new H(A.formDependencies,this)),r=this.getFirstChild(A.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new pa(r,n.toString()))}}}});var Pr,Js=R(()=>{"use strict";ze();Es();Be();Gi();te();et();_r();Pr=class extends H{previewVersion;constructor(t){super(A.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(v.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t)}set ClassId(t){this.setProperty(v.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(v.datafieldname)}set dataFieldName(t){this.setProperty(v.datafieldname,t)}set id(t){this.setProperty(v.id,t)}get id(){return this.getProperty(v.id)}get UniqueId(){let t=this.getProperty(v.uniqueid);return I.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set UniqueId(t){this.setProperty(v.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(v.isRequired)==="true"}set isRequired(t){I.IsNullOrUndefined(t)||this.setProperty(v.isRequired,String(t))}get disableMru(){return this.getParam(v.DisableMru)==="true"}set disableMru(t){I.IsNullOrUndefined(t)||this.setParameter(v.DisableMru,t)}get useMFDForCreate(){return this.getParam(v.UseMFDForCreate)==="true"}set useMFDForCreate(t){I.IsNullOrUndefined(t)||this.setParameter(v.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(v.UseMFDForEdit)==="true"}set useMFDForEdit(t){I.IsNullOrUndefined(t)||this.setParameter(v.UseMFDForEdit,t)}get disabled(){return this.getProperty(v.disabled)==="true"}set disabled(t){I.IsNullOrUndefined(t)||this.setProperty(v.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(v.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(v.indicationOfSubgrid,String(t))}getAllParameters(){let t=new Ct,r=this.getFirstChild(v.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Pn.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(A.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new H(i,a))}else n||(a=new H(t,o),a.addChild(new H(i,a)),o.addChild(a))}else if(!n){o=new H("parameters",this);let a=new H(t,o);a.addChild(new H(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===Pn.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(v.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new Ct;switch(this.ClassId.guidString.toUpperCase()){case _.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(v.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case _.BooleanControl:case _.CheckboxControl:return 0;case _.DateTimeControl:return 2;case _.DecimalControl:return 3;case _.FloatingNumberControl:return 4;case _.IntegerControl:case _.DurationControl:case _.LanguageControl:case _.TimezoneControl:return 5;case _.LookupControl:return 6;case _.CurrencyControl:return 8;case _.PartyListControl:return 10;case _.ChoiceControl:case _.RelationshipRoleChoiceControl:return 11;case _.ChoiceStatusControl:return 13;case _.TextAreaControl:case _.TextboxControl:case _.LabelControl:case _.EmailAddressControl:case _.UrlControl:case _.TickerControl:case _.ButtonControl:case _.PhoneNumberControl:return 14;case _.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===We.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:n,ControlLayout:0,RequiredLevel:0,Type:this.getAttributeTypeFromClassId(this.ClassId.guidString),IsUnbound:this.getIsUnbound(),IsRequired:this.isRequired,DataFieldName:this.dataFieldName,UniqueId:this.UniqueId&&this.UniqueId.guidString,Id:this.previewVersion?this.id+this.previewVersion:this.id,Label:r.getDisplayName(t.langCode),LabelId:r.labelId&&r.labelId.guidString,Name:null,ShowLabel:r.showlabel,PreviewId:r&&r.id.guidString,Visible:r.visible||t.formModelService.showHiddenElements}}}});var ma,ah=R(()=>{"use strict";ht();Ho();Js();te();et();ma=class extends Pr{constructor(t){super(t)}get targetEntityType(){return this.getParam(v.targetEntityType)||M.EmptyString}set targetEntityType(t){this.setParameter(v.targetEntityType,t)}get viewId(){return M.StripBraces(this.getParam(v.viewId))||M.EmptyString}set viewId(t){this.setParameter(v.viewId,M.AddBraces(t))}get viewIds(){return this.getParam(v.viewIds)||M.EmptyString}set viewIds(t){this.setParameter(v.viewIds,t)}get relationshipName(){return this.getParam(v.RelationshipName)||M.EmptyString}set relationshipName(t){this.setParameter(v.RelationshipName,t)}get isUserView(){return M.IsStrictTrue(this.getParam(v.isUserView))}set isUserView(t){this.setParameter(v.isUserView,t.toString())}get enableViewPicker(){return M.IsStrictTrue(this.getParam(v.enableViewPicker))}set enableViewPicker(t){this.setParameter(v.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(v.autoExpand)===v.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(v.autoExpand,t?v.Auto:v.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(v.recordsPerPage)?Number(this.getParam(v.recordsPerPage)):Number(v.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(v.recordsPerPage,String(t))}get enableQuickFind(){return M.IsStrictTrue(this.getParam(v.enableQuickFind))}set enableQuickFind(t){this.setParameter(v.enableQuickFind,t)}get teamTemplateId(){return M.StripBraces(this.getParam(v.teamTemplateId))||M.EmptyString}set teamTemplateId(t){this.setParameter(v.teamTemplateId,M.AddBraces(t))}get chartId(){return this.getParam(v.visualizationId)||M.EmptyString}set chartId(t){this.setParameter(v.visualizationId,t)}get enableChartPicker(){return M.IsStrictTrue(this.getParam(v.enableChartPicker))}set enableChartPicker(t){this.setParameter(v.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(v.chartGridMode)){case dr.Chart:return dr.Chart;case dr.Grid:return dr.Grid;default:return dr.All}}set chartGridMode(t){this.setParameter(v.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=dr.Chart:this.chartGridMode=this.enableChartPicker?dr.All:dr.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case v.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case v.viewId:n.getAllChildren()[0].setNodeName("<"+M.AddBraces(r.viewId));break;case v.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case v.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case v.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new H(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(St.dataset)?n[i].getParameters().get(St.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var ha,sh=R(()=>{"use strict";ht();Ho();Js();te();ha=class extends Pr{constructor(t){super(t)}get defaultViewId(){return M.StripBraces(this.getParam(v.DefaultViewId))||M.EmptyString}set defaultViewId(t){this.setParameter(v.DefaultViewId,M.AddBraces(t))}get autoResolve(){return M.IsStrictTrue(this.getParam(v.AutoResolve))}set autoResolve(t){this.setParameter(v.AutoResolve,t)}get disableQuickFind(){return M.IsStrictTrue(this.getParam(v.DisableQuickFind))}set disableQuickFind(t){this.setParameter(v.DisableQuickFind,t)}get disableViewPicker(){return M.IsStrictTrue(this.getParam(v.DisableViewPicker))}set disableViewPicker(t){this.setParameter(v.DisableViewPicker,t)}get allowFilterOff(){return M.IsStrictTrue(this.getParam(v.AllowFilterOff))}set allowFilterOff(t){this.setParameter(v.AllowFilterOff,t)}get disableMru(){return M.IsStrictTrue(this.getParam(v.DisableMru))}set disableMru(t){this.setParameter(v.DisableMru,t)}get dependentAttributeName(){return this.getParam(v.DependentAttributeName)||M.EmptyString}set dependentAttributeName(t){this.setParameter(v.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(v.DependentAttributeType)||M.EmptyString}set dependentAttributeType(t){this.setParameter(v.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(v.FilterRelationshipName)||M.EmptyString}set filterRelationshipName(t){this.setParameter(v.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(v.AvailableViewIds)||M.EmptyString}set availableViewIds(t){this.setParameter(v.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case v.datafieldname:case v.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case v.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+M.AddBraces(r.defaultViewId));break;case v.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case v.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case v.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case v.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case v.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case v.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case v.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case v.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case v.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(St.value)?n[i].getParameters().get(St.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var NI,lh,qt,Qs=R(()=>{"use strict";NI=de(CI());vi();te();Be();ze();oh();Js();Hu();hm();Hf();_r();Gi();zo();ah();sh();uh();Is();lh="_",qt=class e extends gt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(A.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,I.IsNullOrUndefined(this.getProperty(v.id))&&(this.id=new L(L.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof Pr?this.addChild(n):n instanceof L&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!I.IsNullOrUndefined(this.control))return I.IsNullOrUndefined(this.control.dataFieldName)?I.IsNullOrUndefined(this.control.id)?!0:!Wi.dependencyFieldCount.containsKey(this.control.id):!Wi.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new fa(this,ws.onLoad))}get dependencies(){let t=this.getChildren(A.formEvents);for(let r of t){let n=r.getChildren(A.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&xu[i])o=xu[i].replace(/ /g,lh)+lh;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,NI.trackErrorTrace)(Et,{eventName:`${bA}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,v.isUnbound,"true"),e.prototype.setProperty.call(t,v.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===fr.Grid?(l=new ma(this),l.indicationOfSubgrid=!0):o===fr.Lookup?l=new ha(this):l=new Pr(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,v.id,c),l.ClassId=n,!I.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=je.getUniqueIdentifierForControl(l);I.IsNullOrUndefined(d)||(je.getControlDataTypeByControlOrUniqueId(d)===j.QuickFormCollectionControl||!je.isUnboundFormControlByIdentifier(d)?o!==fr.Grid&&a&&u!==_.IframeControl&&u!==_.SubgridControl&&u!==_.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,v.disabled,"false")):(this.rowspan=je.GetRowSpan(l),(je.getControlDataTypeByControlOrUniqueId(d)===j.NotesControl||je.getControlDataTypeByControlOrUniqueId(d)===j.TimeLineControl)&&(e.prototype.setProperty.call(l,v.disabled,"false"),l.id=j.NotesControl)),(je.getUnboundControlNameFromIdentifier(n)===j.SubGridControl||je.getUnboundControlNameFromIdentifier(n)===j.NotesControl||je.getUnboundControlNameFromIdentifier(n)===j.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(I.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(v.id);a.getNodeName()===A.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(A.formControl)}set rowspan(t){this.setProperty(v.rowspan,String(t))}get rowspan(){let t=this.getProperty(v.rowspan);return I.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(v.auto,String(t))}get autoexpand(){return this.getProperty(v.auto)==="true"}set colspan(t){let r=Number(fm.ONE_COLUMN),n=Number(fm.FOUR_COLUMN);I.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(v.colspan,String(t))}get colspan(){let t=this.getProperty(v.colspan);return I.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(A.formRow)}getParentSection(){return this.getAncestor(A.formSection)}getParentTab(){return this.getAncestor(A.formTab)}getParentForm(){return this.getAncestor(A.form)}isInHeader(){let t=this.getAncestor(A.formHeader);return!I.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(A.formFooter);return!I.IsNullOrUndefined(t)}isEmpty(){return I.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(A.formHeader):this.isInFooter()?this.getAncestor(A.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(v.userspacer);return I.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(v.userspacer,"true")}ClearUserSpacer(){this.setProperty(v.userspacer,"false")}get columns(){let t=this.getProperty(v.columnName);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!I.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();I.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===Hi.ApplicationRequired||a===Hi.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Hi.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Hi.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===A.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===A.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===lh&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var ga,ch=R(()=>{"use strict";ht();te();et();ga=class extends H{isInternal;constructor(t,r,n,i){super(A.library,t),this.isInternal=!!i,M.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(v.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(v.libraryUniqueId,t)}get name(){return this.getProperty(v.libraryName)}set name(t){this.setProperty(v.libraryName,t)}get displayName(){return this.getProperty(v.displayName)}set displayName(t){this.setProperty(v.displayName,t)}get description(){return this.getProperty(v.description)}set description(t){this.setProperty(v.description,t)}}});var Yi,dh=R(()=>{"use strict";Be();Qs();te();et();Yi=class extends H{isRowAddedOnDragOver;constructor(t){super(A.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return I.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return I.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(A.formSection)}insertPaddingCellAtIndex(t){let r=new qt(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(A.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function H6(e){switch(e){case Ki.Left:return Ji.Left;case Ki.Right:return Ji.Right;case Ki.Center:return Ji.Center;default:return Ji.Left}}function K6(e){switch(e){case Qo.Left:return Yo.Left;case Qo.Top:return Yo.Top;default:return Yo.Left}}function DI(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var J6,nn,Xs=R(()=>{"use strict";gm();ze();Be();ht();nh();Qs();te();_r();vi();dh();J6=115,nn=class e extends gt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Te.ONE_COLUMN;break;case 11:t=Te.TWO_COLUMN;break;case 111:t=Te.THREE_COLUMN;break;case 1111:t=Te.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=De.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+De.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(v.Name,r)}initializeDefaultProperties(t,r,n){if(n===Te.REFERENCE_PANEL){this.addProperty(v.rowheight,"25");let i=`${De.referencePanelNamePrefix}${L.NewGuid()}${De.namePrefix}`;this.addProperty(v.Name,i)}else this.setUniqueName();if(this.addProperty(v.id,new L(L.NewGuid()).guidString),this.addProperty(v.IsUserDefined,De.IsUserDefined),this.addProperty(v.locklevel,De.LockLevel),this.addProperty(v.showlabel,De.ShowLabel),this.addProperty(v.showbar,De.ShowBar),this.addProperty(v.layout,De.Layout),this.addProperty(v.Fieldlabelalignment,De.labelAlignment),this.addProperty(v.Fieldlabelposition,De.labelPosition),I.IsNullOrUndefined(n))this.addProperty(v.columnName,De.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(v.columnName,i)}this.addProperty(v.LabelWidth,De.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return I.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(M.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Yi(null);if(this.addGrandChild(A.formRows,r),bI.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new qt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Te.REFERENCE_PANEL&&(n=Te.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(A.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(A.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(A.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(A.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(A.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(A.formRows);return t.length===0?[]:t[0].getChildren(A.formRow)}get columns(){let t=this.getProperty(v.columnName),r=I.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return DI(n)}return r}set columns(t){I.IsNullOrUndefined(t)||this.setProperty(v.columnName,String(t))}get rowHeight(){let t=this.getProperty(v.rowheight);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(v.rowheight,String(t))}set autoexpand(t){this.setProperty(v.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(v.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(v.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(v.IsUserDefined,"1"):this.setProperty(v.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(A.formColumn)}getParentTab(){return this.getAncestor(A.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(v.showlabel)==="true"}set showlabel(t){I.IsNullOrUndefined(t)||this.setProperty(v.showlabel,String(t))}get fieldLabelAlignment(){let t=De.labelAlignment,r=this.getProperty(v.Fieldlabelalignment);return I.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){I.IsNullOrUndefined(t)||this.setProperty(v.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(v.Fieldlabelposition);return I.IsNullOrUndefined(t)?De.labelPosition:t}set fieldLabelPosition(t){I.IsNullOrUndefined(t)||this.setProperty(v.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(v.showbar)==="true"}set showbar(t){I.IsNullOrUndefined(t)||this.setProperty(v.showbar,String(t))}get labelwidth(){let t=+this.getProperty(v.LabelWidth);return t===0?J6:t}set labelwidth(t){I.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(v.LabelWidth,t.toString())}async getRowsJSON(t){let r=[],n=[];if(this.rows){for(let i of this.rows)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this.id&&this.id.guidString,Rows:await this.getRowsJSON(t),CellLabel:{Width:this.labelwidth,Alignment:H6(this.fieldLabelAlignment),Position:K6(this.fieldLabelPosition)},Columns:DI(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===A.formSection){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!I.IsNullOrUndefined(this)&&!I.IsNullOrUndefined(this.Name)&&this.Name.indexOf(De.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===A.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===A.formFooter||this.NodeName===A.formHeader}}});var yi,cc=R(()=>{"use strict";te();et();Xs();yi=class e extends H{constructor(t){super(A.formColumn,t)}initializeDefaultProperties(t){this.addProperty(v.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(A.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new nn(A.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(A.formSections,t,r)}initialize(t,r,n,i=Te.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(A.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(A.formSection)}get width(){return this.getProperty(v.width)}set width(t){this.setProperty(v.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(A.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(v.Name),Id:this.getProperty(v.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(v.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var dc,_I=R(()=>{"use strict";ze();te();_r();Xs();dc=class extends nn{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(v.Name,n),this.addProperty(v.id,new L(L.NewGuid()).guidString),this.addProperty(v.columnName,De.columns),this.setDisplayName(r,t)}}});var pc,II=R(()=>{"use strict";cc();te();_I();pc=class extends yi{addAndIntializeNavBarSection(t,r,n,i){let o=new dc(A.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(A.formSections,o,n),o}}});var On,fc=R(()=>{"use strict";ze();Be();ht();cc();te();et();vi();On=class extends gt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(A.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(A.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ie.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ie.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ie.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ie.TWO_COLUMN_WIDER_RIGHT;break}t=Ie.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=Ie.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=Ie.THREE_COLUMN_WIDER_MID;break}t=Ie.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(v.Name,di.namePrefix+t.toString()),this.addProperty(v.id,new L(L.NewGuid()).guidString),this.addProperty(v.IsUserDefined,di.IsUserDefined),this.addProperty(v.locklevel,di.LockLevel),this.addProperty(v.showlabel,di.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=Te.ONE_COLUMN,o=!0,a){let s=this.getChildren(A.formColumns)[0],l=[];switch(t){case Ie.ONE_COLUMN:l.push(100);break;case Ie.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ie.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ie.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ie.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ie.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new yi(s);c.initialize(u,r,n,i),this.addGrandChild(A.formColumns,c)}}initialize(t,r,n,i,o,a=Te.ONE_COLUMN,s=!0,l){this.addChild(new H(A.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(A.formColumns);return t.length!==1?[]:t[0].getChildren(A.formColumn)}get expanded(){return this.getProcessedValue(v.expanded)}set expanded(t){I.IsNullOrUndefined(t)||this.setProperty(v.expanded,String(t))}get groupName(){return this.getProperty(v.groupName)}get contentType(){return this.getProperty(v.contentType)}set contentType(t){this.setProperty(v.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(A.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(A.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(A.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===A.formTab){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Zi,ph=R(()=>{"use strict";ze();te();et();_r();II();fc();Zi=class extends On{constructor(t,r,n){super(t,Ie.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new L(L.NewGuid())}initializeDefaultProps(){this.addChild(new H(A.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(A.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<Wu.FIVE_COLUMN;t++){let r=new pc(this.getChildren(A.formColumns)[0]);r.initializeDefaultProperties(JA.FiveEqColumn),this.addGrandChild(A.formColumns,r)}}}});function X6(e){switch(e){case We.Main:return fi.Main;case We.QuickCreate:return fi.QuickCreate;case We.QuickViewForm:return fi.Quick;case We.Dialog:return fi.Dialog;default:return fi.None}}function Y6(e,t){if(t===We.Main){if(e)switch(e.toLowerCase()){case"low":return ci.Low;case"highreadonlyvalues":return ci.HighReadOnlyValues;default:return ci.HighWithControls}return ci.Low}}var hc,Q6,mc,TI=R(()=>{"use strict";rE();hc=de(zi());gm();Be();ht();zo();nh();te();Ho();Lf();Gi();Qs();te();vi();ch();ph();fc();Q6="1920";mc=class e extends gt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(A.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Tu,this._metadataChangeEvent=new Ku}get FormLibraries(){let t=this.getFirstChild(A.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof qt).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof qt){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===A.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new ga(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,hc.trackErrorTrace)(wA,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:n.attribute,EventName:n.eventName}}),i}}),r}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return M.IsNullOrEmpty(this.getProperty(v.ShowImage))?!0:this.getProperty(v.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(v.ShowImage,String(t)):this.setProperty(v.ShowImage,"false")}get ShowNavigation(){return M.IsNullOrEmpty(this.getProperty(v.ShowNavigationbar))?!0:this.getProperty(v.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(v.ShowNavigationbar,String(t)):this.setProperty(v.ShowNavigationbar,"false")}get MaxWidth(){return M.IsNullOrEmpty(this.getProperty(v.MaxWidth))?Q6:this.getProperty(v.MaxWidth)}set MaxWidth(t){this.setProperty(v.MaxWidth,t)}get headerDensityType(){return this.getProperty(v.HeaderDensityType)}set headerDensityType(t){t&&this.formType===We.Main?this.setProperty(v.HeaderDensityType,t):this.formType!==We.Main&&this.headerDensityType&&this.removeProperty(v.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===We.Main||this.formType===We.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(A.formHeader);return t.length!==1?null:t[0]}set header(t){I.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(A.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(A.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return I.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(A.formFooter);return t.length!==1?null:t[0]}set footer(t){I.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new On(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(A.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new On(null,Ie.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Ie.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(A.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===di.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(A.formTabs);return t.length!==1?[]:t[0].getChildren(A.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Zi)return t}return null}get NavigationNode(){let t=this.getChildren(A.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(A.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(A.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(A.formTabs);if(!I.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(A.formFooter).length>0}get displayCondition(){let t=this.getChildren(A.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(A.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(A.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(A.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);I.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(A.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof qt))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof qt&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==_.CustomControl?!1:this.cellHasCustomControlWithName(t,pi.EditableGridControl)||wI.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,pi.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===_.CustomControl&&this.cellHasCustomControlWithName(t,pi.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===A.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof Zi)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,hc.getSessionId)(),EntityLogicalName:this._entityName,FormId:this._formId.guidString,TabAttributes:{},Tabs:await this.getTabsJSON(t),HiddenFields:[],Header:this.header&&await this.header.toJSON(t),Footer:this.footer&&await this.footer.toJSON(t),...this.formType===We.Main?{HeaderDensity:Y6(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:X6(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:r,BusinessLogic:void 0,FormLibraries:[],Navigation:n,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var gc,fh,PI=R(()=>{"use strict";ze();Be();te();et();vi();gc=class extends gt{constructor(t){super(A.formDisplayConditions,t)}get Order(){let t=this.getProperty(v.Order);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(v.Order,t.toString())}get FallbackForm(){return this.getProperty(v.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(v.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(A.formEveryOne)&&this.getChildren(A.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new fh(this))}},fh=class extends H{constructor(t){super(A.formEveryOne,t)}}});var vc,RI=R(()=>{"use strict";te();et();vc=class extends H{constructor(t,r){super(A.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(v.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(v.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(v.functionName)}set FunctionName(t){this.setProperty(v.functionName,t)}get LibraryName(){return this.getProperty(v.libraryNameEventHandler)}set LibraryName(t){this.setProperty(v.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(v.enabledForField)}set Enabled(t){this.setProperty(v.enabledForField,t)}get PassExecutionContext(){return this.getProperty(v.passExecutionContext)}set PassExecutionContext(t){this.setProperty(v.passExecutionContext,t)}get Parameters(){return this.getProperty(v.parameters)}set Parameters(t){this.setProperty(v.parameters,t)}}});var va,mh=R(()=>{"use strict";te();Xs();va=class extends nn{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(A.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var Ys,OI=R(()=>{"use strict";te();mh();Ys=class extends va{_customFooter;constructor(t,r){super(A.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var Zs,xI=R(()=>{"use strict";te();mh();Zs=class extends va{_customHeader;constructor(t,r){super(A.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(v.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(v.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(v.showBody)}set showBody(t){t!=null&&this.setProperty(v.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(v.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(v.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var Vt,eo=R(()=>{"use strict";ze();ht();te();vi();Vt=class e extends gt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(v.LCID)===t)return r.getProperty(v.text);return null}getAllTitles(){let t=this.getChildren(A.Titles);return t.length===0?[]:t[0].getChildren(A.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(v.LCID)===r){i.setProperty(v.text,t);return}let n=new e(A.Title,null);n.setProperty(v.text,t),n.setProperty(v.LCID,String(r)),this.addGrandChild(A.Titles,n)}get Sequence(){return+this.getProperty(v.Sequence)}set Sequence(t){this.setProperty(v.Sequence,t.toString())}get Area(){return this.getProperty(v.Area)}set Area(t){this.setProperty(v.Area,t)}set Id(t){this.setProperty(v.Id,t)}get Id(){return this.getProperty(v.Id)}get id(){return new L(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(v.icon)}set Icon(t){t=t||M.EmptyString,this.setProperty(v.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var el,LI=R(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(el||(el={}))});var yc,kI=R(()=>{"use strict";Be();te();eo();LI();yc=class extends Vt{constructor(t){super(A.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return I.IsNullOrUndefined(r)?el.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):el.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var Se,Z6,FI,Oae,ya,hh=R(()=>{"use strict";ze();te();eo();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(Se||(Se={}));Z6=new Map([[Se.Info,"Info"],[Se.Sales,"Sales"],[Se.Service,"Service"],[Se.Marketing,"Marketing"],[Se.ProcessCenter,"ProcessCenter"]]),FI=new Map([["Info",Se.Info],["Sales",Se.Sales],["Service",Se.Service],["Marketing",Se.Marketing],["ProcessCenter",Se.ProcessCenter]]),Oae=new Map([[Se.Info,9e3],[Se.Sales,9200],[Se.Service,9400],[Se.Marketing,9600],[Se.ProcessCenter,9800],[Se.InternetMarketing,1e4],[Se.Async,10200]]),ya=class extends Vt{constructor(t,r){super(A.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=Z6.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(A.formNavigation)}get AreaId(){return this.getProperty(v.Id)}set AreaId(t){this.setProperty(v.Id,t)}get id(){return new L(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var ba,gh=R(()=>{"use strict";te();eo();ba=class extends Vt{constructor(t,r){super(A.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(A.formNavBarArea)}get ParentNavigation(){return this.getAncestor(A.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var bc,MI=R(()=>{"use strict";Be();te();eo();bc=class extends Vt{RelationshipNameUCIRuntime;constructor(t){super(A.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(v.RelationshipName)}set RelationshipName(t){this.setProperty(v.RelationshipName,t)}set Show(t){this.setProperty(v.Show,String(t))}get Show(){let t=this.getProperty(v.Show);return I.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(v.TitleResourceId)}async toJSON(t){return{Area:this.Area,Show:this.Show||t.formModelService.showHiddenElements,Id:this.Id,Titles:[{Name:t.langCode.toString(),Value:this.getTitle(t.langCode)}],Sequence:this.Sequence.toString(),Privileges:[],TooltipTitles:[],AvailableOffline:!0,PreviewId:this.Id,RelationshipName:this.RelationshipNameUCIRuntime??this.RelationshipName,Icon:null,ViewId:null,Client:null,TitleResourceId:null}}}});var wc,BI=R(()=>{"use strict";te();eo();wc=class extends Vt{constructor(t){super(A.formNavBarItem,t)}get Url(){return this.getProperty(v.url)}set Url(t){this.setProperty(v.url,t)}}});var Ac,$I=R(()=>{"use strict";ze();te();hh();gh();eo();Ac=class extends Vt{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(A.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Se.Info,Se.Sales,Se.Service,Se.Marketing,Se.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>FI.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new ba(A.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new ya(A.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(A.formNavBar)}get id(){return new L(jf,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(A.formNavBarAreas,r),this.addGrandChildAtIndex(A.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var UI={};gn(UI,{ControlType:()=>fr,DeserializationService:()=>bh,DeserializationServiceScope:()=>yh,DeserializedFormElementNode:()=>Gt});var vh,Gt,yh,fr,bh,uh=R(()=>{"use strict";vh=de(zi());ze();Be();ht();zo();Hf();Gi();AA();tE();Hu();TI();Qs();cc();Js();ih();te();te();PI();et();_r();oh();RI();OI();ah();sh();xI();ch();dh();Xs();fc();kI();hh();gh();MI();BI();$I();Gt=class extends H{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},yh="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(fr||(fr={}));bh=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let f="";throw d.length===0?f="FormXml has no form node.":f="FormXml has multiple form nodes.",(0,vh.trackErrorTrace)(Et,{eventName:yh,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return I.IsNullOrUndefined(p.displayCondition)&&s!==We.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Wi.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!I.IsNullOrUndefined(t)){let n=I.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new mc(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===We.Main&&(this.insertHeaderFooterElementProperties(A.formHeader,d,d.header),this.insertHeaderFooterElementProperties(A.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(I.IsNullOrUndefined(n)){let i=t===A.formHeader?new Zs(r,!0):new Ys(r,!0);Gt.prototype.insertProperty.call(i,v.id,"{"+L.NewGuid()+"}"),Gt.prototype.insertProperty.call(i,v.Fieldlabelposition,"Top"),Gt.prototype.insertProperty.call(i,v.columnName,De.MarginalControlColumns),Gt.prototype.insertProperty.call(i,v.LabelWidth,De.LabelWidth),Gt.prototype.insertProperty.call(i,v.Fieldlabelalignment,"Left");let o=null,a=new Yi(o);for(let s=0;s<i.maxColumns;s++){let l=new qt(a);Gt.prototype.insertProperty.call(l,v.id,"{"+L.NewGuid()+"}"),l.setDisplayName(M.EmptyString,this.lcid),Gt.prototype.insertProperty.call(l,v.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===A.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new Gt(`<${t.nodeValue}`,r);if(t.nodeType===Node.COMMENT_NODE)return;let n=this.createModelNode(t,r);return this.populateElementProperties(n,t.attributes),this.populateElementChildren(n,t.childNodes),n}populateElementProperties(t,r){if(!r){let n="attributes is undefined for element: "+t.getNodeName();throw(0,vh.trackErrorTrace)(Et,{eventName:yh,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Gt.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===A.formCell&&i.name===v.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Gt.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case A.form:throw new Error("Form node shouldn't be created using this method");case A.formTab:return new On(r);case A.formColumn:return new yi(r);case A.formHeader:return new Zs(r,!1);case A.formFooter:return new Ys(r,!1);case A.formSection:return new nn(A.formSection,r);case A.formRow:return new Yi(r);case A.formCell:return new qt(r);case A.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===v.indicationOfSubgrid&&l.value==="true"||l.name===v.classid&&(l.value?.toLocaleUpperCase()===`{${_.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${_.ReferencePanelSubgridControl}}`))o=fr.Grid;else if(l.name===v.classid&&l.value?.toLocaleUpperCase()===`{${_.LookupControl}}`)o=fr.Lookup;else if(l.name===v.classid&&l.value?.toLocaleUpperCase()===`{${_.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===v.DefaultViewId&&(o=fr.Lookup)}return o===fr.Grid?new ma(r):o===fr.Lookup?new ha(r):new Pr(r);case A.formEvent:return new fa(r,M.EmptyString);case A.dependency:return this.populateDependencyTable(t),new pa(r,M.EmptyString);case A.Handler:let a=[];return new vc(a,r);case A.formNavigation:return new Ac(t.nodeName,r);case A.formNavBarArea:return new ya(t.nodeName,r);case A.formNavBarAreas:return new ba(t.nodeName,r);case A.formNavBar:return new yc(r);case A.formNavBarByRelationshipItem:return new bc(r);case A.formNavBarItem:return new wc(r);case A.formDisplayConditions:return new gc(r);case A.library:return new ga(r,M.EmptyString,M.EmptyString);case A.controlDescription:return new Lu(r);case A.customControl:return this.populateCustomControlConfigurationId(t),new ju(r);default:return new Gt(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===v.id&&this.upsertFieldCount(i.value,Zr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===v.id){let o=new L(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===v.ForControl){let l=s.value.substr(1,i.value.length-2);je.CustomControlIdMap.upsert(l,o);break}}break}}}}});var qI={};gn(qI,{SerializationService:()=>wh,SerializationServiceScope:()=>ez,SerializedFormElementNode:()=>wa});var ez,wa,wh,VI=R(()=>{"use strict";ht();et();_r();ph();ez="SerializationService",wa=class extends H{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},wh=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=wa.prototype.fetchNodeName.call(t);if(r.charAt(0)===Pn.StartTag)return M.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return M.EmptyString;let n=wa.prototype.enumerateProperties.call(t),i=wa.prototype.enumerateChildren.call(t);if(!(t instanceof Zi)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=M.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return M.EmptyString}getPropertiesString(t){let r=M.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${M.EscapeXml(n.value,!0)}"`}),r}}});var Sh=b(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.completeRecordAsStored=Aa.completeLabelsAsStored=void 0;var Ah=oi(),tz="E7A81278-8635-4D9E-8D4D-59480B391C5B",rz=new Set(["tab","section","cell"]);function Rr(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function bi(e,t){return Rr(e).find(r=>r.tagName===t)}function zI(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Eh(e){let t=bi(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===tz:!1}function Ch(e,t){var r,n;let i=((r=bi(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=bi(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function nz(e,t){if(bi(e,"labels"))return;let r=Rr(e),n=Rr(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!zI(r,n.slice(1)))return;let o=Rr(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Eh(e)&&Ch(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function iz(e,t){let r=oz(e.ownerDocument,t),n=Rr(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function oz(e,t){let r=e.createElement("labels");for(let n of Rr(t))r.appendChild(WI(e,n));return r}function WI(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function GI(e,t){let r=bi(e,"labels");return r?Rr(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function az(e,t,r){if(e.tagName!=="cell"||!Eh(e)||!Ch(e,t))return!1;let n=GI(e,r),i=GI(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function sz(e,t){if(e.tagName!=="cell"||!Eh(e)||!Ch(e,t))return;let r=bi(e,"labels"),n=bi(t,"labels");if(!r||!n)return;let i=Rr(r),o=Rr(n),a=p=>p.tagName==="label"&&p.hasAttribute("description")&&p.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(p=>[p.getAttribute("languagecode")||"",p]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let p of o){let f=p.getAttribute("languagecode")||"";if(l.has(f))return;l.add(f);let m=s.get(f);if(!m){d.push(p);continue}if((m.getAttribute("description")||"")!==(p.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(p=>({label:p}))),u===i.length?c:void 0}function jI(e,t,r,n){if(e.tagName!==t.tagName)return;if(rz.has(e.tagName)){let a=nz(e,t);a&&(iz(e,a),n.changed=!0),az(e,t,r)&&(n.changed=!0);let s=sz(e,t),l=bi(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=WI(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Rr(e),o=Rr(t);zI(i,o)&&i.forEach((a,s)=>jI(a,o[s],r,n))}function HI(e,t,r){let n,i;try{n=(0,Ah.parseXmlRoot)(e,""),i=(0,Ah.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return jI(n,i,r,o),o.changed?(0,Ah.serializeNode)(n):e}Aa.completeLabelsAsStored=HI;function lz(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=HI(n,i,r);return o===n?e:{...e,formxml:o}}Aa.completeRecordAsStored=lz});var cT=b(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.classIdForAttributeType=Wt.QUICK_VIEW_CLASS_ID=Wt.NOTES_CLASS_ID=Wt.SUBGRID_CLASS_ID=Wt.formRegistration=Wt.FormAdapter=void 0;var xn=(ze(),$r(pA)),uz=(Be(),$r(fA)),cz=(et(),$r(hA)),tt=(te(),$r(mA)),$e=(Gi(),$r(gA)),dz=(uh(),$r(UI)),pz=(VI(),$r(qI)),He=ri(),KI=nr(),zt=Nr(),fz=mf(),Ea=lt(),mz=Sh(),vt=af(),JI=re(),Ih=ae(),Th=ii(),rT=Li(),hz={[tt.FormType.Main]:"Main",[tt.FormType.QuickCreate]:"QuickCreate",[tt.FormType.QuickViewForm]:"QuickView",[tt.FormType.Card]:"Card"},Ec={Main:tt.FormType.Main,QuickCreate:tt.FormType.QuickCreate,QuickView:tt.FormType.QuickViewForm,Card:tt.FormType.Card},gz=new Map(Object.entries($e.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function nT(e){var t;return e&&(t=gz.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function tl(e){return e.getAllProperties().map(t=>[t.key,t.value])}function to(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function iT(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Ph(e,t){var r,n;let i=iT(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>to(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=to(a).get("description"))!==null&&n!==void 0?n:""}function vz(e){let t=iT(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function oT(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Nh(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function rl(e){return String(e??"").replace(/[{}]/g,"")}function Dh(e){return`{${rl(e)}}`}function QI(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Sc(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,He.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:tl(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,He.rawFromNode)(u)})}),{modeled:s,bag:{a:tl(e),c:o,w:{n:a.getNodeName(),a:tl(a),c:l}}}}function aT(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,He.rawFromNode)(o)})}),{modeled:n,bag:{a:tl(e),c:i}}}function XI(e,t){let{modeled:r,bag:n}=Sc(e,"tabs","tab");return{tabs:r.map(i=>yz(i,t)),bag:n}}function yz(e,t){var r,n;let i=to(e),{modeled:o,bag:a}=Sc(e,"columns","column");return{id:(r=i.get("id"))!==null&&r!==void 0?r:"",name:(n=i.get("name"))!==null&&n!==void 0?n:"",label:Ph(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>bz(s,t)),bag:a}}function bz(e,t){let r=to(e),{modeled:n,bag:i}=Sc(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>wz(o,t)),bag:i}}function wz(e,t){var r,n,i;let o=to(e),{modeled:a,bag:s}=Sc(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Ph(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:oT((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>Az(l,t)),bag:s}}function Az(e,t){let{modeled:r,bag:n}=aT(e,"cell",!1);return{cells:r.map(i=>Ez(i,t)),bag:n}}function Ez(e,t){var r;let n=to(e),{modeled:i,bag:o}=aT(e,"control",!0),a=Ph(e,t),s=n.get("showlabel")==="true",l=i[0]?Cz(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:QI(n.get("colspan"),1),rowspan:QI(n.get("rowspan"),1),control:l,bag:o}}function Cz(e,t,r){var n,i;let o=to(e),a=rl((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:nT(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:vz(e),bag:{a:tl(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,He.rawFromNode)(l)}))}}}function Ei(e){return e.a.length===0&&e.c.length===0&&!e.w}function sT(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ro(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Ei(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=sT(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,He.mergeAttrs)(e.a,o)}var wi=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Ai=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),YI=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function Rh(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function _h(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,Ih.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function Sz(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function Nz(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function Oh(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Ei(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:Rh(t,r)},...a]}}if(Sz(e.c[n].node,r)===t)return e;let i=Nz(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function Dz(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function _z(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function Iz(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function Tz(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Ei(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:_h(t)}]}}if(_z(Dz(e.c[r].node),t))return e;let n=_h(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Nc(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,He.spliceChildren)(e.w.c,r)};return(0,He.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,He.spliceChildren)(e.c,[...i,o])}function Pz(e,t){let r=e.tabs.map(n=>Rz(n,t));return{n:"form",a:ro(e.bag,[]),c:e.tabs.length===0&&Ei(e.bag)?[]:Nc(e.bag,"tabs",r,()=>[])}}function lT(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Rh(t,r)]:[]}function Rz(e,t){let r=[wi("id",e.id),wi("name",e.name),Ai("expanded",e.expanded),Ai("visible",e.visible,!0)],n=e.columns.map(o=>Oz(o,t)),i=Oh(e.bag,e.label,t);return{n:"tab",a:ro(i,r),c:Nc(i,"columns",n,()=>lT(i,e.label,t))}}function Oz(e,t){let r=e.width!==void 0?[wi("width",e.width)]:[],n=e.sections.map(i=>xz(i,t));return{n:"column",a:ro(e.bag,r),c:Nc(e.bag,"sections",n,()=>[])}}function xz(e,t){let r=[wi("id",e.id),wi("name",e.name),Ai("showlabel",e.showLabel),Ai("visible",e.visible,!0),{key:"columns",matches:o=>oT(o)===e.columns,render:()=>Nh(e.columns),absentDefault:Nh(1)}],n=e.rows.map(o=>Lz(o,t)),i=Oh(e.bag,e.label,t);return{n:"section",a:ro(i,r),c:Nc(i,"rows",n,()=>lT(i,e.label,t))}}function Lz(e,t){let r=e.cells.map(n=>kz(n,t));return{n:"row",a:ro(e.bag,[]),c:Ei(e.bag)?r:(0,He.assembleChildren)(e.bag,r)}}function kz(e,t){let r=e.control?e.control.showLabel:sT(e.bag,"showlabel")==="true",n=[wi("id",e.id),Ai("showlabel",r),Ai("visible",e.visible,!0),YI("colspan",e.colspan),YI("rowspan",e.rowspan)],i=e.control?[Fz(e.control)]:[],o;if(Ei(e.bag))o=[...e.control&&e.control.label?[Rh(e.control.label,t)]:[],...i];else{let a=e.control?Oh(e.bag,e.control.label,t):e.bag;o=(0,He.assembleChildren)(a,i)}return{n:"cell",a:ro(e.bag,n),c:o}}function Fz(e){let t=[wi("id",e.id),{key:"classid",matches:i=>rl(i)===e.classId,render:()=>Dh(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(wi("datafieldname",e.fieldName)),t.push(Ai("disabled",e.isReadOnly)),t.push(Ai("isrequired",e.isRequired));let r=e.fieldName===null?Iz(e.bag,"datafieldname"):e.bag,n;return Ei(r)?n=Object.keys(e.parameters).length>0?[_h(e.parameters)]:[]:n=(0,He.assembleChildren)(Tz(r,e.parameters),[]),{n:"control",a:ro(r,t),c:n}}var Mz={make:(e,t)=>new cz.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function ZI(e,t,r,n){(0,Th.installDomShim)();let i=$z(e,r);(0,vt.reconcileEmbedDescriptions)(i,n);let o=(0,He.rebuildRaw)(Pz(i,t),Mz,null);return new pz.SerializationService(t).serializeFormXmlNode(o)}function Bz(e){return JSON.parse(JSON.stringify(e))}function $z(e,t){var r;let n=Bz(e);n.bag||(n.bag=(0,He.emptyBag)()),Hz(n.bag),t&&Uz(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])qz(i);return n}function Uz(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";xh(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=uT(s.attributeType)))})}function eT(e){let t=[];return xh(e,r=>t.push(r)),t}function xh(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function qz(e){e.id||(e.id=xn.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.expanded===void 0&&(e.expanded=!0),e.visible===void 0&&(e.visible=!0),e.columns||(e.columns=[]);for(let t of e.columns)Vz(t);e.bag||(e.bag=(0,He.emptyBag)())}function Vz(e){e.sections||(e.sections=[]);for(let t of e.sections)Gz(t);e.bag||(e.bag=(0,He.emptyBag)()),e.width===void 0&&Ei(e.bag)&&(e.width="100%")}function Gz(e){e.id||(e.id=xn.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.showLabel===void 0&&(e.showLabel=!1),e.visible===void 0&&(e.visible=!0),e.columns===void 0&&(e.columns=1),e.rows||(e.rows=[]);for(let t of e.rows)zz(t);e.bag||(e.bag=(0,He.emptyBag)())}function zz(e){e.cells||(e.cells=[]);for(let t of e.cells)Wz(t);e.bag||(e.bag=(0,He.emptyBag)())}function Wz(e){(0,vt.hasGenPage)(e.control)&&(0,vt.applyEmbedCellDefaults)(e),e.id||(e.id=xn.Guid.NewGuid()),e.visible===void 0&&(e.visible=!0),e.colspan===void 0&&(e.colspan=1),e.rowspan===void 0&&(e.rowspan=1),e.control===void 0&&(e.control=null),e.control&&jz(e.control),e.bag||(e.bag=(0,He.emptyBag)())}function jz(e){var t;(0,vt.hasGenPage)(e)&&(0,vt.applyEmbedControlDefaults)(e),e.id||(e.id=xn.Guid.NewGuid()),e.classId===void 0&&(e.classId=String($e.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":nT(String(e.classId))),e.isRequired===void 0&&(e.isRequired=!1),e.isReadOnly===void 0&&(e.isReadOnly=!1),e.label===void 0&&(e.label=(t=e.fieldName)!==null&&t!==void 0?t:""),e.showLabel===void 0&&(e.showLabel=!0),(e.parameters===void 0||e.parameters===null)&&(e.parameters={});for(let r of Object.keys(e.parameters))(0,Ih.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,He.emptyBag)())}function Hz(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!tT(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Dh(xn.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!tT(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Dh(xn.Guid.NewGuid())])}}var Cc=class{constructor(t=rT.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=XI(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=hz[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,vt.projectGenPageEmbeds)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:ZI(t,this.lcid),formid:t.id||(0,Ea.newId)(),objecttypecode:t.entityLogicalName,type:Ec[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:tt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?tt.FormActivationState.Active:tt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d=this.deserialize({formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ea.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate});return Jz(this.toArtifact(d,(l=u.description)!==null&&l!==void 0?l:void 0),c)}toApiPayload(t,r,n){let i=(0,vt.genPageEmbedIssues)(t);if(i.length>0)throw new JI.ValidationError("form",t.id,i);return{formxml:ZI(t,this.lcid,n,r),name:t.name,type:Ec[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return xh(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}createDefault(t){var r,n,i,o,a,s,l,u,c,d,p;let f=(0,vt.genPageEmbedIssues)(t);if(f.length>0)throw new JI.ValidationError("form",t.id||"(new)",f);let m=t.tabs&&t.tabs.length>0?void 0:oW(this.lcid),h=m!==void 0?m:t.tabs.map(w=>Qz(w,this.lcid)).join(""),g=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,Ea.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Ec[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:tt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?tt.FormActivationState.Active:tt.FormActivationState.InActive}),y=this.toArtifact(g,t.description);if(t.tabs&&t.tabs.length>0){let w=eT(t);eT(y).forEach((C,S)=>{w[S]&&w[S].label===void 0&&delete C.label,w[S]&&w[S].genPage!==void 0&&(C.genPage=JSON.parse(JSON.stringify(w[S].genPage)))})}return{id:(l=t.id)!==null&&l!==void 0?l:y.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:y.tabs,bag:y.bag}}assignMissingIds(t){return(0,Ea.assignMissingIds)(t)}completeAsStored(t,r){return(0,mz.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,vt.mintEmbedIdentity)(t)}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!(0,vt.mayCommitEmbedState)(t))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ea.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Ec[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:tt.FormPresentation.AirForm,formactivationstate:tt.FormActivationState.Active}),{bag:d}=XI(c,this.lcid),p=(0,vt.commitEmbedState)(t,(l=(0,vt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node);return{artifact:p,baseline:p}}validate(t){return mW(t)}deserialize(t){(0,Th.installDomShim)();let r=uz.ScriptUtilities.ParseXml(t.formxml),n=new dz.DeserializationService(this.lcid).deSerializeFormXml(r,new xn.Guid(t.formid),t.objecttypecode,tt.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!n)throw new Error("FormXml could not be deserialized into a Form model.");return n}readActivationStatus(t){return t.formactivationstate===tt.FormActivationState.InActive?"Inactive":"Active"}};Wt.FormAdapter=Cc;function Kz(e){var t;(0,Th.installDomShim)();let r=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function Jz(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=Kz(t),i=["header","footer"].filter(a=>!n.has(a)),o=e.bag.c.filter(a=>{var s;return i.includes((s=a?.node)===null||s===void 0?void 0:s.n)}).map(a=>a.i);return o.length>0&&(e.bag.c=e.bag.c.filter(a=>{var s;return!i.includes((s=a?.node)===null||s===void 0?void 0:s.n)}).map(a=>({...a,i:a.i-o.filter(s=>s<a.i).length}))),e}function Or(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Lh(e,t){return e?`<labels><label description="${Or(e)}" languagecode="${t}" /></labels>`:""}function kh(e){return e&&e.length>0?rl(e):(0,Ea.newId)()}function Qz(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[iW()]).map(l=>Xz(l,t)).join("");return`<tab id="{${Or(kh(e.id))}}" name="${Or((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${Lh(e.label,t)}<columns>${s}</columns></tab>`}function Xz(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>Yz(o,t)).join("");return`<column width="${Or((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function Yz(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>Zz(l,t)).join("");return`<section id="{${Or(kh(e.id))}}" name="${Or((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Nh((a=e.columns)!==null&&a!==void 0?a:1)}">${Lh(e.label,t)}<rows>${s}</rows></section>`}function Zz(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>eW(n,t)).join("")}</row>`}function eW(e,t){var r,n,i,o,a;let s=tW(e),l=s.control,u=l?Lh((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?rW(l):"";return`<cell id="{${Or(kh(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function tW(e){if(!(0,vt.hasGenPage)(e.control))return e;let t={...e.control};(0,vt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,vt.applyEmbedCellDefaults)(r),r}function rW(e){var t,r,n;let i=e.fieldName?` datafieldname="${Or(e.fieldName)}"`:"",o=nW(e.parameters),a=e.classId?rl(e.classId):String($e.ControlClassId.TextboxControl);return`<control id="${Or((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Or(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function nW(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Ih.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Or(e[n])}</${n}>`).join("")}</parameters>`)}function iW(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function oW(e){return`<tab id="{${xn.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${xn.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${e}" /></labels><rows></rows></section></sections></column></columns></tab>`}function aW(e=rT.DEFAULT_LCID){return{adapter:new Cc(e),api:fz.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,KI.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,KI.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Wt.formRegistration=aW;var sW=new Set(["id","name","label","expanded","visible","columns","bag"]),lW=new Set(["id","width","sections","bag"]),uW=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),cW=new Set(["id","cells","bag"]),dW=new Set(["id","visible","colspan","rowspan","control","bag"]),pW=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","bag"]),fW={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function mW(e){let t=[];return(0,zt.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,zt.rejectUnknownKeys)(n,sW,o,"tab",t),(0,zt.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,zt.rejectUnknownKeys)(s,lW,u,"column",t),(0,zt.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:p})=>{let f=`${u}/sections/${p}`;(0,zt.rejectUnknownKeys)(d,uW,f,"section",t),(0,zt.childObjects)(d,"rows",f,"row",t).forEach(({node:h,index:g})=>{let y=`${f}/rows/${g}`;(0,zt.rejectUnknownKeys)(h,cW,y,"row",t),(0,zt.childObjects)(h,"cells",y,"cell",t).forEach(({node:C,index:S})=>{let T=`${y}/cells/${S}`;(0,zt.rejectUnknownKeys)(C,dW,T,"cell",t,fW);let O=C.control;O!=null&&!(0,zt.isJsonObject)(O)?t.push((0,zt.issue)(`${T}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof O}`)):(0,zt.isJsonObject)(O)&&(0,zt.rejectUnknownKeys)(O,pW,`${T}/control`,"control",t)})})})})}),t.push(...(0,vt.genPageEmbedIssues)(e)),t}Wt.SUBGRID_CLASS_ID=$e.ControlClassId.SubgridControl;Wt.NOTES_CLASS_ID=$e.ControlClassId.TimelineControl;Wt.QUICK_VIEW_CLASS_ID=$e.ControlClassId.QuickViewControl;var hW={Lookup:String($e.ControlClassId.LookupControl),Customer:String($e.ControlClassId.LookupControl),Owner:String($e.ControlClassId.LookupControl),PartyList:String($e.ControlClassId.PartyListControl),Boolean:String($e.ControlClassId.BooleanControl),DateTime:String($e.ControlClassId.DateTimeControl),Decimal:String($e.ControlClassId.DecimalControl),Double:String($e.ControlClassId.FloatingNumberControl),Money:String($e.ControlClassId.CurrencyControl),Integer:String($e.ControlClassId.IntegerControl),BigInt:String($e.ControlClassId.IntegerControl),Memo:String($e.ControlClassId.TextAreaControl),String:String($e.ControlClassId.TextboxControl)},gW="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function uT(e){return e==="Picklist"||e==="State"||e==="Status"?gW:e&&hW[e]||String($e.ControlClassId.TextboxControl)}Wt.classIdForAttributeType=uT;function tT(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Fh=b(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.viewApi=Ca.findDefaultViews=void 0;var fT=Rt(),Xt=be(),on=ae(),vW="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",yW="savedqueryid,name,returnedtypecode,querytype,isdefault",bW=60*1e3;function dT(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=String((n=e.fetchxml)!==null&&n!==void 0?n:"");if(/<link-entity\b/i.test(o))return!1;let a=(i=o.match(/<condition\b[^>]*>/gi))!==null&&i!==void 0?i:[];return a.length===1&&/\battribute=["']statecode["']/i.test(a[0])&&/\boperator=["']eq["']/i.test(a[0])&&(t===1?/\bvalue=["']1["']/i:/\bvalue=["']0["']/i).test(a[0])}function wW(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/),n=String(t??"").trim().toLowerCase().split(/\s+/);return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function AW(e){var t,r;let n=e.filter(l=>dT(l,0)),i=e.filter(l=>dT(l,1));if(n.length!==1||i.length!==1)return;let[o]=n,[a]=i;return Math.abs(Date.parse(String((t=a.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=o.createdon)!==null&&r!==void 0?r:"")))<=bW&&wW(o.name,a.name)?a:void 0}async function EW(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,on.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,on.odataQuery)([["$select","savedqueryid,name,isdefault,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,fT.collectPages)(e,a,`findDefaultViews('${t}')`),l=c=>{var d;return/^(Active|Inactive)\b/i.test((d=c.name)!==null&&d!==void 0?d:"")},u=new Set(s.filter(c=>c.isdefault||l(c)));if(!s.some(l)){let c=AW(s);c&&u.add(c)}return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}Ca.findDefaultViews=EW;async function CW(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,on.odataPathLiteral)(t)}')${(0,on.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function pT(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await CW(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Ca.viewApi={async get(e,t){let r=(0,on.normalizeGuid)(t,"id"),n=await(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,on.odataQuery)([["$select",vW]]);return{raw:(0,Xt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",(0,on.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueries${(0,on.odataQuery)([["$select",yW],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,on.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,fT.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Xt.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await pT(e,n.layoutxml,n.returnedtypecode),s=(0,Xt.ensureSuccess)(await e.post(o,(0,Xt.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r),i.options),e.apiUrl(o));return{id:(0,Xt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Xt.readEtag)(s)}},async update(e,t,r,n){let i=r,o=(0,on.normalizeGuid)(t,"id"),a=(0,Xt.echoWrite)("savedqueryid",{"If-Match":(0,Xt.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await pT(e,i.layoutxml,i.returnedtypecode),u=(0,Xt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,Xt.readEtag)(u)}},delete(e,t){return(0,Xt.deleteRecord)(e,"savedqueries",t)}}});var IT=b(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.viewRegistration=Sa.ViewAdapter=void 0;var wT=re(),Yt=Nr(),Mh=ri(),no=oi(),mT=nr(),SW=Fh(),Bh=ii(),NW=lt(),AT=100,_c=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Bh.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,no.parseXmlRoot)(c,"<fetch/>"),f=(0,no.parseXmlRoot)(d,"<grid/>"),m=CT(p);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:_W(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:ET(f,p),filters:NT(p),sort:ST(p),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,no.projectElementBag)(p):void 0,layoutBag:d?(0,no.projectElementBag)(f):void 0}}fromArtifact(t){(0,Bh.installDomShim)();let{fetchxml:r,layoutxml:n}=hT(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,Bh.installDomShim)();let{fetchxml:s,layoutxml:l}=hT(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,NW.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,Yt.childObjects)(n,"columns","","column",r),(0,Yt.childObjects)(n,"sort","","sort",r),(0,Yt.childObjects)(n,"linkEntities","","linkEntity",r),DW(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Yt.isJsonObject)(i)?$h(i,"/filters",r):r.push((0,Yt.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Sa.ViewAdapter=_c;function DW(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Yt.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Yt.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,Yt.isJsonObject)(i)?$h(i,`/linkEntities/${n}/filters`,t):t.push((0,Yt.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function $h(e,t,r){(0,Yt.childObjects)(e,"conditions",t,"condition",r),(0,Yt.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>$h(i,`${t}/groups/${o}`,r))}function _W(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function ET(e,t){var r;let n=Uh(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?AT:c,order:a},p=n.get(u);p&&(d.relatedEntity=p.linkKey,p.attributeName&&p.attributeName!==u&&(d.sourceAttribute=p.attributeName)),a+=1,o.push(d)}return o}function Uh(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function CT(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of yt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=yt(n,"filter").find(c=>!Ic(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:qh(u)}:{}})}return r}function ST(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function NT(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=yt(t,"filter").filter(i=>!Ic(i)).map(qh);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Ic(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(yt(e,"filter").length>0)return!1;let t=yt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||yt(r,"value").length>0||TW(r))}var IW=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function TW(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!IW.has(i))return!0}return!1}function qh(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let p=l.getAttribute("entityname")||"";p&&(c.entityname=p),i.push(c)}else l.tagName==="filter"&&o.push(qh(l))}return{type:n,conditions:i,groups:o}}function yt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Vh=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function PW(e,t){let r=Uh(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Vh(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function RW(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Vh(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new wT.ValidationError("view",e.id,a.map(s=>(0,Yt.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function hT(e){let t=OW(e.columns);if(!gT(e.fetchBag)||!gT(e.layoutBag))return{fetchxml:zW({...e,columns:t}),layoutxml:WW({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=vT(e.fetchBag,"fetch",r),i=vT(e.layoutBag,"grid",r),o=ET(i,n),a=!Dc(t,o),s=!Dc(e.sort,ST(n)),l=!Dc(e.filters,NT(n)),u=e.linkEntities,c=u!==void 0&&!Dc(u,CT(n)),d=c?PW(n,o):void 0;return c&&qW(r,n,u),c&&(GW(e,n,t,d),RW(e,n,t,d)),a?(yT(r,n,t,o),FW(r,i,t)):c&&yT(r,n,t,o),s&&$W(r,n,e.sort),l&&UW(r,n,e.filters),{fetchxml:(0,no.serializeNode)(n),layoutxml:(0,no.serializeNode)(i)}}function OW(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:AT,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function gT(e){return!!e&&(e.c.length>0||e.a.length>0)}function vT(e,t,r){let n={n:t,a:(0,Mh.mergeAttrs)(e.a,[]),c:(0,Mh.spliceChildren)(e.c,[])};return(0,Mh.rebuildRaw)(n,(0,no.domEngine)(r),null)}function yT(e,t,r,n){var i,o;let a=t.getElementsByTagName("entity")[0];if(!a)return;let s=d=>{var p,f;return`${(p=d.relatedEntity)!==null&&p!==void 0?p:""}:${d.name}:${(f=d.sourceAttribute)!==null&&f!==void 0?f:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||xW(a,d);let u=Uh(t),c=new Set(yt(a,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((p,f)=>p.order-f.order))if(d.relatedEntity){let p=u.get(d.name);if(p&&p.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(p.linkKey===d.relatedEntity||p.linkName===d.relatedEntity||!_T(a,d.relatedEntity)))continue;let f=LW(e,a,d.relatedEntity),m=e.createElement("attribute");DT(m,d),f.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:f.getAttribute("name")||d.relatedEntity,attributeName:(o=d.sourceAttribute)!==null&&o!==void 0?o:d.name,link:f})}else{if(c.has(d.name))continue;let p=e.createElement("attribute");p.setAttribute("name",d.name),kW(a,p),c.add(d.name)}}function DT(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function xW(e,t){if(t.relatedEntity){for(let r of yt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of yt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of yt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function _T(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of yt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function LW(e,t,r){let n=_T(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function kW(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function FW(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=MW(n);if(BW(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function MW(e){return yt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function BW(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].getAttribute("name")!==t[r].name)return!1;return!0}function $W(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(p,f)=>`${p.toLowerCase()}\0${f.toLowerCase()}`,o=new Map,a=new Map,s=(p,f,m)=>{let h=p.get(f);h?h.push(m):p.set(f,[m])};for(let p of yt(n,"order")){let f=p.getAttribute("attribute")||"";f&&(s(o,i(p.getAttribute("entityname")||"",f),p),s(a,f.toLowerCase(),p)),n.removeChild(p)}let l=new Set,u=(p,f)=>{let m=p.get(f);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=p=>{var f;let m=a.get(p.toLowerCase());if(!m)return;let h=m.filter(y=>!l.has(y)),g=(f=h.find(y=>!y.getAttribute("entityname")))!==null&&f!==void 0?f:h[0];return g&&l.add(g),g},d=r.map(p=>{let f=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:u(o,i(p.entityname,f))}});for(let p of d)p.expression.entityname===void 0&&(p.element=c(String(p.expression.attribute)));for(let{expression:p,element:f}of d){let m=f??e.createElement("order");m.setAttribute("attribute",p.attribute),m.setAttribute("descending",String(p.descending)),p.entityname?m.setAttribute("entityname",p.entityname):p.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function UW(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of yt(n,"filter"))Ic(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(nl(e,r))}}function Dc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qW(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=yt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,g)=>{if(s[g])return;let y=o.filter(S=>!l.has(S)&&m(S,h));if(y.length!==1)return;let w=y[0];r.some((S,T)=>T!==g&&!s[T]&&m(w,S))||(s[g]=w,l.add(w))})};u((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),u((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!l.has(m)),p=new Map;for(let m of d){let h=p.get(a(m,"name"));h?h.push(m):p.set(a(m,"name"),[m])}let f=new Map;for(let m of c){let h=f.get(r[m].name);h?h.push(m):f.set(r[m].name,[m])}for(let[m,h]of f){let g=(n=p.get(m))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((y,w)=>{s[y]=g[w],l.add(g[w])})}r.forEach((m,h)=>{let g=s[h];if(g){bT(e,g,m);return}let y=e.createElement("link-entity");bT(e,y,m),i.appendChild(y)});for(let m of o)l.has(m)||i.removeChild(m)}var VW=new Set(["inner","outer"]);function GW(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],p=d.getAttribute("name"),f=d.getAttribute("alias");p&&o.add(p),f&&o.add(f)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Vh(c));return!!d&&d.every(p=>s.has(p))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new wT.ValidationError("view",e.id,u.map(c=>{var d;let p=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(f=>f.name===c.relatedEntity||f.alias===c.relatedEntity);return(0,Yt.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(p?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function bT(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):VW.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=yt(t,"filter").find(o=>!Ic(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?nl(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function zW(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(nl(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){DT(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(nl(r,e.filters)),new XMLSerializer().serializeToString(r)}function nl(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(nl(e,n));return r}function WW(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function jW(){return{adapter:new _c,api:SW.viewApi,publish:(e,t,r)=>(0,mT.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,mT.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Sa.viewRegistration=jW});function Tc(e,t){return e==="SetFieldValue"&&t!==void 0&&HW.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var HW,Gh=R(()=>{"use strict";HW=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function TT(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function zh(e){return e==="AllForms"||TT(e)?1:2}function Wh(e){return TT(e)?e:null}function PT(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Na.WorkflowCategory.BusinessRule,type:Na.WorkflowTypeCode.Definition,mode:1,scope:Na.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:zh(e.scope),processtriggerformid:Wh(e.scope)}}var Na,RT=R(()=>{"use strict";Na=de(Ti());});function OT(e,t=0){return(ct[e[t+0]]+ct[e[t+1]]+ct[e[t+2]]+ct[e[t+3]]+"-"+ct[e[t+4]]+ct[e[t+5]]+"-"+ct[e[t+6]]+ct[e[t+7]]+"-"+ct[e[t+8]]+ct[e[t+9]]+"-"+ct[e[t+10]]+ct[e[t+11]]+ct[e[t+12]]+ct[e[t+13]]+ct[e[t+14]]+ct[e[t+15]]).toLowerCase()}var ct,xT=R(()=>{ct=[];for(let e=0;e<256;++e)ct.push((e+256).toString(16).slice(1))});function jh(){return Pc>Rc.length-16&&((0,LT.randomFillSync)(Rc),Pc=0),Rc.slice(Pc,Pc+=16)}var LT,Rc,Pc,kT=R(()=>{LT=require("crypto"),Rc=new Uint8Array(256),Pc=Rc.length});var FT,Hh,MT=R(()=>{FT=require("crypto"),Hh={randomUUID:FT.randomUUID}});function KW(e,t,r){if(Hh.randomUUID&&!t&&!e)return Hh.randomUUID();e=e||{};let n=e.random??e.rng?.()??jh();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return OT(n)}var Nt,BT=R(()=>{MT();kT();xT();Nt=KW});var Kh=R(()=>{BT()});var $T=R(()=>{"use strict";});var Jh=b(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.WorkflowConditionOperator=mr.WorkflowAttributeType=mr.SystemStep=mr.FieldRequiredLevelTypes=mr.AttributeDateTimeBehavior=void 0;mr.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};mr.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};mr.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};mr.WorkflowAttributeType={Boolean:"0",Customer:"1",DateTime:"2",Decimal:"3",Float:"4",Integer:"5",Lookup:"6",Money:"7",Owner:"8",PartyList:"9",Picklist:"10",Key:"11",State:"12",Status:"13",String:"14",UniqueIdentifier:"15",EntityNameReference:"16",Entity:"17",EntityCollection:"18",BpfProcess:"19",BpfStageCategory:"20",BpfStage:"21",EntityReferenceCollection:"22",MultiSelectPicklist:"23",BigType:"24"};mr.WorkflowConditionOperator={IsNull:"0",NotNull:"1",LogicalAnd:"2",LogicalOr:"3",IN:"4",NotIn:"5",NotInNull:"51",Equal:"6",NotEqual:"7",Contains:"8",DoesNotContain:"9",BeginsWith:"10",DoesNotBeginWith:"11",EndsWith:"12",DoesNotEndWith:"13",GreaterThan:"14",GreaterThanOrEqual:"15",LessThan:"16",LessThanOrEqual:"17",EqualUserId:"18",NotEqualUserId:"19",On:"20",NotOn:"21",OnOrAfter:"22",OnOrBefore:"23",Yesterday:"24",Today:"25",Tomorrow:"26",NextSevenDays:"27",LastSevenDays:"28",NextWeek:"29",LastWeek:"30",ThisWeek:"31",NextMonth:"32",LastMonth:"33",ThisMonth:"34",NextYear:"35",LastYear:"36",ThisYear:"37",Anytime:"38",LastXHours:"39",NextXHours:"40",LastXDays:"41",NextXDays:"42",LastXWeeks:"43",NextXWeeks:"44",LastXMonths:"45",NextXMonths:"46",LastXYears:"47",NextXYears:"48",Under:"49",NotUnder:"50"}});function GT(e){switch(e){case"Boolean":return Ne.WorkflowAttributeType.Boolean;case"Customer":return Ne.WorkflowAttributeType.Customer;case"DateTime":return Ne.WorkflowAttributeType.DateTime;case"Decimal":return Ne.WorkflowAttributeType.Decimal;case"Double":return Ne.WorkflowAttributeType.Float;case"Integer":return Ne.WorkflowAttributeType.Integer;case"Lookup":return Ne.WorkflowAttributeType.Lookup;case"Money":return Ne.WorkflowAttributeType.Money;case"Owner":return Ne.WorkflowAttributeType.Owner;case"Picklist":return Ne.WorkflowAttributeType.Picklist;case"State":return Ne.WorkflowAttributeType.State;case"Status":return Ne.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ne.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ne.WorkflowAttributeType.BigType;default:return Ne.WorkflowAttributeType.String}}function QT(e){return e&&e!==Ne.WorkflowAttributeType.String?e:void 0}function XW(e){return{__class:JT,parameterName:"primaryEntity",entityName:e}}function UT(e){return{__class:Xh,type:Qh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:zT,parameters:[e]}}function qT(e,t,r=Ne.WorkflowAttributeType.String){return{__class:jT,type:r,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,entity:XW(t),attributeName:e}}function YW(e,t=Ne.WorkflowAttributeType.String){return{__class:HT,type:t,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function ZW(e){return{__class:KT,type:Qh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function XT(e,t){let r=JW[e.operator],n=UT(qT(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=ZW(e.right.value??"0"):e.right.kind==="field"?i=qT(e.right.field??"",t,e.right.workflowType):i=YW(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=UT(i);return{__class:Xh,type:Qh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:WT,parameters:[r,n,o]}}function YT(e){return typeof e=="object"&&e.__class===Xh}function e7(e){return typeof e=="object"&&e.__class===KT}function Oc(e){return YT(e)&&e.method===zT&&e.parameters.length>0?Oc(e.parameters[0]):e}function VT(e){if(typeof e!="object"||e.__class!==jT)return null;let t=e.entity;if(t&&t.__class&&t.__class!==JT)return null;let r=e.attributeName;return r?{field:r,workflowType:QT(e.type)}:null}function ZT(e){if(!e)return null;let t=Oc(e);if(!YT(t)||t.method!==WT||t.parameters.length!==3)return null;let r=t.parameters[0],n=QW[String(r)];if(!n)return null;let i=VT(Oc(t.parameters[1]));if(!i)return null;let o=Oc(t.parameters[2]);if(e7(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=VT(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===HT){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:QT(o.type)}}}return null}function Zh(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Yh&&r<=Da}function io(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!Zh(t)?"invalidDayCount":null}function _a(e){return io(e)===null}var Ne,zT,WT,Qh,jT,HT,Xh,KT,JT,JW,QW,Yh,Da,il=R(()=>{"use strict";Ne=de(Jh());zT="0",WT="3",Qh="0",jT="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",HT="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Xh="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",KT="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",JT="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";JW={"+":0,"-":1,"*":2,"/":3},QW={0:"+",1:"-",2:"*",3:"/"};Yh=0,Da=2147483647});var e2=R(()=>{"use strict";});function Ln(e){return!t7.has(e)}function eg(e){return e==="Equals"||e==="DoesNotEqual"}function i2(e){return c7.has(e)}function xc(e){return r2.has(e)?r7:s7.has(e)?n7:n2.has(e)?i7:u7.has(e)?a7:o7}function o2(e){return xc(e)[0]}function a2(e,t){return xc(t).includes(e)}function t2(e){return r2.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":n2.has(e)?"date":l7.has(e)?"boolean":"other"}function Lc(e,t){let r=t2(e),n=t2(t);return r==="other"||n==="other"?e===t:r===n}var t7,r7,n7,i7,o7,a7,r2,s7,n2,l7,u7,c7,kc=R(()=>{"use strict";e2();t7=new Set(["ContainsData","DoesNotContainData"]);r7=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],n7=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],i7=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],o7=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],a7=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],r2=new Set(["String","Memo","EntityName"]),s7=new Set(["Integer","BigInt","Money","Decimal","Double"]),n2=new Set(["DateTime"]),l7=new Set(["Boolean"]),u7=new Set(["Lookup","Owner","Customer"]);c7=new Set(["Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith"])});function p7(e){return e.startsWith("__")&&!d7.has(e)}function f7(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{p7(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function b2(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function oo(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Fc(e){return b2(e)||oo(e)}function m7(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function ol(){return{list:[]}}function tg(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Nt(),languageCode:r,description:t}]}}function og(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Uc(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entity:og(t),attributeName:e}}function Ta(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function v7(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?E2:A2:w2}function C2(e){return e.bpfField==="StageCategory"?G.WorkflowAttributeType.BpfStageCategory:G.WorkflowAttributeType.BpfProcess}function y7(e,t){let r=C2(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${l2}_${s2}`,entityName:s2,relatedAttributeName:l2},attributeName:g7}:Uc(h7,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,method:lg,parameters:[v7(e),n]}}function S2(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==lg)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===A2?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===E2?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===w2?{bpfField:"ProcessName"}:null}function Mc(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===lg){let r=(t.parameters??[])[0];if(typeof r=="string"&&b7.has(r.replace(/^"+|"+$/g,"")))return!0}return oo(e)?Mc(e.operand):b2(e)?Mc(e.left)||(e.right??[]).some(Mc):!1}function N2(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function w7(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function u2(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return N2(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function A7(e){let t=sg[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(oo(e))return r&&c2(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:c2(e.left,r,n[0])}function c2(e,t,r){return S2(e)||N2(e)?t||u2(r):!1}function ag(e){if(!e||!Fc(e))return!1;let t=e.conditionOperatoroperator;if(!oo(e)&&(t===G.WorkflowConditionOperator.LogicalAnd||t===G.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&ag(e.left)&&r.every(ag)}return A7(e)}function d2(e){return!e||w7(e)?!1:Mc(e)||!ag(e)}function D2(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??G.WorkflowAttributeType.Lookup,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ta(e.id.replace(/[{}]/g,""),G.WorkflowAttributeType.UniqueIdentifier)}}function p2(e){return e==="ContainsData"||e==="DoesNotContainData"}function rg(e){return E7.has(e)}function f2(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function m2(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??G.WorkflowAttributeType.Lookup:e.valueWorkflowType??G.WorkflowAttributeType.String,n=e.leftWorkflowType??r,i=rg(n)&&i2(e.operator),o=ig[e.operator]??G.WorkflowConditionOperator.Equal;if(e.source==="BusinessProcess"){let l=y7(e,t);if(p2(e.operator))return f2(l,o);let u=C2(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o,left:l,right:[Ta(e.value??"",u)]}}let a=Uc(e.field,t,n);if(p2(e.operator))return f2(a,o);let s;if(e.valueType==="Field"&&e.valueField){let l=rg(n)&&rg(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:n;s=[Uc(e.valueField,t,i?G.WorkflowAttributeType.String:l)]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[D2(e.lookupValue)]}else e.valueType==="Clear"?s=[Ta(null,r)]:e.valueType==="Expression"?s=[$c(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:s=[Ta(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o,left:a,right:s}}function C7(e,t,r){if(e.length===0)return null;let n=m2(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?G.WorkflowConditionOperator.LogicalAnd:G.WorkflowConditionOperator.LogicalOr,left:n,right:[m2(e[i],r)]}}return n}function Bc(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return e.primitiveValue==null?{valueType:"Clear",valueWorkflowType:e.type}:{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):"",valueWorkflowType:e.type};if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==G.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=ZT(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function S7(e){let t=sg[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=oo(e)?e.operand:e.left,i=oo(e)?[]:e.right??[],o=S2(n);if(o){let d=i[0];return{id:Nt(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:d?.primitiveValue!=null&&!r?String(d.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:Bc(i[0]),c=u.valueWorkflowType??l;return{id:Nt(),field:s,fieldDisplayName:s,operator:t,...u,...c?{valueWorkflowType:c}:{},...l?{leftWorkflowType:l}:{}}}function h2(e){if(!e||!Fc(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(oo(o)||s!==G.WorkflowConditionOperator.LogicalAnd&&s!==G.WorkflowConditionOperator.LogicalOr){t.push({...S7(o),...a?{connector:a}:{}});return}let l=s===G.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Fc(o.left)&&r(o.left,a),(o.right??[]).filter(Fc).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function $c(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return Uc(r,n,G.WorkflowAttributeType.String);if(e==="Expression"){if(i)return XT(i,n);if(o!=null)return o}return e==="Lookup"&&a?D2(a):e==="Clear"?Ta(null,s??G.WorkflowAttributeType.String):Ta(t??"",G.WorkflowAttributeType.String)}function ng(e,t){return{propertyName:e,propertyValueExpr:t}}function Ia(e){return`Step_${e.value++}`}function hr(e,t){let r=(t.counts[e]??0)+1,n=`${e}${r}`;for(;t.used.has(n);)r+=1,n=`${e}${r}`;return t.counts[e]=r,t.used.add(n),n}function g2(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):hr(t,r)}function N7(e){return e===y2.StateCode.Activated?"Active":"Draft"}function D7(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function _2(e,t=1033){return new Pa({languageCode:t}).serialize(e)}function I2(e){return new Pa().deserialize(e)}var y2,G,d7,ig,sg,lg,w2,A2,E2,h7,g7,s2,l2,b7,E7,ug,Pa,cg=R(()=>{"use strict";Kh();y2=de(Ti());$T();il();kc();G=de(Jh());d7=new Set(["__class"]);ig={Equals:G.WorkflowConditionOperator.Equal,DoesNotEqual:G.WorkflowConditionOperator.NotEqual,IsGreaterThan:G.WorkflowConditionOperator.GreaterThan,IsLessThan:G.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:G.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:G.WorkflowConditionOperator.LessThanOrEqual,Contains:G.WorkflowConditionOperator.Contains,DoesNotContain:G.WorkflowConditionOperator.DoesNotContain,BeginsWith:G.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:G.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:G.WorkflowConditionOperator.EndsWith,DoesNotEndWith:G.WorkflowConditionOperator.DoesNotEndWith,On:G.WorkflowConditionOperator.On,NotOn:G.WorkflowConditionOperator.NotOn,ContainsData:G.WorkflowConditionOperator.NotNull,DoesNotContainData:G.WorkflowConditionOperator.IsNull},sg={};for(let e of Object.keys(ig))sg[ig[e]]=e;lg="23",w2="BpfProcess",A2="ActiveStageCategory",E2="SelectedStageCategory",h7="processid",g7="stagecategory",s2="processstage",l2="stageid";b7=new Set(["ActiveStage","SelectedStage","Stage"]);E7=new Set([G.WorkflowAttributeType.Lookup,G.WorkflowAttributeType.Owner,G.WorkflowAttributeType.Customer]);ug={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};Pa=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>ug[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??Nt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:ol(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:hr("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ia(this.stepCounter),stepLabels:{list:[]},specification:ng(t.field,$c(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:og(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=tg(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:g2(n?.id,"ActionStep",this.idCounter),name:n?.name??Ia(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??Nt(),uniqueName:n?.uniqueName??`id_${Nt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=og(this.entityName),n=t.stepName??Ia(this.stepCounter),i=t.stepLabels??ol(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:hr("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ng(t.field,$c(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:hr("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ng(t.field,$c(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:hr("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:hr("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?G.FieldRequiredLevelTypes.Required:G.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:hr("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=tg(t.stepLabels,s,this.languageCode);return{...o,id:hr("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,name:s,controlId:t.field,entity:r,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,l=tg(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:hr("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ia(this.stepCounter),n=hr("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??C7(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ia(this.stepCounter):Ia(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?g2(o.branchId,"ConditionBranchStep",this.idCounter):hr("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:ol(),conditionExpression:s??void 0,steps:{list:o.trueBranch.map(p=>this.serializeBranchItem(p))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:ol(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:hr("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:ol(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??Nt():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:f7(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:D7(r,i?.formId),status:N7(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(m7);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=h2(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??Nt(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...d2(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=h2(n.conditionExpression);return i.length===0&&!d2(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||Nt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Bc(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bc(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetFieldValue",displayName:t.description||t.name||this.label("setFieldValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bc(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==G.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});function mg(e){return _7.has(e.type)}function dg(e,t,r,n,i,o,a){let s=i.get(r);!s||!R2.has(s.attributeType)||n!=="Value"||a?.operator&&!eg(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function I7(e,t){let r=t.get(e.field);return!!r&&R2.has(r.attributeType)&&eg(e.operator)}function pg(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function fg(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Da}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Da}}}function T2(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Tc(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Vc(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(mg(t))return!0}else if(Vc(t))return!0;return!1}function hg(e,t){if(e.id===t)return e;for(let r of[...e.trueBranch,...e.falseBranch]){if(r.id===t)return r;if(r.kind==="condition"){let n=hg(r,t);if(n)return n}}return null}function Ra(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=Ra(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=Ra(n,t);if(i)return i}}return null}function gg(e,t){return{...e,trueBranch:P2(e.trueBranch,t),falseBranch:P2(e.falseBranch,t)}}function P2(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?gg(r,t):r)}function Ci(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Ci(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Ci(n,t,r):n)}}function qc(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?qc(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?qc(n,t,r):n)}}function O2(e,t,r,n){return Ci(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function vg(e){return e.length===1&&e[0].kind==="condition"}function P7(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(vg(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function R7(e){return!!e&&P7(e)<T7}function O7(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(vg(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function x2(e,t,r){let n=O7(e,t);return!n||!R7(n)?e:Ci(e,t,i=>L2(i,r))}function L2(e,t){if(vg(e.falseBranch))return{...e,falseBranch:[L2(e.falseBranch[0],t)]};let r=yg(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function k2(e,t){let r=Ra(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return Ci(e,r.node.id,o=>({...o,falseBranch:i}))}function F2(e,t,r){let n=Ra(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return Ci(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function yg(e){return{kind:"condition",id:Nt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M2(e,t){let r={kind:"action",id:Nt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Nt(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...r,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...r,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...r,type:"SetVisibility",field:"",visible:!0};default:return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function B2(e){if(!e)return[];let t=[];return $2(e,t),[...new Set(t)]}function $2(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?$2(r,t):"field"in r&&r.field&&t.push(r.field)})}function U2(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return q2(e,r,n),Vc(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function q2(e,t,r){let n=!!e.rawConditionExpression;e.clauses.length===0&&!n&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(i=>{if(n)return;if(i.source==="BusinessProcess"){i.bpfField?i.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:i.id,messageKey:"Validation.SelectBusinessProcessField"});return}let o=i.valueType==="Expression"&&!i.rawExpression?io(i.expression):null;if(!i.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:i.id});else if(Ln(i.operator)&&i.valueType==="Value"&&!i.value&&!I7(i,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id});else if(Ln(i.operator)&&i.valueType==="Value"&&i.value){let a=r.get(i.field);a?.maxLength&&i.value.length>a.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${a.maxLength} characters.`,target:"clauseValue",itemId:i.id,messageParams:{maxLength:a.maxLength}})}else Ln(i.operator)&&i.valueType==="Expression"&&!i.rawExpression&&!_a(i.expression)?t.push(o==="invalidDayCount"?fg(e.id,"clauseValue",i.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.CompleteClauseFormula"}):Ln(i.operator)&&i.valueType==="Field"&&!i.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseCompareField"});Ln(i.operator)&&i.valueType==="Lookup"&&(pg(i.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseLookupValue"})),Ln(i.operator)&&dg(e.id,"Condition",i.field,i.valueType,r,t,{operator:i.operator,target:"clauseValue",itemId:i.id})}),[...e.trueBranch,...e.falseBranch].forEach(i=>{if(i.kind==="condition")q2(i,t,r);else{if(!("field"in i)||!i.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:`${i.type}: a target field is required.`,target:"actionField",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&(i.valueType??"Value")==="Value"&&!i.value?.trim())t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Value"&&i.value){let o=r.get(i.field);o?.maxLength&&i.value.length>o.maxLength&&t.push({nodeId:i.id,kind:"ACTION_VALUE_TOO_LONG",message:`${i.type}: value exceeds the field's maximum length of ${o.maxLength} characters.`,target:"actionValue",messageParams:{actionType:i.type,maxLength:o.maxLength}})}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Field"){if(!i.valueField)t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:i.type}});else if(r.size>0){let o=r.get(i.field),a=r.get(i.valueField);o&&a&&!Lc(o.attributeType,a.attributeType)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:i.type}})}}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Expression"){let o=i.rawExpression?null:io(i.expression);!i.rawExpression&&!_a(i.expression)&&t.push(o==="invalidDayCount"?fg(i.id,"actionValue"):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:i.type}})}else(i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Lookup"&&!pg(i.lookupValue)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:i.type}});if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.field&&(dg(i.id,i.type,i.field,i.valueType,r,t,{target:"actionValue"}),T2(i.id,i.type,i.type,i.field,i.valueType,r,t,{target:"actionValue"})),i.type==="ShowErrorMessage"&&!i.errorMessage?.trim()&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),i.type==="Recommendation"){let o=i.applyActions??[];i.recommendationTitle?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),i.messageText?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),o.length===0&&t.push({nodeId:i.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),o.forEach(a=>{if(!a.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:a.id,messageKey:"Validation.RecommendationApplyField"});else if(a.valueType==="Field")a.valueField||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplySourceField"});else if(a.valueType==="Expression"){let s=a.rawExpression?null:io(a.expression);!a.rawExpression&&!_a(a.expression)&&t.push(s==="invalidDayCount"?fg(i.id,"applyActionValue",a.id):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyFormula"})}else a.valueType==="Lookup"?pg(a.lookupValue)||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyLookupValue"}):a.valueType==="Clear"||a.value?.trim()||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyValue"});a.field&&(dg(i.id,"Recommendation",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}),T2(i.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}))})}}})}var _7,R2,T7,bg=R(()=>{"use strict";Kh();Gh();kc();il();_7=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);R2=new Set(["Lookup","Customer","Owner"]);T7=10});var V2={};gn(V2,{DAY_COUNT_MAX:()=>Da,DAY_COUNT_MIN:()=>Yh,DEFAULT_DESERIALIZE_LABELS:()=>ug,WorkflowJsonMapper:()=>Pa,addElseIfInTree:()=>x2,appendToBranch:()=>O2,areFieldKindsCompatible:()=>Lc,attributeTypeToWorkflowType:()=>GT,buildWorkflowEntity:()=>PT,collectUsedFields:()=>B2,createEmptyAction:()=>M2,createEmptyCondition:()=>yg,deserializeWorkflowJson:()=>I2,findNode:()=>hg,findParent:()=>Ra,getDefaultOperatorForFieldType:()=>o2,getExpressionModelIssue:()=>io,getOperatorsForFieldType:()=>xc,hasAnyTriggerGeneratingAction:()=>Vc,isDayCountValid:()=>Zh,isExpressionModelComplete:()=>_a,isOperatorCompatible:()=>a2,isTriggerGeneratingAction:()=>mg,moveBranchItemInTree:()=>F2,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>Wh,processTriggerScopeFromScope:()=>zh,removeElseIfInTree:()=>k2,removeNodeFromTree:()=>gg,serializeToWorkflowJson:()=>_2,supportsClearForActionType:()=>Tc,updateActionInTree:()=>qc,updateConditionInTree:()=>Ci,validateBusinessRule:()=>U2});var G2=R(()=>{"use strict";Gh();RT();cg();cg();bg();bg();kc();il();il();});var wg=b(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.cloneJson=void 0;function x7(e){return JSON.parse(JSON.stringify(e))}Gc.cloneJson=x7});var tP=b(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.BUSINESS_RULE_NULL_GUID=Si.businessRuleRegistration=Si.BusinessRuleAdapter=void 0;var z2=lt(),al=(G2(),$r(V2)),W2=nr(),j2=re(),L7=wg(),an=Nr(),k7=ap(),F7=lt(),M7=Li(),B7=new Set(["ShowErrorMessage","Recommendation"]);function Q2(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?Q2(n):B7.has(String(n.type))):!1}function $7(e){return X2((0,L7.cloneJson)(e))}function X2(e){var t,r;let n=i=>(i??[]).map(o=>U7(o)?X2(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function U7(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function q7(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new j2.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new j2.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var V7="00000000-0000-0000-0000-000000000000";Si.BUSINESS_RULE_NULL_GUID=V7;var G7=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),z7=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],W7=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],j7=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function xr(e,t){return e===void 0?t:{...e,...t}}var ao=["kind","id","type","displayName","field","stepName","stepLabels"],H2=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],H7={Recommendation:[...ao,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...ao,"lock"],ShowErrorMessage:[...ao,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...ao,...H2],SetDefaultValue:[...ao,...H2],SetBusinessRequired:[...ao,"required"],SetVisibility:[...ao,"visible"]};function K(e,t){return t===void 0?{}:{[e]:t}}function Y2(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Ag(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",Y2(e.lookupValue)),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function Z2(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var K7=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function J7(e){return xr(e.bag,{id:e.id,field:e.field,...Ag(e),...K("stepName",e.stepName),...K("displayName",e.displayName)})}function Q7(e){let t=Z2(e,K7);return{id:e.id,field:e.field,valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression),...K("stepName",e.stepName),...K("displayName",e.displayName),...K("bag",t)}}function K2(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function J2(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var X7=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Y7=new Set,Z7="INVALID_CLEAR_FOR_FIELD";function ej(e){let t=n=>{var i;return(0,an.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,an.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var zc=class{toArtifact(t){let r=this.residualBag(t,z7),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return xr(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,al.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return Q2(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName});let s=(0,al.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:M7.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,z2.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,al.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson($7(q7(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,z2.newId)()),u}assignMissingIds(t){return(0,F7.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,an.isJsonObject)(n)?(eP(n,"/rootCondition",r),r):(r.push((0,an.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,an.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:ej(n.rootCondition),o;return r.length===0?o=X7:r.some(a=>a.requiredLevel!==void 0)?o=Y7:o=new Set([Z7]),(0,al.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,an.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}residualBag(t,r){return Z2(t,r)}buildWorkflowEntity(t,r){return(0,al.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,W7),n={id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseToJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemToJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemToJson(i))};return r&&(n.bag=r),n}clauseToJson(t){let r=this.residualBag(t,j7),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,H7[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels),...K("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Q7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...K2(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...K2(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return J2(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return xr(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return xr(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...K("value",t.value),...K("valueField",t.valueField),...K("lookupValue",Y2(t.lookupValue)),...K("expression",t.expression),...K("rawExpression",t.rawExpression),...K("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!G7.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);rj(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return xr(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(J7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return xr(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return xr(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return xr(t.bag,{...r,type:"SetFieldValue",...Ag(t)});case"SetDefaultValue":return xr(t.bag,{...r,type:"SetDefaultValue",...Ag(t)});case"SetBusinessRequired":return xr(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return xr(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return J2(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Si.BusinessRuleAdapter=zc;function eP(e,t,r){(0,an.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,an.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,an.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?eP(o,`${t}/${n}/${a}`,r):tj(o,`${t}/${n}/${a}`,r)})}function tj(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,an.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function rj(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function nj(){return{adapter:new zc,api:k7.businessRuleApi,publish:(e,t,r)=>(0,W2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,W2.boundEntityPublishScope)(t)}}Si.businessRuleRegistration=nj});var yP=b(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.appRegistration=Ni.AppAdapter=Ni.HEADER_NAV_BOOLEAN_RULE=void 0;var kn=Nr(),rt=ri(),ll=oi(),ij=nr(),dP=Nu(),Eg=Au(),Cg=ii(),oj=lt(),aj=ae(),pP=Li(),fP=re(),mP=Cu();Object.defineProperty(Ni,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return mP.HEADER_NAV_BOOLEAN_RULE}});var Kc="7.0.0.0",rP=`<SiteMap IntroducedVersion="${Kc}"></SiteMap>`,nP="/_imgs/imagestrips/transparent_spacer.gif",iP="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",sj=["Entity","Url","DefaultDashboard","Page","GenPageId"],sl="sitemapId",oP="sitemapName",lj="sitemapNameUnique",aP="aiDescription",sP="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",uj=new RegExp(`^(?:\\{${sP}\\}|${sP})$`);function lP(e,t){if(!uj.test(e.trim()))throw new fP.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function uP(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new fP.ValidationError("app",t,[hP(e)]);return e}function hP(e){return(0,kn.issue)("/headerAndNavigationRefresh",mP.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function cj(e){let t=n=>{let i=e[n];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},r=n=>{let i=t(n);if(i!==void 0)try{return(0,aj.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function dj(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var Jc=class{constructor(t=pP.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Wc(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,rt.emptyBag)()}}fromArtifact(t){(0,Cg.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,rt.rebuildRaw)(i,(0,ll.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,p;(0,Cg.installDomShim)();let f=t??{},m=(r=f.$sitemap)!==null&&r!==void 0?r:f,h=(0,ll.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:rP,rP),g=this.toArtifact(h);return g.id=(i=f.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=f.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=f.uniquename)!==null&&a!==void 0?a:"",g.description=(s=f.description)!==null&&s!==void 0?s:"",f.aiappdescription&&(g.aiDescription=f.aiappdescription),g.bag={a:[[sl,(u=(l=m.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[oP,(c=m.sitemapname)!==null&&c!==void 0?c:""],[lj,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[aP,(p=f.aiappdescription)!==null&&p!==void 0?p:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,p,f,m,h,g,y;(0,Cg.installDomShim)();let w=(0,ll.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let O of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let k of(o=O.groups)!==null&&o!==void 0?o:[])for(let F of(a=k.subAreas)!==null&&a!==void 0?a:[])F.type==="Entity"&&F.entity?C.push(F.entity):F.type==="DashBoard"&&F.dashboardId&&S.push(F.dashboardId);let T=(s=t.bag)!==null&&s!==void 0?s:(0,rt.emptyBag)();return{sitemapId:Ng(T,sl)||(t.sitemapId?lP(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Ng(T,oP)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Ng(T,aP))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Eg.HEADER_AND_NAVIGATION_REFRESH]:uP(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Eg.APP_SETTING_ON:Eg.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(m=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&m!==void 0?m:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((y=t.components)===null||y===void 0?void 0:y.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,oj.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:lP(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:uP(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(_g):Array.isArray(r.areas)?r.areas.forEach(_g):Array.isArray(r.groups)?_g(r):Array.isArray(r.subAreas)?vP(r):"type"in r&&Qc(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,kn.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(hP(o)),i==null)return r;if(!(0,kn.isJsonObject)(i))return r.push((0,kn.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,kn.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,kn.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let m=`${c}/groups/${f}`;(0,kn.childObjects)(p,"subAreas",m,"subArea",r).forEach(({node:g,index:y})=>{let w=`${m}/subAreas/${y}`;(0,kn.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=cj(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,kn.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,dP.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,dj(t))}applyServerIdentity(t,r){let n=r[sl];if(!n)return;t.bag||(t.bag=(0,rt.emptyBag)());let i=t.bag.a.find(o=>o[0]===sl);i?i[1]=n:t.bag.a.push([sl,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Wc(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Sg(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=Wc(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Sg(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Wc(t,null),i=pj(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Sg(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==nP&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,rt.emptyBag)(),l=jc(a)?[["IntroducedVersion",Kc]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,rt.mergeAttrs)(a.a,l),c:(0,rt.spliceChildren)(a.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,rt.emptyBag)(),i=jc(n),o=[],a=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Kc]),t.icon!==void 0?o.push(["Icon",t.icon]):Hc(n.a,"Icon")&&a.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Hc(n.a,"VectorIcon")&&a.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=Dg((0,rt.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,rt.mergeAttrs)(n.a,o,a),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,rt.emptyBag)(),i=jc(n),o=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Kc],["IsProfile","false"]);let a=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Dg((0,rt.spliceChildren)(n.c,a),t.title,i,this.lcid);return{n:"Group",a:(0,rt.mergeAttrs)(n.a,o),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,rt.emptyBag)(),i=jc(n),o=mj(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]),gj(a,t),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Hc(o,"Icon",nP)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Hc(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",iP]):s.push("VectorIcon"):t.type==="GenPage"&&!fj(o,"VectorIcon")&&a.push(["VectorIcon",iP]);let l=Dg((0,rt.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,rt.mergeAttrs)(o,a,s),c:l}}};Ni.AppAdapter=Jc;function Wc(e,t){let r=(0,ll.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,rt.rawFromNode)((0,ll.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function cP(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Sg(e,t){var r;let n=cP(e,"Titles")[0];if(!n)return"";let o=cP(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function pj(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function jc(e){return e.a.length===0&&e.c.length===0}function fj(e,t){return e.some(([r])=>r===t)}function Hc(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Ng(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function mj(e,t){let r=hj(t);return e.filter(([n])=>!sj.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function hj(e){switch(e){case"Entity":return new Set(["Entity"]);case"URL":return new Set(["Url"]);case"DashBoard":return new Set(["DefaultDashboard","Url"]);case"CustomPage":return new Set(["Page"]);case"GenPage":return new Set(["GenPageId"]);default:return new Set}}function gj(e,t){var r,n,i,o,a;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(o=t.page)!==null&&o!==void 0?o:""]);break;case"GenPage":e.push(["GenPageId",(a=t.genPageId)!==null&&a!==void 0?a:""]);break;default:break}}function Dg(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=vj(e[i],t,n),o}return r?[yj(t,n),...e]:e}function vj(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&bj(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,rt.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(gP(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function yj(e,t){return{n:"Titles",a:[],c:[gP(e,t)]}}function gP(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function bj(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function wj(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Qc(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${wj(8)}`)}function _g(e){var t;Qc(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])vP(r)}function vP(e){var t;Qc(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Qc(r,"subarea")}function Aj(e=pP.DEFAULT_LCID){return{adapter:new Jc(e),api:dP.appApi,languageSensitive:!0,publish:(t,r)=>(0,ij.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}Ni.appRegistration=Aj});var bP={};gn(bP,{ActionType:()=>Tg,AppActionOrigin:()=>Mg,AppActionVisibilityType:()=>Fg,ButtonType:()=>Rg,CannotUpdateAppActionColumns:()=>Ej,Context:()=>xg,IconType:()=>Pg,Location:()=>Og,OnClickEventType:()=>kg,Scope:()=>Lg,VisibilityType:()=>Ig});var Ig,Tg,Pg,Rg,Og,xg,Lg,kg,Fg,Mg,Ej,wP=R(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Ig||(Ig={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Tg||(Tg={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Pg||(Pg={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Rg||(Rg={}));(function(e){e[e.Form=0]="Form",e[e.HomePageGrid=1]="HomePageGrid",e[e.SubGridStandard=2]="SubGridStandard",e[e.SubGridAssociated=3]="SubGridAssociated",e[e.QuickForm=4]="QuickForm",e[e.Global=5]="Global",e[e.Dashboard=6]="Dashboard"})(Og||(Og={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(xg||(xg={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Lg||(Lg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(kg||(kg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Fg||(Fg={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Mg||(Mg={}));Ej=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var SP=b(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.commandApi=void 0;var AP=Rt(),Lr=be(),CP=re(),gr=ae(),Cj="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Xc(e,t){let r=`/EntityDefinitions(LogicalName='${(0,gr.odataPathLiteral)(t)}')${(0,gr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,gr.normalizeGuid)(o,"entityMetadataId"):""}Yc.commandApi={async get(e,t){let r=t,n=await Xc(e,r),i=n?`_contextentity_value eq ${n}`:`contextvalue eq '${(0,gr.odataLiteral)(r)}'`,o=`/appactions${(0,gr.odataQuery)([["$expand",Cj],["$filter",i]])}`,a,s=await(0,AP.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let p=c["@odata.etag"];u[(0,gr.normalizeGuid)(d,"appactionid")]=typeof p=="string"?p:null}}return{raw:l,etag:a?(0,Lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t){let r=t,n=r.entityMetadataId||await Xc(e,r.entityLogicalName);return EP(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){let o=r,a=o.entityMetadataId||await Xc(e,o.entityLogicalName);return EP(e,{...o,entityMetadataId:a},!0,i)},async delete(e,t){let r=await Xc(e,t),n=r?`_contextentity_value eq ${r}`:`contextvalue eq '${(0,gr.odataLiteral)(t)}'`,i=`/appactions${(0,gr.odataQuery)([["$select","appactionid"],["$filter",n]])}`,o=await(0,AP.collectPages)(e,i,"deleteArtifact('command')");for(let a of o)a.appactionid&&await(0,Lr.deleteRecord)(e,"appactions",a.appactionid)}};async function EP(e,t,r,n){let i=t.entityMetadataId?(0,gr.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",o=Nj(t.rows),a={};try{await Sj(e,t,o,i,r,n,a)}catch(s){throw(0,CP.withPartialTokens)(s,{memberEtags:a})}return{id:t.entityLogicalName,etag:null,memberEtags:a}}async function Sj(e,t,r,n,i,o,a){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,gr.normalizeGuid)(c.appactionid,"id"),p=(s=o?.[d])!==null&&s!==void 0?s:c.etag,f=(0,Lr.echoWrite)("appactionid",p?{"If-Match":p}:void 0),m=`/appactions(${d})${f.query}`,h=(0,Lr.ensureSuccess)(await e.patch(m,c.body,f.options),e.apiUrl(m));a[d]=(0,Lr.readEtag)(h)}else{let d=(0,Lr.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};if(f["[email protected]"]===void 0){if(!n)throw new CP.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${c.appactionid}' for entity '${t.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);f["[email protected]"]=`/entities(${n})`}let m=(0,Lr.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),h=(0,Lr.readCreatedId)(m,"appactionid");h&&(a[(0,gr.normalizeGuid)(h,"appactionid")]=(0,Lr.readEtag)(m))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,gr.normalizeGuid)(c,"id");await(0,Lr.deleteRecord)(e,"appactions",d,(u=o?.[d])!==null&&u!==void 0?u:void 0),delete a[d]}}function Nj(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var MP=b(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.commandRegistration=Oa.CommandAdapter=void 0;var Ue=(wP(),$r(bP)),NP=nr(),vr=Nr(),Dj=SP(),_j=lt(),xa=ae(),Ug="$ClientSvg:",qg=".svg",Ij=2,Tj=1,Pj=1,IP="entityMetadataId",Rj=new Set(["@odata.etag","IconWebResourceId","OnClickEventJavaScriptWebResourceId","VisibilityFormulaComponentLibraryId","OnClickEventFormulaComponentLibraryId","ContextEntity","_appmoduleid_value","_contextentity_value","_createdby_value","_createdonbehalfby_value","_iconwebresourceid_value","_modifiedby_value","_modifiedonbehalfby_value","_onclickeventformulacomponentlibraryid_value","_onclickeventjavascriptwebresourceid_value","_organizationid_value","_parentappactionid_value","_visibilityformulacomponentlibraryid_value","createdon","modifiedon","overriddencreatedon","overwritetime","componentstate","componentidunique","solutionid","ismanaged","iscustomizable","versionnumber","importsequencenumber","timezoneruleversionnumber","utcconversiontimezonecode","statecode","statuscode","scope"]),Zc=class{toArtifact(t){var r,n,i,o,a,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let f of l){let m=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(f),c.set(m,h)}let d=new Map;for(let f of(o=c.get(""))!==null&&o!==void 0?o:[]){let m=Fj(f.location),h=(a=d.get(m))!==null&&a!==void 0?a:[];h.push(f),d.set(m,h)}let p=[];for(let[f,m]of d)p.push({location:f,groups:xj(m,c,xP(f),u)});return{id:u,entityLogicalName:u,commandBars:kj(p),bag:{a:[[IP,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Gg(t),appActions:Bg(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Bg(r).map(l=>l.appactionid):[]),i=Bg(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Kj(l.row):FP(l.row)}}),s=[...n].filter(l=>!o.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Gg(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,_j.assignMissingIds)(t)}validate(t){let r=[];return(0,vr.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,vr.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,vr.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;TP(l.bag)||((0,vr.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),PP((0,vr.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Oa.CommandAdapter=Zc;function TP(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function PP(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;TP(n.bag)||(0,vr.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,vr.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,vr.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,vr.isJsonObject)(n.action)?(0,vr.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,vr.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,vr.childObjects)(n,"children",o,"control",r);s.length>0&&PP(s,`${o}/children`,r)})}function Vg(e){return{a:Object.entries(e)}}function Oj(e){return Object.fromEntries(e.a)}function ed(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Gg(e){let t=ed(e.bag,IP);return typeof t=="string"?t:""}function xj(e,t,r,n){var i,o;let a=[],s=[];for(let l of rd(e))l.type===Ue.ButtonType.Group?a.push({id:OP(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:rd((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>td(u,t,r,n)),bag:Vg(l)}):s.push(td(l,t,r,n));return s.length>0&&a.unshift({id:Hj(n,r),title:"",controls:s}),a}function zg(e){let t=e.bag?ed(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function td(e,t,r,n){var i,o,a,s,l;let u=OP(e.name,n),c={id:u,type:Mj(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Vg(e)},d=RP(e);d&&(c.icon=d);let p=Lj(e);p&&(c.action=p),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let f=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(f&&f.length>0){let m=[],h=[];for(let g of rd(f))if(g.type===Ue.ButtonType.Group){let y=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Vg(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of rd((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let T=td(S,t,r,n);m.push(T),C.push(zg(T))}h.push({id:y,bag:w,childIds:C})}else m.push(td(g,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function RP(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Ug)?e.fonticon.slice(Ug.length)+qg:e.fonticon}function Lj(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function DP(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function rd(e){return[...e].sort((t,r)=>DP(t)-DP(r))}function kj(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function OP(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let r=e.split("!");return r.length===2?r[1]:e}function Fj(e){switch(e){case Ue.Location.Form:case Ue.Location.QuickForm:return"MainTab";case Ue.Location.HomePageGrid:case Ue.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function xP(e){switch(e){case"MainTab":return Ue.Location.Form;case"HomeTab":return Ue.Location.HomePageGrid;default:return Ue.Location.SubGridStandard}}function Mj(e){switch(e){case Ue.ButtonType.Dropdown:return"FlyoutAnchor";case Ue.ButtonType.Split:return"SplitButton";default:return"Button"}}function Bj(e){switch(e){case"FlyoutAnchor":return Ue.ButtonType.Dropdown;case"SplitButton":return Ue.ButtonType.Split;default:return Ue.ButtonType.Standard}}function $j(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function LP(e,t){var r,n,i;return((n=(r=e.bag)===null||r===void 0?void 0:r.a.length)!==null&&n!==void 0?n:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function Bg(e,t=new Set){var r,n,i,o;let a=[],s=Gg(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=xP(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var m;return(m=f.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(f=>!LP(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if($j(f)){let h=qj(f,u,void 0,e,s);a.push(h),m=h.appactionid}for(let h of(o=f.controls)!==null&&o!==void 0?o:[])kP(h,u,m,e,s,a,d?p:void 0,t),p+=1}}return a}function kP(e,t,r,n,i,o,a,s=new Set){var l;let u=Uj(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!LP(h,s)),p=(h,g,y)=>{kP(h,t,g,n,i,o,d?y:void 0,s)},f=e.flyoutGroups;if(f&&f.length>0){let h=new Map(c.map(S=>[zg(S),S])),g=new Set,y=0,w;for(let[S,T]of f.entries()){let O=T.id||(S===0?$g(u.appactionid):jg("flyout-group",`${u.appactionid}#${S}`)),k=_P(O,t,u.appactionid,n,i,T.bag);o.push(k);let F=k.appactionid;w===void 0&&(w=F);for(let P of T.childIds){let q=h.get(P);!q||g.has(P)||(g.add(P),p(q,F,y),y+=1)}}let C=w??$g(u.appactionid);for(let S of c){let T=zg(S);g.has(T)||(g.add(T),p(S,C,y),y+=1)}return}let m=e.flyoutGroupId||$g(u.appactionid);o.push(_P(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())p(g,m,h)}function Uj(e,t,r,n,i,o){let a=Wg(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=RP(s);return e.location!==void 0&&(s.location=e.location),s.type=Bj(e.type),s.buttonlabeltext=e.label,Gj(s,e.icon,l),Wj(s,e.action),zj(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function qj(e,t,r,n,i){let o=Wg(e,t,r,n,i);return o.row.type=Ue.ButtonType.Group,o.row.grouptitle=e.title,o}function _P(e,t,r,n,i,o){let a=Wg({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,xa.normalizeGuid)(r,"Command flyout group id")})`,s.type=Ue.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Wg(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Oj(e.bag),a=!0;let u=ed(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=ed(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,o=Vj(l,t,n,i),a=!1,s=null;return r?o["[email protected]"]=`/appactions(${(0,xa.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==Ue.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Vj(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Ue.Context.Entity,contextvalue:r.entityLogicalName,scope:Ue.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,xa.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Gj(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,xa.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(qg)?Ug+t.slice(0,t.length-qg.length):t,e.IconWebResourceId=null}function zj(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,xa.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Tj&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Pj)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Wj(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Ij,t.webResourceId){let r=(0,xa.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function jj(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function jg(e,t){let r="";for(let n=0;n<4;n+=1)r+=jj(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function $g(e){return jg("flyout-group",e)}function Hj(e,t){return jg("loose-group",`${e}|${t}`)}function FP(e){let t={...e};for(let r of Rj)delete t[r];return t}function Kj(e){let t=FP(e);for(let r of Ue.CannotUpdateAppActionColumns)delete t[r];return t}function Jj(){return{adapter:new Zc,api:Dj.commandApi,publish:(e,t,r)=>(0,NP.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,NP.boundEntityPublishScope)(t)}}Oa.commandRegistration=Jj});var BP=b(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.chartApi=void 0;var Qj=Rt(),Zt=be(),La=ae(),Xj="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Yj="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";nd.chartApi={async get(e,t){let r=(0,La.normalizeGuid)(t,"id"),n=await(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,La.odataQuery)([["$select",Xj]]);return{raw:(0,Zt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",(0,La.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueryvisualizations${(0,La.odataQuery)([["$select",Yj],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,La.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Qj.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Zt.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Zt.ensureSuccess)(await e.post(o,(0,Zt.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,Zt.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Zt.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,La.normalizeGuid)(t,"id"),a=(0,Zt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Zt.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Zt.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,Zt.readEtag)(l)}},delete(e,t){return(0,Zt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var rR=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.chartRegistration=Fa.ChartAdapter=void 0;var Hg=ri(),$P=Nr(),sn=oi(),UP=nr(),Zj=BP(),Kg=ii(),eH=lt(),tH=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],rH=new Map(tH.map(e=>[e.toLowerCase(),e]));function WP(e){var t;return e&&(t=rH.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function nH(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function iH(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${ka(h.series.attribute)}" aggregate="${ka(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${ka(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${ka(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let y=u.get(h);y?y.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${ka(h)}">${g.join("")}</link-entity>`).join(""),p=l.join("")+d,f=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${ka(n)}">${p}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${f}</category></categorycollection></datadefinition>`}var id=class{toArtifact(t){var r,n,i,o,a,s,l;(0,Kg.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,sn.parseXmlRoot)(u,"<datadefinition/>"),p=(0,sn.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:jP(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:JP(d),categories:QP(d),presentation:HP(p),dataBag:u?(0,sn.projectElementBag)(d):void 0,presentationBag:c?(0,sn.projectElementBag)(p):void 0,rowBag:oH(t.charttype,t.type)}}fromArtifact(t){(0,Kg.installDomShim)();let{datadescription:r,presentationdescription:n}=aH(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:qP(t.rowBag,"charttype"),type:qP(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,Kg.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,eH.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,$P.childObjects)(n,"series","","series",r),(0,$P.childObjects)(n,"categories","","category",r),r}};Fa.ChartAdapter=id;function oH(e,t){let r=[];return e!==void 0&&r.push(["charttype",String(e)]),t!==void 0&&r.push(["type",String(t)]),r.length>0?{a:r,c:[]}:void 0}function qP(e,t){if(!e)return;let r=e.a.find(([i])=>i===t);if(!r)return;let n=parseInt(r[1],10);return Number.isNaN(n)?void 0:n}function jP(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return WP(t[r].getAttribute("ChartType"));return"Column"}function HP(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function od(e){return e.getElementsByTagName("fetch")[0]}function KP(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function JP(e){let t=od(e);if(!t)return[];let r=KP(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=WP(c));let d=a.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=r.get(p);f&&(u.relatedEntity=f),i.push(u)}return i}function QP(e){var t;let r=od(e);if(!r)return[];let n=KP(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=n.get(p);f&&(u.relatedEntity=f),o.push(u)}return o}function aH(e){if(!VP(e.dataBag)||!VP(e.presentationBag)){let o=iH(e);return{datadescription:o,presentationdescription:NH(e,o)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=GP(e.dataBag,"datadefinition",t),n=GP(e.presentationBag,"Chart",t),i=JP(r);if(!Jg(e.series,i)){let o=Qg(r);sH(t,r,e.series);let a=Qg(r),s=a.length>0?a:e.series.map(()=>"");XP(t,n,s,o,e.chartType)}return Jg(e.categories,QP(r))||lH(t,r,e.categories),e.chartType!==jP(n)&&eR(n,e.chartType),Jg(e.presentation,HP(n))||tR(n,e.presentation),{datadescription:(0,sn.serializeNode)(r),presentationdescription:(0,sn.serializeNode)(n)}}function VP(e){return!!e&&(e.c.length>0||e.a.length>0)}function XP(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,p)=>{let f=s[p];if(!f)return;let m=u.get(d);m?m.push(f):u.set(d,[f])});let c=r.map(d=>{let p=u.get(d),f=p&&p.length>0?p.shift():void 0;if(f)return f;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function Qg(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function GP(e,t,r){let n={n:t,a:(0,Hg.mergeAttrs)(e.a,[]),c:(0,Hg.spliceChildren)(e.c,[])};return(0,Hg.rebuildRaw)(n,(0,sn.domEngine)(r),null)}function sH(e,t,r){let n=od(t),i=n?.getElementsByTagName("entity")[0];!n||!i||YP(e,t,i,hH(n),r,vH,{aliasPrefix:"aggregate_column",addRef:dH,removeRef:mH})}function lH(e,t,r){let n=od(t),i=n?.getElementsByTagName("entity")[0];!n||!i||YP(e,t,i,gH(n),r,yH,{aliasPrefix:"groupby_column",addRef:pH,removeRef:fH})}function YP(e,t,r,n,i,o,a){let s=new Map;for(let f of n){let m=f.getAttribute("alias");m&&s.set(m,f)}let l=new Set,u=[],c=(f,m)=>{var h;let g=bH(r,f),y=m.relatedEntity;(g??void 0)!==(y??void 0)&&((h=f.parentNode)===null||h===void 0||h.removeChild(f),zP(e,r,f,y))};for(let f of i){let m=f.alias?s.get(f.alias):void 0;m&&!l.has(m)?(o(m,f),c(m,f),l.add(m)):u.push(f)}let d=n.filter(f=>!l.has(f)),p=0;for(let f of u)if(p<d.length){let m=d[p];o(m,f),c(m,f),l.add(m),p+=1}else{let m=e.createElement("attribute"),h=f.alias||cH(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,f),zP(e,r,m,f.relatedEntity),a.addRef(e,t,h)}for(let f of n)if(!l.has(f)){let m=f.getAttribute("alias");m&&a.removeRef(t,m),AH(f)}}function uH(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function cH(e,t){let r=uH(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function ZP(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function dH(e,t,r){let n=ZP(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function pH(e,t,r){let n=ZP(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function fH(e,t){let r=e.getElementsByTagName("category");for(let n=0;n<r.length;n+=1)r[n].getAttribute("alias")===t&&r[n].removeAttribute("alias")}function mH(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!CH(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function hH(e){let t=[],r=e.getElementsByTagName("attribute");for(let n=0;n<r.length;n+=1)r[n].getAttribute("aggregate")&&t.push(r[n]);return t}function gH(e){var t;let r=[],n=e.getElementsByTagName("attribute");for(let i=0;i<n.length;i+=1)((t=n[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&r.push(n[i]);return r}function vH(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function yH(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.getAttribute("dategrouping")!==null&&e.removeAttribute("dategrouping")}function bH(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function zP(e,t,r,n){n?wH(e,t,n).appendChild(r):t.appendChild(r)}function wH(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function AH(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!EH(t))){let r=t.parentNode;r&&r.removeChild(t)}}function EH(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1){let i=n.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function CH(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function eR(e,t){let r=e.getElementsByTagName("Series"),n=!1;for(let i=0;i<r.length;i+=1)r[i].getAttribute("ChartType")&&(r[i].setAttribute("ChartType",t),n=!0);if(!n){for(let i=0;i<r.length;i+=1)if(!SH(r[i])){r[i].setAttribute("ChartType",t);return}}}function SH(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName==="Series")return!0}return!1}function tR(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],o=e.getElementsByTagName("Legends");for(let a=0;a<o.length;a+=1)i.push(o[a]);if(t.showLegend&&i.length===0){let a=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),a.appendChild(s),e.appendChild(a)}else if(!t.showLegend)for(let a of i)(r=a.parentNode)===null||r===void 0||r.removeChild(a)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function NH(e,t){let r=(0,sn.parseXmlRoot)(nH(),"<Chart/>");eR(r,e.chartType),tR(r,e.presentation);let n=Qg((0,sn.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&XP(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,sn.serializeNode)(r)}function Jg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ka(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function DH(){return{adapter:new id,api:Zj.chartApi,publish:(e,t,r)=>(0,UP.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,UP.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Fa.chartRegistration=DH});var aR=b(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.dashboardApi=Ba.dashboardEntity=void 0;var _H=Rt(),Di=be(),Ma=ae(),nR=cf();function iR(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ba.dashboardEntity=iR;var oR="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",IH={select:oR,required:["name","type","objecttypecode","istabletenabled"]},TH="formid,name,type,objecttypecode",PH=0,RH=10;Ba.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Ma.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ma.odataQuery)([["$select",oR]]),i=(0,Di.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Di.readEtag)(i)}},async list(e,t){let r=[`(type eq ${PH} or type eq ${RH})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Ma.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Ma.odataQuery)([["$select",TH],["$filter",r.join(" and ")]])}`;return(await(0,_H.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=iR(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Di.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Di.ensureSuccess)(await e.post(o,(0,Di.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Di.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Di.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,nR.patchSystemForm)(e,(0,Ma.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,IH)},readToken(e,t){return(0,nR.readSystemFormContentEtag)(e,(0,Ma.normalizeGuid)(t,"id"))},delete(e,t){return(0,Di.deleteRecord)(e,"systemforms",t)}}});var bR=b(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.dashboardRegistration=ln.TILE_CLASS_ID=ln.DashboardAdapter=void 0;var cl=ri(),yr=oi(),Xg=nr(),ul=Nr(),pR=aR(),Yg=ii(),so=lt(),fR=ae(),mR=Li(),OH=Sh(),sR="0",Zg="10",xH=new Map([["{E7A81278-8635-4D9E-8D4D-59480B391C5B}","chart"],["{FD2A7985-3187-444E-908D-6624B21F69C0}","iframe"],["{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}","webresource"],["{EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8}","stream"],["{06375649-C143-495E-A496-C962E5B4488E}","timeline"],["{8C54228C-1B25-4909-A12A-F2B968BB0D62}","powerbi"],["{F9A8A302-114E-466A-B582-6771B2AE0D92}","assistant"]]),LH="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",sd=class{constructor(t=mR.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,Yg.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,yr.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:kH(t.type),entityLogicalName:(a=(0,pR.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:FH(l),components:lR(l,this.lcid),bag:(0,yr.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Yg.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Zg:sR,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:uR(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,OH.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:uR(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Zg:sR,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,Yg.installDomShim)();let c=(0,yr.parseXmlRoot)(JH(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,so.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:lR(c,this.lcid),bag:(0,yr.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let r=t;(typeof r.id!="string"||r.id.length===0)&&(r.id=(0,so.newId)())}return t}validate(t){let r=[],n=(0,ul.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,ul.isJsonObject)(u)&&r.push((0,ul.issue)(`${s}/${l}`,`component-${l}-must-be-object`,`a component ${l} must be a JSON object when present, got ${u===null?"null":typeof u}`))}if((0,ul.isJsonObject)(o.position)){let l=dl(o.position);i.has(l)?r.push((0,ul.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ln.DashboardAdapter=sd;function kH(e){return String(e??"")===Zg?"Interactive":"Standard"}function FH(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ee(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function lR(e,t){let r=[];return ee(e,"tabs").flatMap(i=>ee(i,"tab")).forEach((i,o)=>{ee(i,"columns").flatMap(s=>ee(s,"column")).forEach((s,l)=>{ee(s,"sections").flatMap(c=>ee(c,"section")).forEach((c,d)=>{MH(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function MH(e,t,r,n){ee(e,"rows").flatMap(o=>ee(o,"row")).forEach((o,a)=>{ee(o,"cell").forEach((s,l)=>{let u=BH(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function BH(e,t,r){var n,i;let o=vR((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ee(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=qH(a),u=VH(s,l,a),c=$H(a);return{id:a.getAttribute("id")||o,type:u,name:gR(e,r),classId:s,position:t,colspan:e0(e,"colspan",1),rowspan:e0(e,"rowspan",1),parameters:l,bag:(0,yr.projectElementBag)(e),...c?{icProperties:c}:{}}}function hR(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName.toLowerCase()==="icproperties")return n}}function $H(e){let t=hR(e);return t?(0,yr.serializeNode)(t):void 0}function UH(e,t,r){let n=hR(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,cl.rebuildRaw)((0,cl.rawFromNode)((0,yr.nodeLikeFromDom)(i)),(0,yr.domEngine)(e),null);n&&(0,yr.serializeNode)(n)===(0,yr.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function gR(e,t){var r,n;let i=ee(e,"labels")[0];if(!i)return"";let o=ee(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function qH(e){var t;let r={},n=ee(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function VH(e,t,r){var n;let i=xH.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===LH?"assistant":i:"unknown"}function e0(e,t,r){var n;let i=parseInt((n=e.getAttribute(t))!==null&&n!==void 0?n:"",10);return Number.isNaN(i)?r:i}function vR(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function GH(e,t){let r={n:"form",a:(0,cl.mergeAttrs)(e.bag.a,[]),c:(0,cl.spliceChildren)(e.bag.c,[])};return(0,cl.rebuildRaw)(r,(0,yr.domEngine)(t),null)}function uR(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=GH(e,r);return jH(r,n,e.components,t),zH(r,n,e.components,t),(0,yr.serializeNode)(n)}function zH(e,t,r,n){let i=yR(t);for(let o of r)i.has(dl(o.position))||WH(e,t,o,n)}function WH(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=QH(t,e,l);for(let q of ee(u,"row"))ee(q,"cell").some(V=>ee(V,"control").length>0)||u.removeChild(q);let c=r.classId||ln.TILE_CLASS_ID[r.type]||ln.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&cR(r.bag,"id")?String(cR(r.bag,"id")):ad((0,so.newId)()),f=r.id?ad(r.id):ad((0,so.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),y=ee(u,"row"),w=y[y.length-1],C=w?ee(w,"cell").reduce((q,V)=>q+e0(V,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",p),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let T=e.createElement("labels"),O=e.createElement("label");O.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),O.setAttribute("languagecode",String(n)),T.appendChild(O),S.appendChild(T);let k=e.createElement("control");k.setAttribute("id",f),k.setAttribute("classid",ad(c));let F=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let q of Object.keys(P)){let V=(0,fR.createSafeXmlElement)(e,q,"dashboard tile parameter");V.textContent=P[q],F.appendChild(V)}k.appendChild(F),S.appendChild(k),w.appendChild(S)}function cR(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function jH(e,t,r,n){var i;let o=yR(t),a=new Set(r.map(s=>dl(s.position)));for(let s of r){let l=o.get(dl(s.position));if(!l)continue;let u=ee(l,"control")[0];u&&(HH(e,l,s.name,n),KH(e,u,s.parameters),dR(l,"colspan",s.colspan),dR(l,"rowspan",s.rowspan),s.icProperties!==void 0&&UH(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function yR(e){let t=new Map;return ee(e,"tabs").flatMap(n=>ee(n,"tab")).forEach((n,i)=>{ee(n,"columns").flatMap(a=>ee(a,"column")).forEach((a,s)=>{ee(a,"sections").flatMap(u=>ee(u,"section")).forEach((u,c)=>{ee(u,"rows").flatMap(p=>ee(p,"row")).forEach((p,f)=>{ee(p,"cell").forEach((m,h)=>{var g;vR((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ee(m,"control")[0]&&t.set(dl({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:h}),m)})})})})}),t}function dl(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function HH(e,t,r,n){if(r===gR(t,n))return;let i=ee(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ee(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function KH(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ee(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,fR.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function dR(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function JH(e=2){let t=`{${(0,so.newId)()}}`,r=`{${(0,so.newId)()}}`,n=`{${(0,so.newId)()}}`,i=Math.max(1,Math.floor(e));return`<form><tabs><tab id="${t}" name="General" showlabel="true" expanded="true" verticallayout="true"><columns><column width="100%"><sections><section id="${r}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${n}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}ln.TILE_CLASS_ID={chart:"E7A81278-8635-4D9E-8D4D-59480B391C5B",list:"E7A81278-8635-4D9E-8D4D-59480B391C5B",iframe:"FD2A7985-3187-444E-908D-6624B21F69C0",webresource:"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"};function ad(e){return`{${e.replace(/[{}]/g,"")}}`}function QH(e,t,r){var n;let i=ee(e,"tabs").flatMap(u=>ee(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ee(i,"columns").flatMap(u=>ee(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ee(o,"sections").flatMap(u=>ee(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ee(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function XH(e=mR.DEFAULT_LCID){return{adapter:new sd(e),api:pR.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Xg.publishBoundEntity)(t,n):(0,Xg.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Xg.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ln.dashboardRegistration=XH});var LR=b(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});cd.genPageApi=void 0;var ud=Rt(),TR=ql(),_e=be(),se=ae(),kr=bu(),ke=re(),PR=lt();function YH(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var un="uxagentprojects",uo="uxagentprojectfiles",ml="agentconversationmessages",hl="uxagentprojectid",Dt="uxagentprojectfileid",co="agentconversationmessageid",pl=`${hl},name`,ZH=`${Dt},filename,filetype`,RR=2e8,OR=200000001,po={"MSCRM.IncludeUnpublished":"true"},t0={};function lo(e,t){return{"MSCRM.VersioningChangeset":e,...po,...t}}async function n0(e,t,r,n){var i;let o=`/${t}(${r})`+(0,se.odataQuery)([["$select",n]]),a=(0,_e.ensureSuccess)(await e.get(o,{headers:{...po}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,_e.readEtag)(a)}}async function ld(e,t,r=po){let n=`/${uo}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,_e.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=YH(o);if(a)return{status:"available",data:(0,kr.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,kr.utf8ToBase64)(o)};throw new ke.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function xR(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function eK(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${uo}(${t})/filecontent`,s=(0,kr.base64ToBytes)(n);(0,se.assertNoControlChars)(r,"generative-page file name"),(0,_e.ensureSuccess)(await e.patchRaw(a,s,{headers:lo(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":xR(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function fl(e,t,r=po){let n=`/${uo}`+(0,se.odataQuery)([["$select",ZH],["$filter",`_${hl}_value eq ${t}`]]);return(await(0,ud.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function r0(e,t){let r=`/${ml}`+(0,se.odataQuery)([["$select",`${co},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,ud.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...po}})}async function wR(e,t){var r,n,i;let{row:o,etag:a}=await n0(e,un,t,pl),s=new Map;for(let{row:l,etag:u}of await fl(e,t))s.set((0,se.normalizeGuid)(String((r=l[Dt])!==null&&r!==void 0?r:""),Dt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function AR(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,se.normalizeGuid)(c.id,"file id");u.add(d);let p=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new ke.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!p)throw new ke.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}p&&c.unchanged||(p?(p.filename!==c.name||p.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:p!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function o0(e){let t=(0,kr.base64ToUtf8)(e);return(0,kr.utf8ToBase64)(t)===(0,kr.bytesToBase64)((0,kr.base64ToBytes)(e))?t:void 0}function tK(e,t,r,n){var i,o,a,s,l,u,c,d;let p=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[co]:(0,se.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${un}(${e})`,message:t.message,messagecontext:JSON.stringify(p),messagesender:t.sender==="user"?RR:OR}}async function rK(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(p=>p.id).filter(p=>typeof p=="string"&&p!=="").map(p=>(0,se.normalizeGuid)(p,"message id"));if(s.length===0)return r;let l=`/${ml}`+(0,se.odataQuery)([["$select",`${co},message,messagesender,_regardingobjectid_value`],["$filter",s.map(p=>`${co} eq ${p}`).join(" or ")]]),u=await(0,ud.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...po}});if(u.length===0)return r;let c=new Map(u.map(p=>{var f;return[String((f=p[co])!==null&&f!==void 0?f:"").toLowerCase(),p]})),d=[];for(let p of(i=r.messages)!==null&&i!==void 0?i:[]){let f=p.id?c.get((0,se.normalizeGuid)(p.id,"message id")):void 0;if(!f){d.push(p);continue}if(!(String((o=f.message)!==null&&o!==void 0?o:"")===p.message&&Number(f.messagesender)===(p.sender==="user"?RR:OR)&&String((a=f._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new ke.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${p.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function i0(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${un}`,body:(0,_e.withClientMintedId)({name:t.name},hl,e),headers:lo(n)};case"createRow":return{method:"POST",path:`/${uo}`,body:(0,_e.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${hl}@odata.bind`]:`/${un}(${e})`},Dt,(0,se.normalizeGuid)(t.file.id,"file id")),headers:lo(n)};case"renameRow":return{method:"PATCH",path:`/${uo}(${(0,se.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:lo(n,{"If-Match":"*"})};case"content":{let i=o0(t.data);if(i===void 0)throw new ke.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,se.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${uo}(${(0,se.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:lo(n,{"x-ms-file-name":xR(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${uo}(${t.fileId})`,headers:lo(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${un}(${e})`,body:{name:t.name},headers:lo(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${ml}`,body:tK(e,t.turn,r,n)};default:{let i=t;throw new ke.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function ER(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||o0(r.data)!==void 0)}async function CR(e,t,r,n,i){await(0,TR.postChangeSet)(e,r.map(o=>i0(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function SR(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await eK(e,(0,se.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=i0(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,_e.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>i0(t,l,n,i));if(e.supportsAtomicBatch)await(0,TR.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,_e.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function NR(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await wR(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,se.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let T=u.rows.get(C);T&&(T.filename!==S.name||T.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${T.filename}' (type ${T.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await ld(e,(0,se.normalizeGuid)(C.file.id,"file id")),T=(0,kr.bytesToBase64)((0,kr.base64ToBytes)(C.data));(S.status!=="available"||S.data!==T)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,kr.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,kr.base64ToBytes)(T).byteLength} written`:`file '${C.file.name}' holds no content`)}let p=new Set(r.filter(C=>C.kind==="content").map(C=>(0,se.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!p.has(C)&&(await ld(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let f=await wR(e,t),m=[...f.rows.keys()],h=f.etag!==u.etag||f.rows.size!==u.rows.size||m.some(C=>{var S,T;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((T=f.rows.get(C))===null||T===void 0?void 0:T.etag)}),g=m.length!==i.size||m.some(C=>!i.has(C)),y={},w=[];for(let[C,S]of f.rows){let T=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;y[C]=T,T!==S.etag&&w.push(S.filename)}return h||g||!f.etag||Object.values(y).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):nK({id:t,etag:f.etag,memberEtags:y},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}cd.genPageApi={async get(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),{row:i,etag:o}=await n0(e,un,n,pl),a=await fl(e,n),s={},l=[];for(let{row:c,etag:d}of a){let p=(0,se.normalizeGuid)(String((r=c[Dt])!==null&&r!==void 0?r:""),Dt);s[p]=d;let f=await ld(e,p);l.push({...c,content:f})}let u=await r0(e,n);return{raw:{project:i,files:l,conversation:u},etag:o,memberEtags:s}},async getPublished(e,t){var r,n;let i=(0,se.normalizeGuid)(t,"id"),o=`/${un}(${i})`+(0,se.odataQuery)([["$select",pl]]),a=await e.get(o);if(a.status===404)return null;(0,_e.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await fl(e,i,t0);for(let{row:g,etag:y}of c){let w=(0,se.normalizeGuid)(String((n=g[Dt])!==null&&n!==void 0?n:""),Dt);l[w]=y,u.push({...g,content:await ld(e,w,t0)})}let d=g=>g.map(({row:y,etag:w})=>`${String(y[Dt])}@${String(w)}`).sort().join("|"),p=()=>new ke.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),f=await e.get(o);if(f.status===404)throw p();(0,_e.ensureSuccess)(f,e.apiUrl(o));let m=await fl(e,i,t0);if([(0,_e.readEtag)(a),(0,_e.readEtag)(f),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new ke.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,_e.readEtag)(f)!==(0,_e.readEtag)(a)||d(m)!==d(c))throw p();return{raw:{project:s,files:u,conversation:[]},etag:(0,_e.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${un}`+(0,se.odataQuery)([["$select",pl]]);return(await(0,ud.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...po}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[hl])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t;IR(e,i);let o=r?(0,se.normalizeGuid)(r,"id"):(0,PR.newId)();_R(e,o,i);let a=AR(o,i,void 0),s=DR(),l=[],u=!0;ER(e,a)?await CR(e,o,a,i,s):{warnings:l,turnRecorded:u}=await SR(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(p=>(0,se.normalizeGuid)(p.id,"file id"))),d=await NR(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,se.normalizeGuid)(t,"id");IR(e,s);let u=await rK(e,l,s);_R(e,l,u);let c=await fl(e,l),{row:d,etag:p}=await n0(e,un,l,pl);if(n&&p&&n!==p)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${p}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!p)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let f=new Map(c.map(({row:k})=>{var F,P;return[(0,se.normalizeGuid)(String((F=k[Dt])!==null&&F!==void 0?F:""),Dt),{filename:String((P=k.filename)!==null&&P!==void 0?P:""),filetype:Number(k.filetype)}]})),m=new Set(f.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(k=>(0,se.normalizeGuid)(k.id,"file id")));if(!i)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(k=>k.toLowerCase()));for(let k of h)if(!m.has(k)&&g.has(k))throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative-page file '${k}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let k of m)if(!g.has(k))throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative-page file '${k}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let y=new Map(c.map(({row:k,etag:F})=>{var P;return[(0,se.normalizeGuid)(String((P=k[Dt])!==null&&P!==void 0?P:""),Dt),F]}));for(let[k,F]of Object.entries(i)){let P=k.toLowerCase();if(!m.has(P))continue;let q=y.get(P);if(!F||!q)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${F?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(F!==q)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${F}, server ${q}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=AR(l,u,{rows:f,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(w.length===0)return{id:l,etag:p,memberEtags:Object.fromEntries(c.map(({row:k,etag:F})=>{var P;return[(0,se.normalizeGuid)(String((P=k[Dt])!==null&&P!==void 0?P:""),Dt),F]}))};let C=DR(),S=[],T=!0;ER(e,w)?await CR(e,l,w,u,C):{warnings:S,turnRecorded:T}=await SR(e,l,w,u,C);let O=await NR(e,l,w,u,h,y,S);return T?O:{...O,intentPending:!0}},async delete(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),i=await r0(e,n);await(0,_e.deleteRecord)(e,un,n);let o=new Set(i.map(l=>{var u;return String((u=l[co])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await r0(e,n)){let u=String((r=l[co])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,_e.deleteRecord)(e,ml,l)}catch(u){u instanceof ke.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new ke.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${ml} rows regarding '${n}'.`)}};function DR(){return`uxagentproject_${(0,PR.newId)()}`}function nK(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function _R(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new ke.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function IR(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(a=>a.content.status==="available"&&!a.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(a=>a.content.status==="available"&&!a.unchanged&&o0(a.content.data)===void 0)&&!e.supportsBinaryPatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var QR=b(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.genPageRegistration=Ua.GenPageAdapter=void 0;var iK=LR(),oK=nr(),he=Nr(),gd=lt(),vd=bu(),fo=re(),kR=bf(),a0=Ep(),_i=2e8,jR=200000001,Mn={source:{name:"src/pages/page.tsx",fileType:_i},output:{name:"src/pages/page.compiled",fileType:jR},config:{name:"config.json",fileType:_i},prompt:{name:"firstPrompt.json",fileType:_i}},HR=Object.keys(Mn),aK=["dataSources","model","connectorBindings","actionBindings"],sK=["userMessage","agentMessage"],FR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lK={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},uK="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function KR(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let a=0;a<32;a+=1)i.push(parseInt((r=n[a])!==null&&r!==void 0?r:"0",16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>(Number.isNaN(a)?0:a).toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function dd(e,t){return KR(e,lK[t])}function cK(e,t){let r=KR(e,uK),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function MR(e){return typeof e=="string"&&e.trim()!==""?e:(0,gd.newId)()}function Fn(e){return(0,he.isJsonObject)(e)?e:{}}function $a(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function pd(e){return JSON.parse(JSON.stringify(e))}function dK(e){let t=Fn(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function fd(e){if(!e||e.status!=="available")return;let t=(0,vd.base64ToUtf8)(e.data);return(0,vd.utf8ToBase64)(t)===e.data?t:void 0}function md(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,he.isJsonObject)(t)?t:void 0}catch{return}}function BR(e,t){if(t===_i&&e.includes("page.tsx"))return"source";if(t===jR&&e.includes(".compiled"))return"output";if(t===_i&&e===Mn.config.name)return"config";if(t===_i&&e===Mn.prompt.name)return"prompt"}function $R(e){let t=e.toLowerCase();return HR.some(r=>Mn[r].name.toLowerCase()===t)}function s0(e){return Object.fromEntries(e)}function JR(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),s0(i)}function UR(e){var t,r,n;return JR({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},aK,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function qR(e){var t,r;return JR({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},sK,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function VR(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=s0(n)),!0}function GR(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=s0(n)),!0}function vl(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var pK=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function zR(e){return vl(e)?[]:pK.filter(t=>e[t]!==void 0).map(t=>(0,he.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function WR(){return(0,he.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function hd(e){return{status:"available",data:(0,vd.utf8ToBase64)(e)}}function gl(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var yd=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Fn(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var y,w,C;let S=Fn(g);return{id:String((y=S.uxagentprojectfileid)!==null&&y!==void 0?y:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:_i),content:dK(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var y,w;let C=Fn(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((y=C.message)!==null&&y!==void 0?y:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let y=BR(g.name,g.fileType);y?((s.has(y)||g.name!==Mn[y].name)&&(u=!1),s.set(y,g)):($R(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(gl(n,i));let c=gl(n,l),d={rows:{}};for(let[g,y]of s)d.rows[g]=y.id;let p=s.get("source");if(p){let g=fd(p.content);if(g===void 0)return a(gl(n,i));c.source=g}let f=s.get("output");f&&(d.output=f.content);let m=s.get("config");if(m){let g=md(fd(m.content));if(!g||!VR(c,d,g))return a(gl(n,i))}let h=s.get("prompt");if(h){let g=md(fd(h.content));if(!g||!GR(c,d,g))return a(gl(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,p,f,m,h,g,y,w;if(r&&!$a((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new fo.ValidationError("genPage",t.id,[(0,he.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let C=zR(t);if(C.length>0)throw new fo.ValidationError("genPage",t.id,C);let S=[],T=r===void 0,O=T&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(vl(O)){let P=(s=(a=O.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},q=Z=>{var ye;return(ye=P[Z])!==null&&ye!==void 0?ye:dd(O.id,Z)},V=(Z,ye,hn)=>{S.push({id:q(Z),name:Mn[Z].name,fileType:Mn[Z].fileType,content:ye,unchanged:hn})};if(O.source!==void 0){V("source",hd(O.source),!T&&r?.source===O.source&&P.source!==void 0);let Z=!T&&r?.source===O.source&&$a((l=r?.dataSources)!==null&&l!==void 0?l:[],(u=O.dataSources)!==null&&u!==void 0?u:[]),ye=fd((c=O.bag)===null||c===void 0?void 0:c.output);Z&&P.output!==void 0&&(0,kR.isLoadableGenPageOutput)(ye)?V("output",{status:"retain"},!0):V("output",hd(await this.compile(O,O.source,n)),!1)}else{if(P.source!==void 0)throw new fo.ValidationError("genPage",O.id,[WR()]);if(P.output!==void 0){if(!T&&!$a((d=r?.dataSources)!==null&&d!==void 0?d:[],(p=O.dataSources)!==null&&p!==void 0?p:[]))throw new fo.ValidationError("genPage",O.id,[(0,he.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);V("output",{status:"retain"},!0)}}let Ve=UR(O),Pt=!T&&r!==void 0&&$a(UR(r),Ve);(T||P.config!==void 0||!Pt)&&V("config",hd(JSON.stringify(Ve)),Pt&&P.config!==void 0);let Je=qR(O),Ge=!T&&r!==void 0&&$a(qR(r),Je);(P.prompt!==void 0||Object.keys(Je).length>0&&!Ge)&&V("prompt",hd(JSON.stringify(Je)),Ge&&P.prompt!==void 0)}for(let P of(f=O.files)!==null&&f!==void 0?f:[]){let q=(m=r?.files)===null||m===void 0?void 0:m.find(V=>V.id===P.id);S.push({id:P.id,name:P.name,fileType:P.fileType,content:P.content,unchanged:q!==void 0&&$a(q,P)})}let k=[];if(O.newTurn){let P=O.newTurn.id,q=V=>P?{id:cK(P,V)}:{};k.push({...q("user"),sender:"user",message:O.newTurn.prompt}),O.newTurn.agentMessage&&k.push({...q("agent"),sender:"agent",message:O.newTurn.agentMessage})}let F=(g=(h=O.bag)===null||h===void 0?void 0:h.config)!==null&&g!==void 0?g:{};return{name:O.name,files:S,...k.length>0?{messages:k,messageContext:{dataSources:(y=O.dataSources)!==null&&y!==void 0?y:[],model:(w=O.model)!==null&&w!==void 0?w:"",enabledTools:Array.isArray(F.enabledTools)?F.enabledTools:[],configurableTools:Array.isArray(F.configurableTools)?F.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:pd(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!vl(t)&&!t.newTurn)return t;let u=pd(t);if(delete u.newTurn,!vl(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let p=HR.find(m=>Mn[m].name===d.name&&Mn[m].fileType===d.fileType);if(!p||u.files.some(m=>m.id===d.id)||(c.rows[p]=d.id,d.content.status!=="available"))continue;let f=(0,vd.base64ToUtf8)(d.content.data);p==="output"?c.output={status:"available",data:d.content.data}:p==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,VR(u,c,(s=md(f))!==null&&s!==void 0?s:{})):p==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,GR(u,c,(l=md(f))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,he.isJsonObject)(r)||typeof r.id=="string"&&FR.test(r.id)?t:{...t,newTurn:{...r,id:(0,gd.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((p,f)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,p);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,he.issue)(`/dataSources/${f}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${p}' could not be read completely (a choice or lookup request failed), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${p}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new fo.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new fo.ValidationError("genPage",t.id,[(0,he.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,a0.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,a0.buildGenPageLegacyEnums)(a):void 0,d=(0,kR.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new fo.ValidationError("genPage",t.id,d.diagnostics.map(fK));return d.code}metadataNeeds(t){return t.source===void 0||!Array.isArray(t.dataSources)?[]:t.dataSources.filter(r=>typeof r=="string"&&r!=="").map(r=>({entityLogicalName:r,fieldName:"",needsColumnDetail:!0}))}createDefault(t){var r,n;let i=MR(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:MR(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:_i,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=pd(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=pd(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:dd(i,"source"),output:dd(i,"output"),config:dd(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,gd.newId)()};if(!(0,he.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,gd.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,he.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Fn(Fn(n.bag).rows).source!==void 0&&r.push(WR()),r.push(...zR(t)),n.newTurn!==void 0){let s=Fn(n.newTurn);(!(0,he.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,he.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,he.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!FR.test(s.id))&&r.push((0,he.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,he.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!a0.TABLE_LOGICAL_NAME.test(l)?r.push((0,he.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,he.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,he.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,he.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=vl(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Fn(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,he.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,he.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let p=typeof c.name=="string"?c.name:"",f=p.split("/");p===""||/[\u0000-\u001F\u007F]/.test(p)||p.includes("\\")||f.some(g=>g===""||g==="."||g==="..")?r.push((0,he.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${p}'`)):o&&($R(p)||BR(p,Number(c.fileType))!==void 0)&&r.push((0,he.issue)(u+"/name","file-name-reserved",`'${p}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,he.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Fn(m);h.status==="available"?typeof h.data!="string"&&r.push((0,he.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,he.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Ua.GenPageAdapter=yd;function fK(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,he.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,he.issue)("/source",e.rule,`${t}: ${e.message}`)}function mK(){return{adapter:new yd,api:iK.genPageApi,publish:(e,t)=>(0,oK.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Ua.genPageRegistration=mK});var YR=b(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.reconcileBpfSecurityRoles=void 0;var wd=be(),bd=ae(),hK="Global",XR={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function gK(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,bd.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,a=(n=(r=(0,wd.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[],s={},l=new Set;return Object.keys(XR).forEach(u=>{let c=a.find(d=>d.PrivilegeType===XR[u]);if(c){let d=(0,bd.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function vK(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,a=(n=(r=(0,wd.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(a.map(s=>(0,bd.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function yK(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:hK,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,wd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function bK(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,wd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function wK(e,t,r){var n;if(!r||r.length===0)return;let i=await gK(e,t.toLowerCase());for(let o of r){let a=(0,bd.normalizeGuid)(o.roleId,"roleId"),s=new Set(((n=o.access)!==null&&n!==void 0?n:[]).map(p=>i.byAccess[p]).filter(p=>!!p)),l=await vK(e,a),u=new Set([...l].filter(p=>i.all.has(p))),c=[...s].filter(p=>!u.has(p)),d=[...u].filter(p=>!s.has(p));await yK(e,a,c);for(let p of d)await bK(e,a,p)}}Ad.reconcileBpfSecurityRoles=wK});var sO=b(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.bpfApi=void 0;var br=Ti(),AK=Rt(),wr=re(),_t=be(),Bn=ae(),EK=YR(),CK={"Content-Type":"application/json",Accept:"application/json"},Ed={...CK,Prefer:"return=representation"},SK=new Set([408,502,503,504]),NK=`category eq ${br.WorkflowCategory.BusinessProcessFlow} and type eq ${br.WorkflowTypeCode.Definition} and businessprocesstype eq ${br.BusinessProcessType.BusinessFlow}`,DK="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",_K="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",IK=["xaml","name","description","processorder"];async function ZR(e,t){var r;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let n=String((r=t.record.uniquename)!==null&&r!==void 0?r:"");n!==""&&await(0,EK.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function aO(e,t,r){let n={statecode:br.StateCode.Activated,statuscode:br.StatusCode.Activated},i=`/workflows(${t})`,o={...Ed};return r&&(o["If-Match"]=r),(0,_t.ensureSuccess)(await e.patch(i,n,{headers:o}),e.apiUrl(i))}async function eO(e,t,r){return(0,_t.readEtag)(await aO(e,t,r))}function tO(e,t){return new wr.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Sd(e))}async function Cd(e,t){var r;let n=`/workflows(${t})${(0,Bn.odataQuery)([["$select","statecode"]])}`,i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new wr.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function l0(e,t,r){if(await Cd(e,t)!==br.StateCode.Activated)return{deactivated:!1,etag:null};let n={statecode:br.StateCode.Draft,statuscode:br.StatusCode.Draft},i=`/workflows(${t})`,o={...Ed};r&&(o["If-Match"]=r);let a;try{a=await e.patch(i,n,{headers:o})}catch(l){return await rO(e,t,l)}if(SK.has(a.status))return await rO(e,t,new wr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${a.status} from an intermediary, so whether it committed is unknown.`));let s=(0,_t.ensureSuccess)(a,e.apiUrl(i));return{deactivated:!0,etag:(0,_t.readEtag)(s)}}async function rO(e,t,r){let n;try{n=await Cd(e,t)}catch{n=void 0}if(n===br.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===br.StateCode.Activated)throw r;let i=new wr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw i.cause=r,i}async function nO(e,t){let r=(0,Bn.normalizeGuid)(t,"workflowid");try{return await aO(e,r,null),"restored"}catch{try{let n=await Cd(e,r);return n===br.StateCode.Activated?"restored":n===br.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function iO(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,o=r==="disabled"?new wr.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new wr.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${i}`);return o.cause=n,o}async function TK(e,t){try{return await Cd(e,t),"survived"}catch(r){return r instanceof wr.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function PK(e,t,r){if(r)try{let{deactivated:n,etag:i}=await l0(e,t,r),o=n?i:r;if(o)return await(0,_t.deleteRecord)(e,"workflows",t,o),"removed"}catch{}return TK(e,t)}function Sd(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function oO(e,t){return new wr.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Sd(e)}`)}function RK(e,t){let r=new wr.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Sd(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function OK(e,t){let r=new wr.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Sd(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function xK(e,t){let r=new wr.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function LK(e){let t={};for(let r of IK)e[r]!==void 0&&(t[r]=e[r]);return t}Nd.bpfApi={async get(e,t){let n=`/workflows(${(0,Bn.normalizeGuid)(t,"id")})${(0,Bn.odataQuery)([["$select",_K]])}`,i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,_t.readEtag)(i)}},async list(e,t){let r=[NK];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Bn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Bn.odataQuery)([["$select",DK],["$filter",r.join(" and ")]])}`;return(await(0,AK.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,Bn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,_t.ensureSuccess)(await e.post(i,r.record,{headers:Ed}),e.apiUrl(i)),a=(0,_t.readEtag)(o);if(!a)throw oO(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await eO(e,n,a)),await ZR(e,r)}catch(l){let u=await PK(e,n,s);throw u==="survived"?RK(n,l):u==="unknown"?OK(n,l):l instanceof wr.SdkError&&l.code===_t.VERSION_CONFLICT_CODE?xK(n,l):l}if(!s)throw oO(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,Bn.normalizeGuid)(t,"id"),a=(0,_t.requireEtag)(n,"bpf",o),{deactivated:s,etag:l,uncertainCause:u}=await l0(e,o,a);try{if(u!==void 0)throw u;let c=a;if(s){if(!l)throw tO(o,"deactivation");c=l}let d=`/workflows(${o})`,p=(0,_t.ensureSuccess)(await e.patch(d,LK(i.record),{headers:{...Ed,"If-Match":c}}),e.apiUrl(d)),f=(0,_t.readEtag)(p);if(i.status==="Active"){if(!f)throw tO(o,"definition write");f=await eO(e,o,f)}return await ZR(e,i),{id:o,etag:f}}catch(c){if(s){let d=await nO(e,o);if(d!=="restored")throw iO(o,"to apply an edit, the edit failed",d,c)}throw c}},async delete(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),{deactivated:n}=await l0(e,r,null);try{await(0,_t.deleteRecord)(e,"workflows",r)}catch(i){if(n){let o=await nO(e,r);if(o!=="restored")throw iO(r,"so it could be deleted, the delete failed",o,i)}throw i}}}});var zO=b(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.bpfRegistration=Va.BpfAdapter=void 0;var Dd=Ti(),kK=sO(),u0=ri(),mo=oi(),wO=ii(),er=Nr(),jt=lt(),cn=re(),FK=100,d0='<?xml version="1.0" encoding="utf-16"?>',lO=1033,AO="mxswa:Workflow",MK="mxswa:ActivityReference.Properties",BK="mcwo:StepLabel",$K="mcwb:Control",uO="mcwb:Control.ControlDisplayName",EO="mcwb:Control.DataFieldName",CO="DataFieldName",cO="ControlDisplayName",SO="Literal",_d="x:Null",dO="x:String",p0="x:Key",f0="DisplayName",Td="Activities",UK="StepLabels",NO="StageId",DO="StageCategory",_O="NextStageId",IO="ProcessStepId",m0="IsProcessRequired",TO="EntityComposite",PO="StageComposite",RO="StepComposite";function c0(e){return(0,er.isJsonObject)(e)?e:{}}function dn(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function ho(e,t){var r;return(r=dn(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function pn(e){return ho(e,MK)}function It(e,t){var r;return(r=dn(e).find(n=>n.getAttribute(p0)===t))!==null&&r!==void 0?r:null}function qa(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Un(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function OO(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function yl(e){var t;let r=(t=e.getAttribute(f0))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function xO(e,t){var r;let n=(r=e.getAttribute(f0))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(f0,i>=0?n.slice(0,i+2)+t:t)}function LO(e,t){let r=It(e,UK),n=ho(r,BK);n&&n.setAttribute("Description",t)}function qK(e){let t=It(e,DO);if(!t||t.tagName===_d)return;let r=Un(t).trim();return r===""?void 0:Number(r)}function VK(e){let t=It(e,_O);if(!t||t.tagName===_d)return;let r=Un(t).trim();return r===""?void 0:r}function kO(e){let t=FO(e);if(!t)return;let r=BO(t,CO,EO);return r===""?void 0:r}function h0(e,t){let r=dn(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of dn(n))r.push(i)}return null}function FO(e){let t=It(pn(e),Td);return t?h0(t,$K):null}function MO(e,t){let r=e.attributes;for(let n=0;n<r.length;n+=1)if(r[n].name===t)return!0;return!1}function BO(e,t,r){var n;return MO(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":HK(e,r)}function pO(e,t,r,n){if(MO(e,t)){e.setAttribute(t,n);return}if(ho(e,r)){GK(e,r,n);return}throw new cn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function GK(e,t,r){let n=ho(e,t),i=n?h0(n,SO):null;i&&i.setAttribute("Value",r)}function $O(e){return yl(e)}function Pd(e){let t=ho(e,AO),r=[];for(let n of dn(t).filter(i=>qa(i,TO))){let i=It(pn(n),Td);for(let o of dn(i).filter(a=>qa(a,PO)))r.push({el:o,entity:$O(n)})}return r}function g0(e){let t=It(pn(e),Td);return dn(t).filter(r=>qa(r,RO))}function zK(e){let t=pn(e),r=Un(It(t,m0)).trim().toLowerCase(),n=kO(e),i={id:Un(It(t,IO)),name:yl(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function WK(e,t){let r=pn(e),n=qK(r),i=VK(r),o={id:Un(It(r,NO)),name:yl(e),entityLogicalName:t,steps:g0(e).map(zK)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function jK(e){return Pd(e).map(({el:t,entity:r})=>WK(t,r))}function $n(e){return new cn.NotImplementedError("bpf-structural-authoring",`${e} is not supported yet (this phase authors identity, stage/step names, step required, step field binding, stage categories, and adding/removing/reordering stages & steps on a single-table process; branching, actions, security-role wiring and multi-table processes land in later phases). The rest of the process round-trips losslessly.`)}function HK(e,t){var r;let n=ho(e,t),i=n?h0(n,SO):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function v0(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(v0(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function UO(e){return It(pn(e),Td)}function KK(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,jt.newId)(),{body:a}=Rd(y0(i,(0,jt.newId)(),t.id,o));return v0(e,Pd((0,mo.parseXmlRoot)(a,"<Activity/>"))[0].el)}function JK(e,t){let{body:r}=Rd(y0("account",(0,jt.newId)(),(0,jt.newId)(),t.id));return v0(e,g0(Pd((0,mo.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function qO(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function VO(e,t,r,n){let i=It(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw $n(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==_d){let s=t.createElement(_d);s.setAttribute(p0,r),o.replaceChild(s,i)}return}if(i.tagName===dO){Un(i)!==n&&OO(i,t,n);return}let a=t.createElement(dO);a.setAttribute(p0,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function QK(e,t,r){VO(e,t,DO,r===void 0?void 0:String(r))}function XK(e,t,r){VO(e,t,_O,r)}function GO(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(r(e[n])!==t[n])return!1;return!0}function fO(e){return Un(It(pn(e),NO))}function mO(e){return Un(It(pn(e),IO))}function hO(e,t,r){var n,i,o,a;let s=pn(e);r.name!==yl(e)&&(xO(e,r.name),LO(s,r.name));let l=Un(It(s,m0)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=It(s,m0);u&&OO(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=kO(e))!==null&&o!==void 0?o:"")){let u=FO(e);if(!u)throw new cn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";pO(u,CO,EO,c),c!==""&&BO(u,cO,uO)===""&&pO(u,cO,uO,c)}}function gO(e,t,r,n){var i;let o=pn(e);if(!o)throw new cn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==yl(e)&&(xO(e,r.name),LO(o,r.name)),QK(o,t,r.category),XK(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw $n("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw $n("stage actions or conditional branching");let a=UO(e);if(!a)throw new cn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new cn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=g0(e);if(GO(l,s.map(d=>d.id),mO)){l.forEach((d,p)=>hO(d,t,s[p]));return}let u=new Map(l.map(d=>[mO(d),d]));if(dn(a).some(d=>!qa(d,RO)))throw $n("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var p;return(p=u.get(d.id))!==null&&p!==void 0?p:JK(t,d)});qO(a,c),c.forEach((d,p)=>hO(d,t,s[p]))}function YK(e,t,r){let n=ho(e,AO);if(!n)throw new cn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw $n("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new cn.InvalidArgumentError("a BPF must have at least one stage");let i=Pd(e),o=i.map(p=>p.el);if(GO(o,r.stages.map(p=>p.id),fO)){i.forEach(({el:p,entity:f},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==f)throw $n(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${f}')`);gO(p,t,h,h.nextStageId)});return}let a=dn(n).filter(p=>qa(p,TO));if(a.length!==1)throw $n("adding, removing or reordering stages on a multi-table process");let s=a[0],l=$O(s),u=UO(s);if(!u)throw new cn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(dn(u).some(p=>!qa(p,PO)))throw $n("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let p of r.stages)if(p.entityLogicalName&&p.entityLogicalName.trim()!==""&&p.entityLogicalName!==l)throw $n(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(p=>[fO(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:KK(t,p,l)});qO(u,d),d.forEach((p,f)=>{let m=f<d.length-1?r.stages[f+1].id:void 0;gO(p,t,r.stages[f],m)})}function Rd(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function ZK(e){var t,r,n,i,o,a;(0,wO.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,u0.mergeAttrs)(s.a,[]),c:(0,u0.spliceChildren)(s.c,[])};return{root:(0,u0.rebuildRaw)(f,(0,mo.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:d0,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=y0(e.entityLogicalName,(0,jt.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,jt.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,jt.newId)()),{body:d}=Rd(c);return{root:(0,mo.parseXmlRoot)(d,"<Activity/>"),prolog:d0,eol:"lf"}}function eJ(e){let{root:t,prolog:r,eol:n}=ZK(e);YK(t,t.ownerDocument,e);let i=(0,mo.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
+`)),r+i}function tJ(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Id=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,wO.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Rd(o),u=(0,mo.parseXmlRoot)(l,"<Activity/>");a.stages=jK(u),a.bag={xaml:(0,mo.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,jt.newId)(),name:t.name,uniquename:tJ(t),primaryentity:t.entityLogicalName,xaml:eJ(t),category:Dd.WorkflowCategory.BusinessProcessFlow,type:Dd.WorkflowTypeCode.Definition,businessprocesstype:Dd.BusinessProcessType.BusinessFlow,scope:Dd.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:FK};t.description!==void 0&&(n.description=t.description);let i={record:n,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new cn.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(yO):[yO({id:(0,jt.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,jt.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=c0(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,jt.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,er.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof n}`)),r;let i=Array.isArray(n)?n:[];i.length>30&&r.push((0,er.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=c0(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,er.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(p.toLowerCase())?r.push((0,er.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${a.get(p.toLowerCase())})`)):a.set(p.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&o.add(l.entityLogicalName);let f=Array.isArray(l.steps)?l.steps:[];f.length===0&&r.push((0,er.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,er.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let m=new Map;f.forEach((h,g)=>{let y=`${c}/steps/${g}`,w=typeof c0(h).id=="string"?h.id.trim():"";w===""?r.push((0,er.issue)(`${y}/id`,"step-id-required","a step needs an id")):m.has(w.toLowerCase())?r.push((0,er.issue)(`${y}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(w.toLowerCase(),g)}),l.branch&&!vO(i,l.branch.nextStageId)&&r.push((0,er.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!vO(i,l.nextStageId)&&r.push((0,er.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,er.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=rJ(i);return s>=0&&r.push((0,er.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Va.BpfAdapter=Id;function rJ(e){let t=new Map(e.map(r=>[r.id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function vO(e,t){return e.some(r=>r.id===t)}function yO(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(bO):[bO({id:(0,jt.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,jt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(r=e.entityLogicalName)!==null&&r!==void 0?r:"",steps:n};return e.category!==void 0&&(i.category=e.category),e.nextStageId!==void 0&&(i.nextStageId=e.nextStageId),e.relationshipName!==void 0&&(i.relationshipName=e.relationshipName),e.actions!==void 0&&(i.actions=e.actions),e.branch!==void 0&&(i.branch=e.branch),i}function bO(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,jt.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(r.fieldName=e.fieldName),e.required!==void 0&&(r.required=e.required),r}function y0(e,t,r,n){return`${d0}<Activity x:Class="XrmWorkflow00000000000000000000000000000000" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mcwb="clr-namespace:Microsoft.Crm.Workflow.BusinessProcessFlowActivities;assembly=Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mcwo="clr-namespace:Microsoft.Crm.Workflow.ObjectModel;assembly=Microsoft.Crm, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxs="clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxswa="clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:srs="clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:this="clr-namespace:" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><x:Members><x:Property Name="InputEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /><x:Property Name="CreatedEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /></x:Members><this:XrmWorkflow00000000000000000000000000000000.InputEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.InputEntities><this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings><mxswa:Workflow><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.EntityComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="EntityStep1: ${e}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StageComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StageStep2: New Stage"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StepComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StepStep3: New Step"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><Sequence DisplayName="ControlStep4"><mcwb:Control ControlId="${t}" IsSystemControl="False" IsUnbound="False" SystemStepType="0"><mcwb:Control.ClassId><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ClassId><mcwb:Control.ControlDisplayName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ControlDisplayName><mcwb:Control.DataFieldName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.DataFieldName><mcwb:Control.Parameters><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.Parameters></mcwb:Control></Sequence></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Step" LabelId="${n}" LanguageCode="${lO}" /></sco:Collection><x:String x:Key="ProcessStepId">${n}</x:String><x:Boolean x:Key="IsProcessRequired">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Stage" LabelId="${r}" LanguageCode="${lO}" /></sco:Collection><x:String x:Key="StageId">${r}</x:String><x:Null x:Key="StageCategory" /><x:Null x:Key="NextStageId" /></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><x:Null x:Key="RelationshipName" /><x:Null x:Key="AttributeName" /><x:Boolean x:Key="IsClosedLoop">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></mxswa:Workflow></Activity>`}function nJ(){return{adapter:new Id,api:kK.bpfApi,languageSensitive:!0}}Va.bpfRegistration=nJ});var WO=b(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.buildRegistrations=void 0;var iJ=cT(),oJ=IT(),aJ=tP(),sJ=yP(),lJ=MP(),uJ=rR(),cJ=bR(),dJ=QR(),pJ=zO();function fJ(e){let t=new Map;return t.set("form",(0,iJ.formRegistration)(e)),t.set("view",(0,oJ.viewRegistration)()),t.set("businessRule",(0,aJ.businessRuleRegistration)()),t.set("app",(0,sJ.appRegistration)(e)),t.set("command",(0,lJ.commandRegistration)()),t.set("chart",(0,uJ.chartRegistration)()),t.set("dashboard",(0,cJ.dashboardRegistration)(e)),t.set("genPage",(0,dJ.genPageRegistration)()),t.set("bpf",(0,pJ.bpfRegistration)()),t}Od.buildRegistrations=fJ});var e1=b(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.removeRowSummary=Fe.configureRowSummary=Fe.buildGptDynamicPrompt=Fe.setAppAiFeatures=Fe.getAiReadiness=Fe.saveSettingValue=Fe.retrieveSetting=Fe.AI_GATE=void 0;var Fr=be(),qe=ae(),jO=lt(),qn=re();Fe.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var QO={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},mJ=new Set(Object.entries(Fe.AI_GATE).filter(([e,t])=>QO[e]===t).map(([e])=>e)),hJ={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function b0(e){return hJ[e]}var xd=1e6;function gJ(e,t){let r=b0(t),n=()=>{throw new qn.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${xd} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>xd?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(xd).length||Number(s)>xd?n():s}}return n()}function vJ(e,t){let r=b0(t);return r?e===r.enabled:e!=="0"}async function yJ(e,t){var r,n,i;let o=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,a=await e.get(o);return a.status>=200&&a.status<300?(i=((n=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function bJ(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new qn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new qn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new qn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new qn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var HO=new WeakMap;async function wJ(e,t){var r,n,i;let o=HO.get(e);if(o||(o=new Map,HO.set(e,o)),o.has(t))return o.get(t);let a=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,s=await e.get(a),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&o.set(t,l),l}async function AJ(e,t,r){var n,i;let o=await wJ(e,r);if(!t||!o)return;let a=`/appsettings${(0,qe.odataQuery)([["$select","value"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(i=(n=s.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];return l.length>0?{exists:!0,value:l[0].value}:{exists:!1}}var EJ=4,CJ=500,KO=20,JO=3e4;function SJ(e){if(e===void 0)return EJ;if(!Number.isFinite(e))throw new qn.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${KO}; got ${e}.`);return Math.min(KO,Math.max(1,Math.floor(e)))}function NJ(e){if(e===void 0)return CJ;if(!Number.isFinite(e))throw new qn.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${JO}; got ${e}.`);return Math.min(JO,Math.max(0,Math.floor(e)))}async function DJ(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(f=>setTimeout(f,a*d));let p;try{let f=await t();f?(p=await AJ(e,f,n),p===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(f){p=void 0,u=f.message}c=p!==void 0,l=p?.exists;try{s=(await Ld(e,n,{appUniqueName:r})).value}catch{}if(p?.exists&&p.value===i)return{result:"proven",effectiveValue:p.value,appOverrideExists:!0}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function XO(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?b0(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Ld(e,t,r={}){var n,i;let o=[`SettingName='${(0,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&o.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let a=`/RetrieveSetting(${o.join(",")})`,l=(i=(n=(0,Fr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Fe.retrieveSetting=Ld;async function YO(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Fr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Fe.saveSettingValue=YO;async function _J(e,t={}){let r={};for(let[n,i]of Object.entries(Fe.AI_GATE)){let{value:o,dataType:a}=await Ld(e,i,t);r[n]={enabled:XO(o,a,n),setting:i,value:o}}return r}Fe.getAiReadiness=_J;async function IJ(e,t,r,n={}){var i,o;if(!t||!t.trim())throw new qn.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let a=SJ(n.verifyAttempts),s=NJ(n.verifyDelayMs),l=[];for(let[h,g]of Object.entries(r)){if(g===void 0)continue;let y=QO[h];y&&l.push({feature:h,setting:y,requestedValue:gJ(g,h)})}let u=[],c=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await bJ(e,t);if(h&&(0,qe.normalizeGuid)(h,"appModuleId")!==c)throw new qn.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,p=async()=>c||(d||(d=await yJ(e,t)),d),f=new Map,m=async h=>{if(mJ.has(h))return;let g=Fe.AI_GATE[h];if(g){if(!f.has(g))try{let{value:y,dataType:w}=await Ld(e,g);f.set(g,{enabled:XO(y,w,h),setting:g,value:y})}catch{f.set(g,void 0)}return f.get(g)}};for(let{feature:h,setting:g,requestedValue:y}of l)try{await YO(e,g,y,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let w=await DJ(e,p,t,g,y,a,s),C={feature:h,setting:g,requestedValue:y,effectiveValue:w.effectiveValue,appOverrideExists:w.appOverrideExists};if(w.result==="proven")u.push({...C,status:"applied"});else if(w.result==="absent"){let S=vJ(y,h)?await m(h):void 0;S&&!S.enabled?u.push({...C,status:"skipped",reason:`the write was issued and no app-scope override holding '${y}' was observed for '${g}' after ${a} attempt(s); the org readiness gate '${S.setting}' reads '${S.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...C,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${y}' was observed for '${g}' after ${a} attempt(s) \u2014 it reads '${(i=w.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...C,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=w.reason)!==null&&o!==void 0?o:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(w){u.push({feature:h,setting:g,requestedValue:y,status:"failed",reason:w.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}Fe.setAppAiFeatures=IJ;var TJ="GptPowerPrompt",PJ='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function ZO(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Fe.buildGptDynamicPrompt=ZO;async function RJ(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,Fr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function OJ(e,t,r={}){var n,i,o,a,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,Fr.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(c)return{modelId:c._aimodel_value,aiSkillConfigId:c.aiskillconfigid};let d=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${TJ}'`],["$top",1]])}`,p=((s=(a=(o=(0,Fr.ensureSuccess)(await e.get(d),e.apiUrl(d)).body)===null||o===void 0?void 0:o.value)===null||a===void 0?void 0:a[0])!==null&&s!==void 0?s:{}).msdyn_aitemplateid,f=(0,jO.newId)(),m=(0,jO.newId)(),h=JSON.stringify(ZO(t)),g={ModelId:f,RunConfigurationId:m,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:h,Source:PJ,RunConfiguration:""};(0,Fr.ensureSuccess)(await e.post("/AIModelPublish",g),e.apiUrl("/AIModelPublish"));try{let y=await RJ(e,t.entityLogicalName),w={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${y})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},C=(0,Fr.ensureSuccess)(await e.post("/aiskillconfigs",w),e.apiUrl("/aiskillconfigs")),S=(0,Fr.requireCreatedId)(C,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:S}}catch(y){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw y}}Fe.configureRowSummary=OJ;async function xJ(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=((n=(r=(0,Fr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!a)return;let s=(0,qe.normalizeGuid)(a.aiskillconfigid,"aiskillconfigid"),l=a._aimodel_value?(0,qe.normalizeGuid)(a._aimodel_value,"_aimodel_value"):void 0,u=`/aiskillconfigs(${s})`;if((0,Fr.ensureSuccess)(await e.delete(u),e.apiUrl(u)),l){let c=`/msdyn_aimodels(${l})`;(0,Fr.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Fe.removeRowSummary=xJ});var n1=b(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.findArtifact=Ga.resolveArtifact=void 0;var dt=ae(),Vn=vu(),LJ=Nu(),kJ=Rt(),FJ=be(),t1=re();async function r1(e,t,r){let n="/uxagentprojects"+(0,dt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,dt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,kJ.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function MJ(e,t,r){var n,i,o,a,s,l,u,c,d,p,f,m,h;switch(t){case"app":{let g=(0,LJ.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,dt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),w=(i=(0,FJ.ensureSuccess)(await e.get(g),e.apiUrl(g)).body)===null||i===void 0?void 0:i.value,C=w&&w[0];return C?[{id:String(C.appmoduleid),name:String(C.name),appModuleIdUnique:String(C.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Vn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"command":{let g=await(0,Vn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,dt.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return g&&g.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Vn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,dt.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"chart":return(await(0,Vn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,dt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,dt.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryvisualizationid),name:String(y.name)}));case"view":return(await(0,Vn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,dt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,dt.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryid),name:String(y.name)}));case"webResource":return(await(0,Vn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,dt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(y=>({id:String(y.webresourceid),name:String(y.name)}));case"solution":return(await(0,Vn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,dt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(y=>({id:String(y.solutionid),name:String(y.uniquename)}));case"genPage":return r1(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}Ga.resolveArtifact=MJ;async function BJ(e,t,r){var n,i,o,a,s,l,u;let c=(0,dt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,dt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let g=await(0,Vn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,dt.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return g&&g.length?String(r.entity):null}if(t==="genPage"){let g=await r1(e,(a=r.name)!==null&&a!==void 0?a:"",2);if(g.length>1)throw new t1.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",g.length);return g.length===1?g[0].id:null}let p=$J(t,c,d,r),f=t!=="app",m=await(0,Vn.queryRecords)(e,p.set,{select:[p.idField],filter:p.filter,top:f?2:1});if(f&&m&&m.length>1)throw new t1.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][p.idField];return h!=null?String(h):null}Ga.findArtifact=BJ;function $J(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,dt.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var o1=b(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});Fd.seedRecordGraph=void 0;var i1=vu(),UJ=Vl(),kd=ae(),qJ=re();async function VJ(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(p=>(0,UJ.resolveEntitySetName)(e,p)),c={},d=p=>{var f;return(f=c[p])!==null&&f!==void 0?f:l[p]};for(let p of t){let f=p.entityLogical.toLowerCase(),m=(o=p.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let O of p.records){let k={...O.body};for(let F of(a=O.binds)!==null&&a!==void 0?a:[]){let P=F.parentEntity.toLowerCase(),q=(s=d(P))===null||s===void 0?void 0:s[F.parentIndex];if(!q)throw new qJ.InvalidArgumentError(`Cannot resolve bind '${F.navProperty}' on a '${f}' record: parent '${F.parentEntity}'[${F.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let V=(0,kd.assertODataName)(await u(P),`entity set for parent '${F.parentEntity}'`),Ve=(0,kd.normalizeGuid)(q,`parent id for bind '${F.navProperty}'`);k[`${F.navProperty}@odata.bind`]=`/${V}(${Ve})`}h.push(k)}let g=m?h.map(O=>{let k=O[m];return k!=null&&k!==""?String(k):null}):h.map(()=>null),y=new Map;if(m){let O=(0,kd.assertODataName)(m,"RecordGraph matchOn key"),k=[...new Set(g.filter(F=>F!==null))];if(k.length){let F=k.map(q=>`${O} eq '${(0,kd.odataLiteral)(q)}'`).join(" or "),P=await(0,i1.queryRecords)(e,f,{select:[O,`${f}id`],filter:F,top:5e3});for(let q of P??[]){let V=q[O];V!=null&&y.set(String(V).toLowerCase(),String(q[`${f}id`]))}}}let w=[],C=new Map,S=h.map((O,k)=>{let F=g[k];if(F&&y.has(F.toLowerCase()))return null;if(F){let P=F.toLowerCase(),q=C.get(P);if(q!==void 0)return q;let V=w.push(O)-1;return C.set(P,V),V}return w.push(O)-1}),T=w.length?await(0,i1.createRecordsBulk)(e,f,w):[];c[f]=h.map((O,k)=>{let F=g[k];return F&&y.has(F.toLowerCase())?y.get(F.toLowerCase()):T[S[k]]})}return{createdIds:c}}Fd.seedRecordGraph=VJ});var h1=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.getEntityPrivileges=bt.addEntityPrivilegesToRole=bt.deleteSecurityRole=bt.createPersonaRole=bt.createSecurityRole=bt.SDK_ROLE_MARKER=void 0;var Mr=be(),nt=ae(),tr=re(),Md={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},A0={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},a1={user:1,businessUnit:2,parentChild:3,organization:4},w0={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};bt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function GJ(e){return Object.prototype.hasOwnProperty.call(Md,e)?Md[e]:void 0}function zJ(e){return Object.prototype.hasOwnProperty.call(A0,e)}var s1=new WeakMap,l1=new WeakMap;async function d1(e,t){var r,n;(0,nt.assertODataName)(t,"entity logical name");let i=s1.get(e);i||(i=new Map,s1.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,nt.odataPathLiteral)(t)}')${(0,nt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Mr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new tr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function WJ(e){var t,r,n;let i=l1.get(e);if(i)return i;let o=`/businessunits${(0,nt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Mr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new tr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,nt.normalizeGuid)(l,"businessUnitId");return l1.set(e,u),u}async function p1(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new tr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!zJ(o))throw new tr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await d1(e,i.entity);for(let s of i.access){let l=GJ(s);if(!l)throw new tr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(m=>m.PrivilegeType===l);if(!u)throw new tr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=w0[o];if(u[c]===!1)throw new tr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,nt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),p=n.get(d);if(!p){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(p.scope===o){p.entities.add(i.entity);continue}if(!(p.entities.size===1&&p.entities.has(i.entity))){let m=[...p.entities].sort().join(", ");throw new tr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}p.scope=a1[o]>a1[p.scope]?o:p.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function jJ(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:A0[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Mr.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function u1(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,nt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Mr.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function HJ(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,nt.normalizeGuid)(l,"teamId");if(!await u1(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Mr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,nt.normalizeGuid)(l,"userId");if(!await u1(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Mr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function c1(e,t,r){var n,i;let o=`/roles${(0,nt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,nt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Mr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var p;return d.ismanaged!==!0&&((p=d.description)!==null&&p!==void 0?p:"")===bt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new tr.InvalidArgumentError(`A role named '${t}' already exists in this business unit and was not created by the SDK; refusing to modify or assign it. Choose a different persona/role name.`);if(l.length>1)throw new tr.InvalidArgumentError(`Multiple (${l.length}) SDK-owned roles named '${t}' exist in this business unit; refusing to reuse one arbitrarily. Remove the duplicate role(s) and retry.`);let c=l[0].roleid;return c?(0,nt.normalizeGuid)(c,"roleId"):void 0}function KJ(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,nt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,nt.normalizeGuid)(n,"userId"))}}function f1(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function m1(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,nt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await WJ(e),a=await p1(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=KJ(t.assignTo),l=await c1(e,i,o),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:bt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let f=(0,Mr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,nt.normalizeGuid)((0,Mr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let m;try{m=await c1(e,i,o)}catch{m=void 0}if(!m)throw f;l=m}}await jJ(e,l,a,u);let c=await HJ(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:f1(a),assignedTeams:c.teams,assignedUsers:c.users}}bt.createSecurityRole=m1;async function JJ(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return m1(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}bt.createPersonaRole=JJ;async function QJ(e,t){let n=`/roles(${(0,nt.normalizeGuid)(t,"roleId")})`;(0,Mr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}bt.deleteSecurityRole=QJ;async function XJ(e,t,r){let n=(0,nt.normalizeGuid)(t,"roleId");if(r.length===0)throw new tr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await p1(e,r),o={Privileges:i.map(s=>({Depth:A0[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Mr.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),f1(i)}bt.addEntityPrivilegesToRole=XJ;var YJ=new Map(Object.keys(Md).map(e=>[Md[e],e]));async function ZJ(e,t){return(await d1(e,t)).map(n=>{let i=Object.keys(w0).filter(a=>n[w0[a]]!==!1),o=YJ.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}bt.getEntityPrivileges=ZJ});var N1=b(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.createMakerSdk=rr.MakerSdk=rr.PUSH_NOT_ATTEMPTED_CODE=rr.ALREADY_EXISTS_CODE=void 0;var g1=ap(),v1=nr(),ne=re(),Ar=wo(),eQ=Qv(),C1=ry(),bl=ly(),tQ=lp(),rQ=Iy(),E0=Ty(),nQ=Gy(),it=Vl(),y1=mf(),Gn=vu(),Bd=Dw(),za=Au(),iQ=Cu(),Tt=Mw(),oQ=bf(),aQ=Rf(),b1=wf(),sQ=WO(),$d=lt(),lQ=Li(),fn=wg(),zn=dp(),uQ=3e5,Er=be(),Wn=ae(),Wa=e1(),w1=n1(),cQ=o1(),dQ=Fh(),wl=h1(),S1=Symbol("cds-maker-sdk.committedWrite");function pQ(e){return typeof e=="object"&&e!==null&&(e[S1]=!0),e}function fQ(e){return typeof e=="object"&&e!==null&&e[S1]===!0}var mQ=new Set(["entity","appmodule","dashboard","uxagentproject"]);function hQ(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,Wn.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function gQ(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new C1.WorkspaceManager(vQ,e.instanceUrl,(0,tQ.assertStorageContract)(t))}rr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";rr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var vQ="<injected workspaceStorage>",Ud=class{constructor(t){var r,n;this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:lQ.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:uQ,this.compiler={load:(0,oQ.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=gQ(t),this.versions=new bl.VersionManager(this.workspace),this.dataverse=new rQ.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,sQ.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){var i,o,a;let s=this.requireRegistration(t,"fetchArtifact"),{raw:l,etag:u,memberEtags:c,siblingEtags:d}=await s.api.get(this.dataverse,r),p=s.adapter.fromApiResponse(l);if(!n?.overwrite&&await this.versions.isDirty(t,r)){let m=(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&o!==void 0?o:null;if(m&&u&&m!==u)throw new ne.LocalEditsWouldBeLostError(t,r,m,u);let h=await this.workspace.readArtifact(t,r);if(h){let g=await this.versions.getMeta(t,r);if(g&&!g.etag&&u){if(!(0,zn.deepEqual)(g.snapshot,p))throw new ne.LocalEditsWouldBeLostError(t,r,m,u);await this.versions.storeMeta(t,r,{...g,etag:u,fetchedAt:(0,Er.nowIso)()})}return(0,fn.cloneJson)(h)}}await this.workspace.writeArtifact(t,r,p);let f=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:u,languageCode:this.languageCode,projectionVersion:bl.PROJECTION_VERSION,fetchedAt:(0,Er.nowIso)(),snapshot:(0,fn.cloneJson)(p),...c?{memberEtags:c}:{},...d?{siblingEtags:d}:{},...f?.refreshGeneration?{refreshGeneration:f.refreshGeneration,observedGeneration:(a=f.observedGeneration)!==null&&a!==void 0?a:0}:{}}),(0,fn.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,Tt.fetchSolutionComponents)(this.dataverse,t),i=[],o=[];for(let a of n)try{let s=await this.resolveComponentType(a);if(!s){o.push({componentId:a.objectId,componentType:a.componentType,workflowCategory:a.workflowCategory,reason:"unsupported"});continue}let l=await this.fetchArtifact(s,a.objectId);i.push({type:s,id:a.objectId,name:typeof l.name=="string"?l.name:(r=a.displayName)!==null&&r!==void 0?r:a.objectId,entityLogicalName:typeof l.entityLogicalName=="string"?l.entityLogicalName:void 0,lastFetched:(0,Er.nowIso)(),isDirty:!1})}catch(s){o.push({componentId:a.objectId,componentType:a.componentType,workflowCategory:a.workflowCategory,reason:"failed",error:Ii(s)})}return await this.workspace.updateManifest({lastSyncAt:(0,Er.nowIso)()}),{summaries:i,skipped:o}}async fetchEntityMetadata(t){let r=await(0,E0.fetchEntityMetadataFromApi)(this.dataverse,t);return await this.workspace.writeEntityMetadata(t,r),r}generateGenPageRuntimeTypes(t,r){return(0,nQ.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,E0.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,E0.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,it.createTable)(this.dataverse,t)}createColumn(t,r){return(0,it.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,it.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,it.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,it.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,y1.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,y1.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,it.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,it.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,it.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,it.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,it.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,it.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large}),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,Wn.xmlText)(t)}</entity></entities></importexportxml>`;(0,Er.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,it.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,it.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,it.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,it.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,it.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,it.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,it.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,wl.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,wl.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,wl.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,wl.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,wl.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Gn.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Gn.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Gn.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Gn.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Gn.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Gn.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Gn.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,cQ.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,w1.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,w1.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,aQ.deleteAppCascade)(this.dataverse,t,r),i=(0,Wn.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Gn.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Gn.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Bd.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Bd.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Bd.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Bd.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,za.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,za.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ne.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:iQ.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,za.setAppSetting)(this.dataverse,t,za.HEADER_AND_NAVIGATION_REFRESH,r?za.APP_SETTING_ON:za.APP_SETTING_OFF)}getSolution(t){return(0,Tt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Tt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Tt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,Tt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,Tt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,Tt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,Tt.exportSolution)(this.dataverse,t)}importSolution(t){return(0,Tt.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,Tt.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=await this.getArtifactUnlocked(t,r);return await this.acknowledgeRefresh(t,r),n})}async getArtifactUnlocked(t,r){return(0,fn.cloneJson)(await this.readRaw(t,r))}async acknowledgeRefresh(t,r){var n,i,o;let a=this.artifactKey(t,r),s=await this.versions.getMeta(t,r);this.baselineObserved.has(a)||this.baselineObserved.set(a,(n=s?.observedGeneration)!==null&&n!==void 0?n:0);let l=(i=s?.refreshGeneration)!==null&&i!==void 0?i:0;s&&l!==((o=s.observedGeneration)!==null&&o!==void 0?o:0)&&await this.versions.storeMeta(t,r,{...s,observedGeneration:l}),this.observedGenerations.set(a,l)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,C1.canonicalArtifactId)(r)}`}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new ne.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new ne.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new ne.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=await this.versions.getMeta(t,r);if(!n)return"skipped";let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return"fresh";if(await this.versions.isDirty(t,r))return"skipped";let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return(0,zn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.getArtifactUnlocked(t,r),o=Ar.JsonPointer.resolve(i,n);if(o===void 0)throw new ne.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r),o})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,eQ.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.workspace.readEntityMetadata(t);if(!r)throw new ne.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new ne.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=Ar.JsonPointer.resolve(a,n);if(s===void 0)throw new ne.PathNotFoundError(t,r,n);let l=jn(s)&&jn(i)?{...s,...i}:i;return Ar.JsonPointer.set(a,n,(0,fn.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=Ar.JsonPointer.resolve(s,n);if(l===void 0)throw new ne.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!jn(l)||!jn(i))throw new ne.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new ne.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let p of Object.keys(i)){if(p==="id")throw new ne.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let f=(0,fn.cloneJson)(i[p]),m=(0,$d.isValueMapKey)(p)||(0,$d.pointerTouchesValueMap)(n);d[p]=m?f:Array.isArray(f)?f.map(h=>jn(h)?this.assignMissingIds(t,h):h):jn(f)?this.assignMissingIds(t,f):f}for(let p of Object.keys(d))Ar.JsonPointer.set(s,Ar.JsonPointer.append(n,p),d[p]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,$d.pointerTouchesValueMap)(n)?(0,fn.cloneJson)(i):this.assignMissingIds(t,(0,fn.cloneJson)(i)),c=wQ(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=Ar.JsonPointer.resolve(l,n);if(u===void 0)throw new ne.PathNotFoundError(t,r,n);let c=Ar.JsonPointer.resolve(l,i);if(c===void 0)throw new ne.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new ne.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ne.ValidationError(t,r,i,"cannot move an element into its own subtree");Ar.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),E1(c);let p=Ar.JsonPointer.resolve(l,A1(n));return Array.isArray(p)&&p!==c&&E1(p),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(Ar.JsonPointer.resolve(o,n)===void 0)throw new ne.PathNotFoundError(t,r,n);return Ar.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,A1(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new ne.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Wa.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Wa.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Wa.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Wa.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Wa.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Wa.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,dQ.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,v1.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&fQ(c)&&a.push(u),o?(0,ne.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new ne.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new ne.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,fn.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.requireRegistration(t,"deleteRemoteArtifact").api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let f of t){let m=this.artifactKey(f.type,f.id);o.has(m)||o.set(m,{type:f.type,id:f.id})}let a=[];for(let[f,m]of o)a.push(await this.withArtifactLock(m.type,m.id,()=>this.preparePublish(f,m.type,m.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let f of a){let m=((n=f.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=f.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;f.scope&&m&&!u.has(m)&&(u.add(m),l.push(...await this.captureSiblings(f.scope,s)))}let c=hQ(a),d;if(c)try{await(0,v1.publishXml)(this.dataverse,c)}catch(f){d=Ii(f)}let p=new Map;for(let f of a)p.set(f.key,await this.withArtifactLock(f.type,f.id,()=>this.settlePublish(f,d,r)));for(let f of l)await this.withArtifactLock(f.type,f.id,()=>this.adoptBracket(f));return t.map(f=>({...p.get(this.artifactKey(f.type,f.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!mQ.has(s.envelope))throw new ne.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,zn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings(s,new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Ii(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){var i;try{let o=(i=await this.versions.getMeta(r,n))===null||i===void 0?void 0:i.etag;if(!o||!t.api.readToken)return;let{raw:a,etag:s}=await t.api.get(this.dataverse,n);return s!==o||await t.api.readToken(this.dataverse,n)!==o?void 0:{type:r,id:n,reg:t,heldEtag:o,content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i;let o=t.envelope==="entity"?(n=t.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;if(!o)return[];let a=[],s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let l of s){let u=this.registrations.get(l.type);if(r.has(this.artifactKey(l.type,l.id))||u?.rebaselineAfterPublish!=="bracket"||!u.publishScope)continue;try{let d=await this.workspace.readArtifact(l.type,l.id),p=d?u.publishScope(l.id,d):void 0;if(p?.envelope!=="entity"||((i=p.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase())!==o)continue}catch{continue}let c=await this.captureBracket(u,l.type,l.id);c&&a.push(c)}return a}async adoptBracket(t){try{let r=await this.versions.getMeta(t.type,t.id);if(!r||r.etag!==t.heldEtag)return;let{raw:n,etag:i}=await t.reg.api.get(this.dataverse,t.id);if(!i||i===t.heldEtag||!(0,zn.deepEqual)(this.bracketContent(t.reg,n),t.content))return;await this.versions.storeMeta(t.type,t.id,{...r,etag:i,fetchedAt:(0,Er.nowIso)()})}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Ii(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,zn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var p,f,m;return(m=(f=(p=t.adapter).baselineContent)===null||f===void 0?void 0:f.call(p,d))!==null&&m!==void 0?m:d};if(!a||!(0,zn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,Er.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}})}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,Wn.normalizeGuid)(r,"id")})${(0,Wn.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},p=n;if(!p)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let f=[];return((o=p.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&f.push("name"),((s=p.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&f.push("description"),f.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${f.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:Ii(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=p=>{var f,m,h;return(h=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,p))!==null&&h!==void 0?h:p},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,zn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,zn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Ii(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r){var n,i;let o=this.requireRegistration(t,"pushArtifact"),a=await this.readLocal(t,r),s=(i=(n=o.adapter).normalize)===null||i===void 0?void 0:i.call(n,a);s&&s!==a&&(await this.workspace.writeArtifact(t,r,s),a=s);let l=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,l,o),this.assertProjectionMatches(t,r,l);let u=await this.buildMetadataContext(o.adapter,a),c=await o.adapter.toApiPayload(a,l?.snapshot,u);return await this.assertSemanticallyComplete(o,t,r,a,l===null,l?.everActivated),{type:t,id:r,reg:o,json:a,meta:l,payload:c}}async assertSemanticallyComplete(t,r,n,i,o,a){var s;let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,c=u?await this.workspace.readEntityMetadata(u):null,d=((s=c?.attributes)!==null&&s!==void 0?s:[]).map(f=>({logicalName:f.logicalName,displayName:f.displayName,attributeType:f.attributeType,isCustomAttribute:f.isCustomAttribute,...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.options?{options:f.options.map(m=>({value:m.value,label:m.label}))}:{},...f.targets?{targets:f.targets}:{}})),p=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(p.length>0)throw new ne.ValidationError(r,n,p)}async pushArtifactUnlocked(t,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,r))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:p,reg:f,json:m,meta:h,payload:g}=t,y=!1;try{let w=h?await f.api.update(this.dataverse,p,g,h.etag,h.memberEtags,h.siblingEtags):await this.createWithMintedId(f,d,p,g);y=!0;let C=p;h||(w.serverIdentity&&f.adapter.applyServerIdentity&&f.adapter.applyServerIdentity(m,w.serverIdentity),w.id&&w.id!==p&&(m.id=w.id,await this.workspace.deleteArtifact(d,p),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(f,w.readBack):void 0,T=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:f.adapter.committed?f.adapter.committed(m,g,{intentPending:w.intentPending===!0}):{artifact:m,baseline:m};(!h||T.artifact!==m)&&await this.workspace.writeArtifact(d,C,T.artifact);let O=S?.artifact!==void 0&&!(0,zn.deepEqual)(S.artifact,m),k=((r=h?.refreshGeneration)!==null&&r!==void 0?r:0)+(O?1:0),F=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(f,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...k>0?{refreshGeneration:k,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:bl.PROJECTION_VERSION,fetchedAt:(0,Er.nowIso)(),snapshot:(0,fn.cloneJson)(T.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}}),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let q=(P=f.publishScope)===null||P===void 0?void 0:P.call(f,C,m);return q?{publishScope:q}:{}})():{},...O?{refreshed:!0}:{},...F.length>0?{warnings:F}:{}}}catch(w){let C=(0,ne.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},T={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,p,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(T).length>0?{siblingEtags:T}:{}})}if(w instanceof ne.SdkError&&w.code===rr.ALREADY_EXISTS_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof ne.SdkError&&w.code===g1.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof ne.SdkError&&w.code===g1.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof ne.SdkError&&w.code===Er.VERSION_CONFLICT_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,b1.isFailureAfterPrimaryWrite)(w)?w:new ne.VersionConflictError(d,p,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw y?pQ(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ne.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==bl.PROJECTION_VERSION)throw new ne.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${bl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i){try{return await t.api.create(this.dataverse,i,n)}catch(o){throw!(o instanceof ne.SdkError)||o.code!==Er.VERSION_CONFLICT_CODE||(0,b1.isFailureAfterPrimaryWrite)(o)?o:new ne.SdkError(rr.ALREADY_EXISTS_CODE,`Cannot create ${r} '${n}': a record already exists at that id, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${r}', '${n}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`)}}async buildMetadataContext(t,r){var n,i,o;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[],s=new Set(a.map(m=>m.entityLogicalName).filter(m=>!!m)),l=new Set(a.filter(m=>m.needsColumnDetail).map(m=>m.entityLogicalName)),u=new Map;for(let m of s){let h=await this.workspace.readEntityMetadata(m);if(h&&l.has(m)&&(h.columnDetailComplete!==!0||h.attributes.some(g=>typeof g.attributeTypeName!="string"))&&(h=null),!h)try{await this.fetchEntityMetadata(m),h=await this.workspace.readEntityMetadata(m)}catch{}h&&u.set(m,h)}let c=this.languageCode,p=a.some(m=>{var h;if(!m.needsLabel||!m.fieldName)return!1;let g=(h=u.get(m.entityLogicalName))===null||h===void 0?void 0:h.attributes.find(y=>y.logicalName===m.fieldName);return g?.localizedDisplayName!==void 0&&!g.localizedDisplayName[c]})?await this.readBaseLanguage():void 0,f=!((o=t.needsBaseLanguage)===null||o===void 0)&&o.call(t,r)?await this.readBaseLanguage():void 0;return{resolveField:(m,h)=>{let g=u.get(m),y=g?.attributes.find(w=>w.logicalName===h);return y?{displayName:bQ(y,c,p),attributeType:y.attributeType}:void 0},resolveEntity:m=>u.get(m),loadTypeScript:()=>this.compiler.load(),...f!==void 0?{baseLanguageCode:f}:{}}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map;for(let i=0;i<t.length;i+=1){let o=t[i];try{await this.withArtifactLock(o.type,o.id,()=>this.prepareArtifactUnlocked(o.type,o.id))}catch(a){r.set(i,{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ii(a)})}}if(r.size>0)return t.map((i,o)=>{var a;return(a=r.get(o))!==null&&a!==void 0?a:{type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ne.SdkError(rr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let n=[];for(let i of t)try{n.push(await this.pushArtifact(i.type,i.id))}catch(o){n.push({type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ii(o)})}return n}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.workspace.readEntityMetadata(a))try{await this.fetchEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,$d.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case Tt.SolutionComponentType.SavedQuery:return"view";case Tt.SolutionComponentType.SavedQueryVisualization:return"chart";case Tt.SolutionComponentType.AppModule:return"app";case Tt.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case Tt.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,Wn.normalizeGuid)(t,"formId")})${(0,Wn.odataQuery)([["$select","type"]])}`,i=(0,Er.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)),o=Number(i.body.type);return o===0||o===10}async isBusinessFlowWorkflow(t){let n=`/workflows(${(0,Wn.normalizeGuid)(t,"workflowId")})${(0,Wn.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,Er.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n));return Number(i.body.businessprocesstype)===0}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new ne.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};rr.MakerSdk=Ud;function yQ(e){return new Ud(e)}rr.createMakerSdk=yQ;function Ii(e){return e instanceof Error?e:new Error(String(e))}function bQ(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function jn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function A1(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function E1(e){e.length===0||!e.every(t=>jn(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function wQ(e,t){if(t===void 0||t==="end")return e.length;if(t==="start")return 0;if("index"in t)return Math.max(0,Math.min(t.index,e.length));if("before"in t){let n=e.findIndex(i=>jn(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>jn(n)&&n.id===t.after);return r<0?e.length:r+1}});var D1=b(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});qd.ARTIFACT_TYPES=void 0;qd.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var I1=b(_1=>{"use strict";Object.defineProperty(_1,"__esModule",{value:!0})});var P1=b(T1=>{"use strict";Object.defineProperty(T1,"__esModule",{value:!0})});var O1=b(R1=>{"use strict";Object.defineProperty(R1,"__esModule",{value:!0})});var L1=b(x1=>{"use strict";Object.defineProperty(x1,"__esModule",{value:!0})});var F1=b(k1=>{"use strict";Object.defineProperty(k1,"__esModule",{value:!0})});var B1=b(M1=>{"use strict";Object.defineProperty(M1,"__esModule",{value:!0})});var U1=b($1=>{"use strict";Object.defineProperty($1,"__esModule",{value:!0})});var V1=b(q1=>{"use strict";Object.defineProperty(q1,"__esModule",{value:!0})});var z1=b(G1=>{"use strict";Object.defineProperty(G1,"__esModule",{value:!0})});var j1=b(W1=>{"use strict";Object.defineProperty(W1,"__esModule",{value:!0})});var K1=b(H1=>{"use strict";Object.defineProperty(H1,"__esModule",{value:!0})});var Q1=b(J1=>{"use strict";Object.defineProperty(J1,"__esModule",{value:!0})});var Y1=b(X1=>{"use strict";Object.defineProperty(X1,"__esModule",{value:!0})});var ex=b(Z1=>{"use strict";Object.defineProperty(Z1,"__esModule",{value:!0})});var rx=b(tx=>{"use strict";Object.defineProperty(tx,"__esModule",{value:!0})});var ix=b(nx=>{"use strict";Object.defineProperty(nx,"__esModule",{value:!0})});var ax=b(ox=>{"use strict";Object.defineProperty(ox,"__esModule",{value:!0})});var lx=b(sx=>{"use strict";Object.defineProperty(sx,"__esModule",{value:!0})});var cx=b(ux=>{"use strict";Object.defineProperty(ux,"__esModule",{value:!0})});var px=b(dx=>{"use strict";Object.defineProperty(dx,"__esModule",{value:!0})});var fx=b(ce=>{"use strict";var AQ=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Pe=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&AQ(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.createMakerSdk=void 0;var EQ=N1();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return EQ.createMakerSdk}});Pe(D1(),ce);Pe(I1(),ce);Pe(P1(),ce);Pe(O1(),ce);Pe(L1(),ce);Pe(F1(),ce);Pe(B1(),ce);Pe(U1(),ce);Pe(V1(),ce);Pe(z1(),ce);Pe(j1(),ce);Pe(K1(),ce);Pe(Q1(),ce);Pe(Y1(),ce);Pe(Cu(),ce);Pe(ex(),ce);Pe(rx(),ce);Pe(ix(),ce);Pe(ax(),ce);Pe(lx(),ce);Pe(cx(),ce);Pe(px(),ce);Pe(re(),ce)});var S0=b(mn=>{"use strict";var CQ=mn&&mn.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),SQ=mn&&mn.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),gx=mn&&mn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&CQ(t,e,r);return SQ(t,e),t};Object.defineProperty(mn,"__esModule",{value:!0});mn.NodeFileSystemStorage=void 0;var Ke=gx(require("fs")),wt=gx(require("path")),mx=re(),hx=up();async function vx(e){let t;try{t=await Ke.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Ke.promises.unlink(e)}catch{await Ke.promises.rmdir(e)}return}if(!t.isDirectory()){await Ke.promises.unlink(e);return}for(let r of await Ke.promises.readdir(e))await vx(wt.join(e,r));await Ke.promises.rmdir(e)}var C0=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(wt.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Ke.existsSync(r);){n.unshift(wt.basename(r));let i=wt.dirname(r);if(i===r)return wt.resolve(t);r=i}return wt.resolve(Ke.realpathSync(r),...n)}assertWithinRoot(t,r){let n=wt.resolve(this.root),i=wt.resolve(t);if(i!==n&&!i.startsWith(n+wt.sep))throw new mx.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):wt.resolve(this.realPathThroughNearestAncestor(wt.dirname(i)),wt.basename(i));if(a!==o&&!a.startsWith(o+wt.sep))throw new mx.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Ke.existsSync(r))return null;try{return await(0,hx.retryTransientIoAsync)(()=>Ke.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=wt.dirname(n);await Ke.promises.mkdir(i,{recursive:!0});let o=wt.join(i,`.${wt.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Ke.promises.writeFile(o,r,"utf8"),await(0,hx.retryTransientIoAsync)(()=>Ke.promises.rename(o,n))}catch(a){try{Ke.existsSync(o)&&await Ke.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Ke.existsSync(r)&&await Ke.promises.unlink(r)}async deleteByPrefix(t){await vx(this.pathFor(t,!1))}async ensureContainer(t){await Ke.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Ke.existsSync(this.pathFor(t))}};mn.NodeFileSystemStorage=C0});var yx=b(Ht=>{"use strict";var NQ=Ht&&Ht.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),DQ=Ht&&Ht.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),_Q=Ht&&Ht.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&NQ(t,e,r);return DQ(t,e),t};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.loadNodeTypeScript=Ht.createNodeWorkspaceStorage=Ht.NodeFileSystemStorage=void 0;var IQ=S0(),TQ=S0();Object.defineProperty(Ht,"NodeFileSystemStorage",{enumerable:!0,get:function(){return TQ.NodeFileSystemStorage}});function PQ(e){return new IQ.NodeFileSystemStorage(e)}Ht.createNodeWorkspaceStorage=PQ;async function RQ(){return await Promise.resolve().then(()=>_Q(require("typescript")))}Ht.loadNodeTypeScript=RQ});var Hn={};module.exports=$r(Hn);Jn(Hn,de(fx()),module.exports);Jn(Hn,de(yx()),module.exports);
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index b78bc82d3..2958eafd3 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -182,7 +182,7 @@ Carry the resolved mode through subprocesses: when it is unattended, append
pre-build, recovery rerun, and full apply). Do not append `--allow-destructive`
unless destructive authority was supplied independently.
-1. **Prereqs** — `node --version`, `pac help` (≥ 2.7.0).
+1. **Prereqs** — `node --version`, `pac help` (> 2.10.0, the plugin's minimum).
2. **Environment (PAC)** — `pac auth list`. If exactly one / an active profile, **confirm it
(FYI), don't ask**. If several and none active, **ask** which to use. If none, ask the user
to `pac auth create`. Capture the org URL (`pac org who`).
@@ -444,7 +444,8 @@ choices** — a download sets it on every one it recovers, so tearing down a dow
a lookup column from a retained table or deletes a shared option set. Dashboards are found by name, so
teardown deletes only those the app's solution holds, never another app's namesake — and none when the spec
has no real solution to ask (the `Default` a download may leave); it keeps the solution itself while any step
-failed, so a re-run can still tell. **Dry-run by default**; add `--apply
+failed, so a re-run can still tell, and keeps the page manifest while the generative-pages step failed, so a
+re-run still finds the pages the app authored. **Dry-run by default**; add `--apply
--allow-destructive` to actually delete (`--clear-workspace` also prunes `.maker-workspace/`).
**`--allow-destructive` is required for `teardown --apply`** — without it teardown refuses and
touches nothing.
@@ -546,10 +547,10 @@ matches more than one app is refused, listing the candidate unique names rather
This reconstructs the app into `<working-dir>/app-spec.json`. **Round-trip scope — be precise, it is
not everything:**
- **Round-trips:** the sitemap → `appShell` (all subareas + icons), **every** generative page (via
- `pac model genpage download`; names come from the sitemap's `GenPage` subarea titles, so
- Maker-added pages are included) into `pages[]` + their `.tsx`, the referenced entities (minimal —
- the build reuses existing tables), **classic dashboards** (id-passthrough tiles carrying the
- deployed view/chart ids), the icon web resources, and the solution.
+ `pac model genpage download`; the pages are the sitemap's `GenPage` subareas, so Maker-added pages
+ are included, and each keeps its own name and model) into `pages[]` + their `.tsx`, the referenced
+ entities (minimal — the build reuses existing tables), **classic dashboards** (id-passthrough tiles
+ carrying the deployed view/chart ids), the icon web resources, and the solution.
- **Does NOT round-trip:** `forms[]`, `views[]`, `charts[]`, `commands[]` — they come back empty.
All four **survive on the live app** (a rebuild preserves them by discovery), so a plain edit is
safe; they just aren't editable through the downloaded spec. Change them in Maker or a fresh spec.
@@ -610,7 +611,8 @@ child view id. Each step emits `[n/total]`.
designer-grade FormXML/FetchXML/sitemap by reusing the designer's own serializers, and writes via
the Web API using an `az`-token HttpClient. No relay, no designer tab.
- **Dedicated unmanaged solution per app** (review / teardown). **`--publish` gates the final
- *bulk* publish** of the app's entity + app customizations (a `PublishXml` per entity + the app). It
+ *bulk* publish** of the app's entity + app customizations (one `PublishXml` for every entity and the
+ app, which also carries the default-view enrichment's publish, deferred to it). It
does **not** suppress the small **targeted** publishes that edit/finalize paths must run so the change
takes effect — reconciling an existing form or view, wiring form events, placing quick-views,
re-syncing an existing app's sitemap, and finalizing the sitemap after generative pages each publish
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index 04569d885..4d3c1a8d7 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -466,8 +466,8 @@ It returns a single JSON object:
```json
{
"ok": true | false,
- "blocker": null | "usage" | "az_missing" | "az_not_logged_in" | "pac_not_logged_in"
- | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error",
+ "blocker": null | "usage" | "az_missing" | "az_not_logged_in" | "az_timeout" | "pac_not_logged_in"
+ | "pac_timeout" | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error",
"message": "human-readable next step",
"warnings": ["..."],
"azUser": "...", "pacUser": "...", "envUrl": "...",
@@ -486,6 +486,11 @@ It returns a single JSON object:
blocker (run `az login`, etc.).
- **`blocker: "usage"`** is the one exception: the `check-auth.js` command line itself was wrong (a
mistyped flag or a missing value). Fix the invocation and run it again instead of stopping.
+- **`blocker: "az_timeout"`** means the Azure CLI was too slow to answer, not that it is missing or
+ signed out. Retry once; if it recurs on a busy machine, set `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`
+ (milliseconds, default 60000) for the Azure CLI budget.
+- **`blocker: "pac_timeout"`** means `pac org who` did not answer within its fixed 60 s, so the PAC
+ login is unknown, not missing. Retry once. The Azure CLI setting above does not change this budget.
Capture `envUrl` from the result — Phase 2b passes it to the entity-builder.
@@ -903,9 +908,10 @@ foreach ($f in 'prompt.txt', 'agent-message.txt', 'page-name.txt') {
Then write, with the file tool, `<working-dir>/prompt.txt` holding the prompt, `<working-dir>/agent-message.txt` the
agent message and, on a create, `<working-dir>/page-name.txt` the page's display name — each exactly its text (a
trailing line break on the name is ignored). `genpage-upload.js` refuses any of them that is a link, a hard link or a
-folder, but only after the write. The name is the one value passed to pac inline: where pac is installed as a
-`pac.cmd` shim (Windows), a name containing a double quote or `%` is refused before anything is uploaded, so pick
-one without them.
+folder, but only after the write. The name is the one value passed to pac inline. A name containing a straight double
+quote (`"`) is refused before anything is uploaded — pac stores each one as `\"`, in the page and in the navigation
+title it writes — so use typographic quotes (“ ”) or an apostrophe, which are stored exactly. Where pac is installed as
+a `pac.cmd` shim (Windows), a name containing `%` is refused too, so pick one without it.
**Log the invocation into `workflow-log.md` under a `## Phase 6 — Deploy` section before running it.** Record the flags and the prompt-file path, plus the prompt's scope, so the approved text is preserved semantically without embedding arbitrary text as an executable command. Format:
@@ -980,6 +986,13 @@ replaces or clears connector bindings; otherwise omit it to preserve the
deployed page's current bindings. The same rule applies to `--actions` for Custom
API bindings: include it only when this upload intentionally replaces or clears them.
+An update without `--name-file` keeps the page's current display name, and one without `--model` its
+current model: pac would otherwise rename the page to its navigation title and store an empty model, so
+the script reads both from the deployed page and sends them again. If either cannot be read — or the
+name cannot be sent, because pac is a `pac.cmd` shim and the name holds `%` or `"` — the update still
+goes ahead and its result carries a `warnings` entry naming what may have changed; re-run with that value
+passed explicitly.
+
### Phase 6.5: Navigation Fix-Up (Multi-Page Only)
Runs only when the plan has 2+ pages AND any built `.tsx` contains a `PAGEREF_`
diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.md
index 32f224ca0..7aaa498d7 100644
--- a/plugins/model-apps/skills/genpage/edit-flow.md
+++ b/plugins/model-apps/skills/genpage/edit-flow.md
@@ -402,12 +402,16 @@ Omit `--data-sources` when `config.json.dataSources` was empty.
Omit `--connectors` when connector bindings are unchanged.
Omit `--actions` when Custom API bindings are unchanged.
-An update without `--name`/`--name-file` gives the page its **sitemap title** as its name (measured:
-a page renamed with `--name-file` reverted to the title on the next update that omitted it). An edit
-that does not rename the page can omit it. To rename a page, pass `--name-file` on this update, and
-tell the user its navigation title is the app's sitemap entry and is not changed by the upload. Where
-pac is installed as a `pac.cmd` shim (Windows), a name containing a double quote or `%` is refused
-before anything is uploaded.
+An update without `--name`/`--name-file` keeps the page's current name: the script reads it from the
+deployed page and sends it again, because pac would otherwise give the page its **sitemap title** as its
+name (measured: a page renamed with `--name-file` reverted to the title on the next update that omitted
+it). So an edit that does not rename the page omits it. To rename a page, pass `--name-file` on this
+update, and tell the user its navigation title is the app's sitemap entry and is not changed by the
+upload. A name containing a straight double quote (`"`) is refused before anything is uploaded, because
+pac would store each one as `\"`; where pac is installed as a `pac.cmd` shim (Windows), so is a name
+containing `%`. If the current name cannot be read — or cannot be sent, because pac is a `pac.cmd`
+shim and the name holds `%` or `"` — the update still goes ahead and its result carries a `warnings`
+entry; re-run it with `--name-file`.
## Edit Phase 7: Verify (Optional)
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index 6c8f61dab..78345573f 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -446,7 +446,7 @@ This plugin ships 1DS telemetry for skill-run and script-run signals. The canoni
- **Optional telemetry enrichment must load non-fatally.** `detect-site-framework` is required in its own `try/catch` that degrades to `null`, *not* in the hooks' mandatory require block. Bundling optional enrichment there would widen the blast radius of any packaging slip or syntax error from "no framework" to **no telemetry at all**. Apply the same separation to any future optional field.
- **Detection cost scales with the entry count of cwd.** A child miss performs one directory enumeration and at most two marker checks per immediate subdirectory; direct or upward site hits do not scan children. Typical directories cost single-digit ms against the hook's much larger PAC/agent-info work. It runs only *after* the hard-disabled / `isProvisioned` gates; user opt-out still builds the event because the local diagnostic mirror is retained.
- **`eventInfo` keys are independent.** Build the object unconditionally and assign it only when non-empty. Never nest a new key inside the `pacAuth.objectId` guard: that both drops the key on unauthenticated runs and throws on `undefined`, which the fail-closed wrapper swallows into *no event at all*.
-- **The bundled lib copy is CI-guarded.** `scripts/tests/telemetry-lib-copy.test.js` asserts byte-equality with `shared/telemetry/lib` (skipping when `shared/` is absent, i.e. an installed plugin) and exercises the copy's defensive branches — `shared/telemetry/tests` has no workflow, so behavior asserted only there is not CI-covered.
+- **The bundled lib copy is CI-guarded.** `scripts/tests/telemetry-lib-copy.test.js` asserts byte-equality with `shared/telemetry/lib` (skipping when `shared/` is absent, i.e. an installed plugin) and exercises the copy's defensive branches — `shared/telemetry/tests` runs in its own workflow (`shared-telemetry-tests`), which compares this copy's bytes with the source whenever either changes but exercises only the source's behavior.
See `shared/telemetry/README.md` for the integration guide.
diff --git a/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.js b/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.js
index 4cab9638c..580567678 100644
--- a/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.js
+++ b/plugins/power-pages/scripts/tests/telemetry-lib-copy.test.js
@@ -5,14 +5,14 @@
// `plugins/power-pages/scripts/lib/telemetry/lib` is a physical copy of
// `shared/telemetry/lib` (not a symlink — some Windows checkouts and plugin
// hosts materialize symlinks as plain link files, which breaks hook-time
-// require()). Nothing else in CI compares the two: `shared/telemetry/tests` has
-// no workflow, and validate-legacy-compatibility.js only mirrors the marketplace
-// manifests. So an author who edits the shared source and forgets to refresh the
+// require()). shared-telemetry-tests.yml also compares the two (bundled-copies.test.js) when
+// either side changes, and validate-legacy-compatibility.js only mirrors the marketplace
+// manifests. Without a comparison, an author who edits the shared source and forgets to refresh the
// copy gets a green build while the plugin ships stale code.
//
// This suite runs in power-pages-script-tests.yml, so it turns that silent drift
// into a CI failure — and additionally exercises the copy's behavior directly,
-// since the shared suite that normally covers it never runs in CI.
+// since the shared suite (shared-telemetry-tests.yml) only compares the copy's bytes.
const test = require("node:test");
const assert = require("node:assert/strict");
diff --git a/shared/telemetry/README.md b/shared/telemetry/README.md
index 9472c8b32..9bc0b90cb 100644
--- a/shared/telemetry/README.md
+++ b/shared/telemetry/README.md
@@ -186,7 +186,7 @@ shared/telemetry/
│ ├─ prompt-detector.js # parses `/plugin:skill` slash commands from prompt text
│ ├─ scrubber.js # legacy text-scrubbing helper (unused by default — kept for callers that need it)
│ └─ local-log.js # appends every emitted event to ~/.power-platform-skills/telemetry/<plugin>/sessions/<sessionId>/events.jsonl (irrespective of iKey), with 14-day session retention and a 10 MB per-session rollover
-└─ tests/ # node:test coverage for every module above
+└─ tests/ # node:test coverage for every module above; CI: .github/workflows/shared-telemetry-tests.yml
```
---
diff --git a/shared/telemetry/tests/bundled-copies.test.js b/shared/telemetry/tests/bundled-copies.test.js
new file mode 100644
index 000000000..c7513193a
--- /dev/null
+++ b/shared/telemetry/tests/bundled-copies.test.js
@@ -0,0 +1,79 @@
+"use strict";
+
+// Every adopting plugin ships a physical copy of shared/telemetry/lib at
+// plugins/<plugin>/scripts/lib/telemetry/lib, because a marketplace install copies only the
+// plugin directory. Only some adopters guard their copy in their own suite, and those suites
+// run only when the plugin itself changes, so an edit to the shared source that skipped a
+// copy (or an edit to one copy alone) could merge green. The shared-telemetry-tests workflow
+// runs on a change to either side, and this test compares every copy with the source there.
+//
+// Line endings are normalized: a Windows checkout may convert them, and that is not drift.
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const REPO_ROOT = path.resolve(__dirname, "..", "..", "..");
+const SOURCE = path.join(REPO_ROOT, "shared", "telemetry", "lib");
+const COPY_PATH = ["scripts", "lib", "telemetry", "lib"];
+
+function listFiles(dir, prefix = "") {
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ return entry.isDirectory() ? listFiles(path.join(dir, entry.name), rel) : [rel];
+ }).sort();
+}
+
+const text = (file) => fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n");
+
+function copyProblems(source, copy) {
+ const sourceFiles = listFiles(source);
+ const copyFiles = listFiles(copy);
+ const problems = [
+ ...sourceFiles.filter((f) => !copyFiles.includes(f)).map((f) => `missing ${f}`),
+ ...copyFiles.filter((f) => !sourceFiles.includes(f)).map((f) => `extra ${f}`),
+ ];
+ for (const f of sourceFiles) {
+ if (copyFiles.includes(f) && text(path.join(source, f)) !== text(path.join(copy, f))) problems.push(`differs ${f}`);
+ }
+ return problems;
+}
+
+function adopterCopies() {
+ const plugins = path.join(REPO_ROOT, "plugins");
+ return fs.readdirSync(plugins, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => path.join(plugins, entry.name, ...COPY_PATH))
+ .filter((dir) => fs.existsSync(dir));
+}
+
+test("every adopting plugin bundles an identical copy of shared/telemetry/lib", () => {
+ const copies = adopterCopies();
+ assert.ok(copies.length > 0, "found no plugins/*/scripts/lib/telemetry/lib copy; if the layout changed, update this test");
+ const drift = copies.flatMap((copy) => copyProblems(SOURCE, copy)
+ .map((problem) => `${path.relative(REPO_ROOT, copy).split(path.sep).join("/")}: ${problem}`));
+ assert.deepEqual(drift, [], "re-copy shared/telemetry/lib into every adopting plugin");
+});
+
+test("the copy check reports missing, extra and changed files but not line endings", () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-copies-"));
+ try {
+ const source = path.join(root, "source");
+ const copy = path.join(root, "copy");
+ fs.mkdirSync(path.join(source, "nested"), { recursive: true });
+ fs.writeFileSync(path.join(source, "a.js"), "one\ntwo\n");
+ fs.writeFileSync(path.join(source, "nested", "b.js"), "b\n");
+ fs.cpSync(source, copy, { recursive: true });
+ assert.deepEqual(copyProblems(source, copy), []);
+ fs.writeFileSync(path.join(copy, "a.js"), "one\r\ntwo\r\n");
+ assert.deepEqual(copyProblems(source, copy), [], "CRLF alone is not drift");
+ fs.writeFileSync(path.join(copy, "a.js"), "one\ntwo changed\n");
+ fs.rmSync(path.join(copy, "nested", "b.js"));
+ fs.writeFileSync(path.join(copy, "stray.js"), "x\n");
+ assert.deepEqual(copyProblems(source, copy), ["missing nested/b.js", "extra stray.js", "differs a.js"]);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/shared/telemetry/tests/local-log.test.js b/shared/telemetry/tests/local-log.test.js
index 0a5638728..a7d9b3598 100644
--- a/shared/telemetry/tests/local-log.test.js
+++ b/shared/telemetry/tests/local-log.test.js
@@ -5,6 +5,7 @@ const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
+const { spawnSync } = require("node:child_process");
const {
appendLocal,
@@ -246,3 +247,110 @@ test("latestSessionLog returns null when every session dir lacks a log", () => {
fs.mkdirSync(path.join(pluginLogDir(root, "power-pages"), "orphan"), { recursive: true });
assert.equal(latestSessionLog(root, "power-pages"), null);
});
+
+test("appendLocal does not rotate a session log of exactly ROTATE_BYTES", () => {
+ const root = mkTmp();
+ const dir = path.join(root, "telemetry", "power-pages", "sessions", "s1");
+ fs.mkdirSync(dir, { recursive: true });
+ const logFile = path.join(dir, LOG_FILE_NAME);
+ // The cap is exclusive: a file of exactly ROTATE_BYTES must keep growing.
+ // Changing `>` to `>=` would rotate this file and fail the assertion.
+ fs.writeFileSync(logFile, Buffer.alloc(ROTATE_BYTES, 0x78));
+ assert.equal(fs.statSync(logFile).size, ROTATE_BYTES);
+
+ appendLocal(
+ { name: "STILL", data: { pluginName: "power-pages", sessionId: "s1" } },
+ { configDir: root }
+ );
+
+ const olds = fs.readdirSync(dir).filter((f) => f.endsWith(".old"));
+ assert.equal(olds.length, 0);
+ assert.match(fs.readFileSync(logFile, "utf8"), /STILL/);
+});
+
+test("appendLocal swallows a failure to append the session log", () => {
+ const root = mkTmp();
+ const dir = path.join(root, "telemetry", "power-pages", "sessions", "s1");
+ // events.jsonl is a directory, so appendFileSync throws. The catch must
+ // swallow that — telemetry must not break the caller.
+ fs.mkdirSync(path.join(dir, LOG_FILE_NAME), { recursive: true });
+ assert.doesNotThrow(() => {
+ appendLocal(
+ { name: "X", data: { pluginName: "power-pages", sessionId: "s1" } },
+ { configDir: root }
+ );
+ });
+ assert.ok(fs.statSync(path.join(dir, LOG_FILE_NAME)).isDirectory());
+});
+
+test("pruneOldSessions keeps a session at exactly the retention boundary", () => {
+ const root = mkTmp();
+ appendLocal(
+ { name: "edge", data: { pluginName: "power-pages", sessionId: "edge" } },
+ { configDir: root }
+ );
+ const log = sessionLog(root, "power-pages", "edge");
+ const mtime = fs.statSync(log).mtimeMs;
+ const windowMs = MAX_LOG_AGE_DAYS * 24 * 60 * 60 * 1000;
+ // Strict greater-than: an event last written exactly one window ago is kept.
+ pruneOldSessions(root, "power-pages", mtime + windowMs);
+ assert.ok(fs.existsSync(log), "exactly the retention window must be kept");
+ pruneOldSessions(root, "power-pages", mtime + windowMs + 1);
+ assert.equal(fs.existsSync(path.dirname(log)), false, "one millisecond past the window must be pruned");
+});
+
+test("pruneOldSessions leaves the session in place when removal throws", () => {
+ const root = mkTmp();
+ appendLocal(
+ { name: "old", data: { pluginName: "power-pages", sessionId: "old" } },
+ { configDir: root }
+ );
+ const oldLog = sessionLog(root, "power-pages", "old");
+ const oldDir = path.dirname(oldLog);
+ const fifteenDaysAgo = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000);
+ fs.utimesSync(oldLog, fifteenDaysAgo, fifteenDaysAgo);
+ // A locked file makes rmSync throw on some platforms and not others. Force the
+ // throw in a child so the best-effort catch is what this test actually hits,
+ // without patching fs in the test process.
+ const script = path.join(root, "prune-throws.js");
+ fs.writeFileSync(
+ script,
+ [
+ '"use strict";',
+ 'const fs = require("node:fs");',
+ "const { pruneOldSessions } = require(" + JSON.stringify(path.join(__dirname, "../lib/local-log")) + ");",
+ "let called = false;",
+ 'fs.rmSync = () => { called = true; throw new Error("locked"); };',
+ "pruneOldSessions(" + JSON.stringify(root) + ", \"power-pages\");",
+ "if (!called) process.exit(2);",
+ "",
+ ].join("\n")
+ );
+ const result = spawnSync(process.execPath, [script], { encoding: "utf8" });
+ assert.equal(result.status, 0, result.stderr);
+ assert.ok(fs.existsSync(oldDir), "a failed removal must not delete the session or escape");
+});
+
+test("appendLocal tolerates a missing record and still does not throw", () => {
+ const root = mkTmp();
+ assert.doesNotThrow(() => appendLocal(null, { configDir: root }));
+ assert.doesNotThrow(() => appendLocal({}, { configDir: root }));
+ assert.ok(fs.existsSync(sessionLog(root, "unknown", "nosession")));
+});
+
+test("retention and newest-log selection ignore non-directory entries", () => {
+ const root = mkTmp();
+ appendLocal(
+ { name: "real", data: { pluginName: "power-pages", sessionId: "real" } },
+ { configDir: root }
+ );
+ const sessionsRoot = pluginLogDir(root, "power-pages");
+ const stray = path.join(sessionsRoot, "notes.txt");
+ fs.writeFileSync(stray, "not a session");
+ const fifteenDaysAgo = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000);
+ fs.utimesSync(stray, fifteenDaysAgo, fifteenDaysAgo);
+ pruneOldSessions(root, "power-pages");
+ assert.ok(fs.existsSync(stray), "a file in the sessions root is not a session dir");
+ assert.equal(latestSessionLog(root, "power-pages"), sessionLog(root, "power-pages", "real"));
+});
+
diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.js
index 493b925bf..681ddd774 100644
--- a/shared/telemetry/tests/telemetry-config.test.js
+++ b/shared/telemetry/tests/telemetry-config.test.js
@@ -169,3 +169,109 @@ test("off output names the logs directory too", () => {
assert.match(stdout, /local diagnostic log is kept whenever telemetry is enabled/i);
assert.match(stdout, /Logs directory:/);
});
+
+test("status for an unknown plugin does not claim a Power Pages or Model Apps user-id policy", () => {
+ const dir = mkTmp();
+ const { status, stdout } = run(["--action", "status", "--plugin", "contoso-plugin"], dir);
+ assert.equal(status, 0);
+ assert.match(stdout, /Telemetry \(contoso-plugin\): ON/);
+ assert.match(stdout, /hard-disabled and writes no log/);
+ assert.doesNotMatch(stdout, /Power Pages can also record/);
+ assert.doesNotMatch(stdout, /Model Apps excludes/);
+});
+
+test("a flag with no value is a usage error", () => {
+ const dir = mkTmp();
+ const { status, stdout } = run(["--action"], dir);
+ assert.equal(status, 2);
+ assert.match(stdout, /Usage:/);
+});
+
+test("on refuses when the config dir cannot be written", () => {
+ const dir = mkTmp();
+ const blocker = path.join(dir, "not-a-dir");
+ fs.writeFileSync(blocker, "x");
+ const { status, stdout } = run(["--action", "off", "--plugin", "power-pages"], path.join(blocker, "sub"));
+ assert.equal(status, 1);
+ assert.match(stdout, /config dir not writable/);
+ assert.equal(fs.existsSync(path.join(blocker, "sub", "config.json")), false);
+});
+
+test("config dir falls back to the home directory when the env override is unset", () => {
+ const home = mkTmp();
+ const env = { ...process.env, HOME: home, USERPROFILE: home };
+ delete env.POWER_PLATFORM_SKILLS_CONFIG_DIR;
+ // Confirm the child will not resolve the real profile before any write.
+ const probe = spawnSync(process.execPath, ["-e", "process.stdout.write(require('node:os').homedir())"], {
+ encoding: "utf8",
+ env,
+ });
+ assert.equal(path.resolve(probe.stdout), path.resolve(home));
+ const { status, stdout } = spawnSync(process.execPath, [CLI, "--action", "off", "--plugin", "power-pages"], {
+ encoding: "utf8",
+ env,
+ });
+ assert.equal(status, 0, stdout);
+ const cfgPath = path.join(home, ".power-platform-skills", "config.json");
+ assert.equal(JSON.parse(fs.readFileSync(cfgPath, "utf8")).telemetry["power-pages"], "off");
+});
+
+// The CLI looks for the plugin manifest four levels above its own folder. For the
+// shared copy that is the folder containing the repo checkout, so planting a manifest
+// there wrote outside the repository, and two checkouts in one folder raced on the
+// same file. Instead run a temp copy of the library at the depth a plugin bundles it
+// (<plugin>/scripts/lib/telemetry/lib), with the manifest planted in the temp plugin.
+function bundledCliCopy() {
+ const pluginRoot = mkTmp();
+ const lib = path.join(pluginRoot, "scripts", "lib", "telemetry", "lib");
+ fs.cpSync(path.dirname(CLI), lib, { recursive: true });
+ return {
+ cli: path.join(lib, path.basename(CLI)),
+ manifestPath: path.join(pluginRoot, ".claude-plugin", "plugin.json"),
+ };
+}
+
+function runCopy(cli, args, configDir) {
+ return spawnSync(process.execPath, [cli, ...args], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "",
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ },
+ });
+}
+
+function withPlantedManifest(contents, fn) {
+ const { cli, manifestPath } = bundledCliCopy();
+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
+ fs.writeFileSync(manifestPath, contents);
+ fn(cli);
+}
+
+test("omitted --plugin fails closed when no manifest is four levels up", () => {
+ const { cli, manifestPath } = bundledCliCopy();
+ assert.equal(fs.existsSync(manifestPath), false, "this test requires the auto-detect path to miss");
+ const dir = mkTmp();
+ const { status, stdout } = runCopy(cli, ["--action", "status"], dir);
+ assert.equal(status, 2);
+ assert.match(stdout, /Usage:/);
+});
+
+test("omitted --plugin uses a manifest name four levels up", () => {
+ const dir = mkTmp();
+ withPlantedManifest(JSON.stringify({ name: "contoso-plugin" }) + "\n", (cli) => {
+ const { status, stdout } = runCopy(cli, ["--action", "status"], dir);
+ assert.equal(status, 0, stdout);
+ assert.match(stdout, /Telemetry \(contoso-plugin\): ON/);
+ });
+});
+
+test("omitted --plugin fails closed when the manifest has no name", () => {
+ const dir = mkTmp();
+ withPlantedManifest("{}\n", (cli) => {
+ const { status, stdout } = runCopy(cli, ["--action", "status"], dir);
+ assert.equal(status, 2);
+ assert.match(stdout, /Usage:/);
+ });
+});
diff --git a/shared/telemetry/tests/user-config.test.js b/shared/telemetry/tests/user-config.test.js
index ad7221898..13a2fc598 100644
--- a/shared/telemetry/tests/user-config.test.js
+++ b/shared/telemetry/tests/user-config.test.js
@@ -180,3 +180,21 @@ test("isTransmissionOptedOut: config off still opts out with no env var set", ()
setTelemetryChoice(dir, "power-pages", "off");
assert.equal(isTransmissionOptedOut(dir, "power-pages", {}), true);
});
+
+test("readTelemetryChoice returns null when the dir or plugin is missing", () => {
+ const dir = mkTmp();
+ assert.equal(readTelemetryChoice("", "power-pages"), null);
+ assert.equal(readTelemetryChoice(dir, ""), null);
+ assert.equal(setTelemetryChoice("", "power-pages", "off"), false);
+});
+
+test("setTelemetryChoice returns false when config.json cannot be written", () => {
+ const dir = mkTmp();
+ // mkdir of the config dir succeeds; the write itself must fail. A directory
+ // where the file should be makes writeFileSync throw, which the catch turns
+ // into false — a success return here would report a saved choice that is not
+ // on disk.
+ fs.mkdirSync(path.join(dir, CONFIG_FILE_NAME));
+ assert.equal(setTelemetryChoice(dir, "power-pages", "off"), false);
+ assert.equal(readTelemetryChoice(dir, "power-pages"), null);
+});